Add Attachment

Contents
[ ]

File attachments in PDFs allow you to include supplementary documents, images, or other resources directly within the PDF. With PdfContentEditor, you can programmatically attach files to specific pages, set the attachment name, and provide a description.

  1. Create the PdfContentEditor object.
  2. Bind the input PDF.
  3. Open the Attachment file.
  4. Add the Attachment to the PDF.
  5. Save the updated Document.
import aspose.pdf.facades as pdf_facades
import aspose.pydrawing as apd
from io import BytesIO
import sys
from os import path

sys.path.append(path.join(path.dirname(__file__), ".."))

from config import set_license, initialize_data_dir


def add_attachment(infile, attachment_file, outfile):
    # Create PdfContentEditor object
    content_editor = pdf_facades.PdfContentEditor()
    # Bind document to PdfContentEditor
    content_editor.bind_pdf(infile)
    # Add attachment to page 1
    with open(attachment_file, "rb") as attachment_stream:
        content_editor.add_document_attachment(
            attachment_stream,
            path.basename(attachment_file),
            "This is a sample attachment for demonstration purposes.",
        )
    # Save updated document
    content_editor.save(outfile)