Extract Attachments from PDF in Python

How to Extract Attachments from PDF programmatically with Python

How to Extract Attachments Using Python for .NET Library

In order to extract Attachments in PDF file, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for python-net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Console

pip install aspose-pdf

Extract Attachments from PDF Python


You need Aspose.PDF for Python via .NET to try the code in your environment.

  1. Get embedded files collection.
  2. Get count of the embedded files.
  3. Loop through the collection to get all the attachments.
  4. Check if parameter object contains the parameters.
  5. Get the Attachment and write to file or stream.

Extract Attachment from PDF document

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())