Adding Attachment to a PDF document using Python

Contents
[ ]

Attachments can contain a wide variety of information and can be of a variety of file types. This article explains how to add an attachment to a PDF file.

  1. Create a new Python project.
  2. Import the Aspose.PDF package
  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 EmbeddedFileCollection collection, with the collection’s add method.

The EmbeddedFileCollection collection contains all the attachments in the PDF file. The following code snippet shows you how to add an attachment in a PDF document.


    import aspose.pdf as ap

    # Open document
    document = ap.Document(input_pdf)

    # Setup new file to be added as attachment
    fileSpecification = ap.FileSpecification(attachment_file, "Sample text file")

    # Add attachment to document's attachment collection
    document.embedded_files.append(fileSpecification)

    # Save new output
    document.save(output_pdf)