Add Attachments to PDF in Python
Contents
[
Hide
]
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.
Use embedded PDF attachments when you need to package supporting source files, spreadsheets, images, or related documents together with the main PDF.
- Create a new Python project.
- Import the Aspose.PDF package
- Create a Document object.
- Create a FileSpecification object with the file you are adding, and file description.
- 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.
from os import path
import aspose.pdf as ap
def add_attachments(infile, attachment_path, outfile):
with ap.Document(infile) as document:
file_spec = ap.FileSpecification(attachment_path, "Sample text file")
document.embedded_files.add(path.basename(attachment_path), file_spec)
document.save(outfile)