通过 Python 从 PDF 中提取附件

如何使用 Python 以编程方式从 PDF 中提取附件。

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

为了提取 PDF 文件中的附件,我们将使用 Aspose.PDF for .NET API,这是一款功能丰富、功能强大且易于使用的适用于 python-net 平台的文档处理 API。打开 NuGet 软件包管理器,搜索 aspose.pdf 然后安装。您也可以从软件包管理器控制台使用以下命令。

Console

pip install aspose-pdf

从 PDF 中提取附件 Python


你需要 Aspose.PDF for .NET 才能在你的环境中试用代码。

  1. 获取嵌入式文件集合。
  2. 获取嵌入文件的计数。
  3. 循环浏览集合以获取所有附件。
  4. 检查参数对象是否包含参数。
  5. 获取附件并写入文件或流。

将附件提取到 PDF 文档。

import aspose.pdf as apdf

from os import path

path_infile = path.join(self.data_dir, 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.data_dir, "export_" + file_specification.name), "wb"
    ) as f:
        f.write(file_specification.contents.readall())