Work with Attachments in PDF using Python

How to Get, Add, Save, and Delete Attachments from PDF programmatically with Python

How to Manage Attachments Using Python for .NET Library

In order to add 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

Work with Attachments in PDF using Python


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

  1. Create a new Python project.
  2. Add a reference to Aspose.PDF DLL.
  3. Create a Document object.
  4. Create a FileSpecification object with the file you are adding, and file description.
  5. Add the FileSpecification object to the Document object’s EmbeddedFiles collection, with the collection’s Add method
  6. Save the PDF file.

Adding Attachment to PDF document

import aspose.pdf as apdf

from os import path

path_infile = path.join(self.data_dir, infile)
path_outfile = path.join(self.data_dir, outfile)

# Open document
document = apdf.Document(path_infile)

# Setup new file to be added as attachment
attachment_file_name = "file_example.txt"
attachment_path = path.join(self.data_dir, attachment_file_name)
file_specification = apdf.FileSpecification(attachment_path, "Sample text file")

# Add attachment to document's attachment collection
document.embedded_files.add(attachment_file_name, file_specification)

# Save new output
document.save(path_outfile)