通過Python處理 PDF 文件中的圖像

現代 Python 庫,用於使用我們的 API 操作 PDF 中的圖像。

使用 Python 庫將圖像添加到 PDF 文件

為了在PDF中添加圖像,我們將使用[Aspose.PDF用於.NET](https://products.aspose.com/pdf/net)API,這是一個功能豐富,功能強大且易於使用的文檔操作API,適用於 python-net 平臺。打開 [NuGet](https://www.nuget.org/packages/aspose.pdf) 包管理器,搜索“.PDF”並安裝。您也可以從程式包管理器主控台使用以下命令。

Python Package Manager Console

pip install aspose-pdf

通過Python將圖像添加到 PDF


您需要 [Aspose.PDF python](https://releases.aspose.com/pdf/net)來嘗試環境中的代碼。

  1. 建立一個文件物件並打開輸入的 PDF 文件。
  2. 取得要新增影像的頁面。
  3. 將影像添加到頁面的資源集合中。
  4. 使用 GSave 運算子保存當前圖形狀態。
  5. 使用串聯矩陣運算子指定要放置影像的位置。
  6. 使用 Do 運算子在頁面上繪製圖像。
  7. 使用 GRestore 運算子保存更新的圖形狀態。
  8. 保存 PDF 檔。

在現有 PDF 檔案中加入影像 - Python。

Example: Python

    import aspose.pdf as ap 
   
    input_file = DIR_INPUT + "sample.pdf"
    output_pdf = DIR_OUTPUT + "add_image.pdf"
    image_file = DIR_INPUT + "logo.jpg"
    # Open document
    document = ap.Document(input_file)

    document.pages[1].add_image(image_file, ap.Rectangle(20, 730, 120, 830, True))

    document.save(output_pdf)