通过 Python 从 PDF 中提取附件

如何使用 Python以程式設計方式從 PDF 中提取附件。

如何使用 Python for .NET 庫提取附件

為了提取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

從 PDF Python中提取附件


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

  1. 抓取嵌入檔案集合。
  2. 抓取嵌入檔案的計數。 迴圈訪問集合以獲取所有附件。
  3. 檢查參數物件是否包含參數。
  4. 取得附件並寫入檔或流。

將附件提取到 PDF 文件。

import aspose.pdf as apdf
from os import path

path_infile = path.join(self.dataDir, infile)

# Open document
document = apdf.Document(path_infile)

# Get count of the embedded files
print(f"Total files : {len(document.embedded_files)}")

# Loop through the collection to get all the attachments
for file_specification in document.embedded_files:
    print(f"Name: {file_specification.name}")
    print(f"Description: {file_specification.description}")
    print(f"Mime Type: {file_specification.mime_type}")

    # Check if parameter object contains the parameters
    if file_specification.params is not None:
        print(f"CheckSum: {file_specification.params.check_sum}")
        print(f"Creation Date: {file_specification.params.creation_date}")
        print(f"Modification Date: {file_specification.params.mod_date}")
        print(f"Size: {file_specification.params.size}")

    # Get the attachment and write to file
    with open(
        path.join(self.dataDir, "export_" + file_specification.name), "wb"
    ) as f:
        f.write(file_specification.contents.readall())