Work with Attachments in PDF via Python

Add, Extract or Remove Attachments in PDF document. Use Aspose.PDF for Python for .NET to modify PDF documents programmatically

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.

Python Package Manager Console

pip install aspose-pdf

Work with Attachments in PDF via 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

    def attachment_add(self, infile, outfile):

        path_infile = self.dataDir + infile
        path_outfile = self.dataDir + outfile

        # Open document
        pdfDocument = Document(path_infile)

        # Setup new file to be added as attachment
        fileSpecification = FileSpecification(self.dataDir  + "test.txt", "Sample text file")

        # Add attachment to document's attachment collection
        pdfDocument.EmbeddedFiles.Add(fileSpecification)

        # Save new output
        pdfDocument.Save(path_outfile)