Skip to main content

How to Attach Files to a PDF with Python

A PDF does not always have to contain everything directly on its pages.

A project report, for example, may need the original Excel data used to generate its charts. An invoice may need supporting documents, while a technical report may need to include configuration files, logs, or other reference material.

Instead of sending these files separately, they can be embedded directly in the PDF.

There are two useful ways to do this. A file can be attached to the PDF as a whole, or it can be placed at a specific location on a page as an attachment annotation.

This article shows how to handle both cases with Python.


Document Attachments vs. Attachment Annotations

Before adding a file, it helps to understand the difference between the two approaches.

A document-level attachment belongs to the PDF itself. It does not appear in the visible page content. Users typically access it through the Attachments panel in a PDF reader.

An attachment annotation, on the other hand, is placed on a particular page. It appears as a clickable attachment icon, which makes it useful when the attached file relates to a specific paragraph, chart, figure, or section.

For example:

  • Attach an Excel workbook to a financial report as a document-level attachment.

  • Place a source-data file next to a chart as an attachment annotation.

  • Include supporting Word documents with a submitted PDF package.

  • Attach a CSV or JSON file to a technical report while keeping the report itself easy to read.

The main question is whether the attachment needs a visible location within the document.

Environment Setup

To run the following code examples, install the required module for PDF processing:

pip install Spire.PDF

Add a File as a Document-Level Attachment

Suppose we have a PDF report named report.pdf and an Excel workbook named source-data.xlsx.

If the spreadsheet contains supplementary data for the entire report, attaching it at the document level is usually the cleaner option.

from spire.pdf import *

# Load the PDF
pdf = PdfDocument()
pdf.LoadFromFile("report.pdf")

# Create an attachment from an external file
attachment = PdfAttachment("source-data.xlsx")

# Add the attachment to the PDF
pdf.Attachments.Add(attachment)

# Save the result
pdf.SaveToFile("report-with-attachment.pdf")

The attachment itself is created with PdfAttachment:

attachment = PdfAttachment("source-data.xlsx")

It is then added to the document's attachment collection:

pdf.Attachments.Add(attachment)

Nothing is added to the visible PDF pages. In a PDF reader that supports embedded attachments, the spreadsheet can be accessed through the document's Attachments panel.

This makes document-level attachments particularly useful for supplementary material that belongs to the document as a whole.

Attach Multiple Files to a PDF

A PDF can also contain more than one document-level attachment.

For example, a project report could include its source spreadsheet, meeting notes, and an original diagram:

attachment1 = PdfAttachment("source-data.xlsx")
attachment2 = PdfAttachment("notes.docx")
attachment3 = PdfAttachment("diagram.png")

pdf.Attachments.Add(attachment1)
pdf.Attachments.Add(attachment2)
pdf.Attachments.Add(attachment3)

This can be useful when a PDF is intended to serve as a self-contained document package rather than being distributed together with several loose files.

Add an Attachment to a Specific PDF Page

Sometimes an attachment makes more sense when it is associated with a particular location in the document.

Consider a PDF report containing a chart generated from an Excel workbook. Instead of placing the workbook in the general attachment list, we can put an attachment icon next to the chart so readers immediately understand what the file relates to.

This is done with an attachment annotation.

from spire.pdf import *

# Load the PDF
pdf = PdfDocument()
pdf.LoadFromFile("report.pdf")

# Get the first page
page = pdf.Pages.get_Item(0)

# Read the file to be attached
data = Stream("source-data.xlsx")

# Define the position and size of the attachment icon
bounds = RectangleF(50.0, 100.0, 16.0, 16.0)

# Create the attachment annotation
annotation = PdfAttachmentAnnotation(
    bounds,
    "source-data.xlsx",
    data
)

# Set the appearance and tooltip text
annotation.Color = PdfRGBColor(Color.get_Blue())
annotation.Flags = PdfAnnotationFlags.Default
annotation.Icon = PdfAttachmentIcon.Graph
annotation.Text = "Open the source data"

# Add the annotation to the page
page.AnnotationsWidget.Add(annotation)

# Save the result
pdf.SaveToFile("report-with-page-attachment.pdf")

Here, RectangleF determines where the attachment icon appears:

bounds = RectangleF(50.0, 100.0, 16.0, 16.0)

The four values represent the X coordinate, Y coordinate, width, and height.

The file is then used to create a PdfAttachmentAnnotation:

annotation = PdfAttachmentAnnotation(
    bounds,
    "source-data.xlsx",
    data
)

Finally, the annotation is added to the page:

page.AnnotationsWidget.Add(annotation)

Unlike a document-level attachment, this file now has a visible entry point on the PDF page.

Add a Label Next to the Attachment

An attachment icon by itself may not always make its purpose obvious.

If the PDF will be shared with other users, adding a short label such as Source Data, Supporting File, or Download Spreadsheet can make the attachment easier to understand.

For example:

text = "Source data:"
font = PdfTrueTypeFont(
    "Arial",
    12.0,
    PdfFontStyle.Regular,
    True
)

x = 50.0
y = 100.0

page.Canvas.DrawString(
    text,
    font,
    PdfBrushes.get_Black(),
    x,
    y
)

text_size = font.MeasureString(text)

bounds = RectangleF(
    x + text_size.Width + 5.0,
    y,
    16.0,
    16.0
)

The width of the label is measured first, and the attachment icon is positioned a few points after the text.

The resulting layout can look something like this:

Source data: [attachment icon]

This is particularly useful when attachments are part of the document's normal reading flow rather than simply supplementary files stored with the PDF.

Which Type of PDF Attachment Should You Use?

Use a document-level attachment when the file relates to the PDF as a whole.

Typical examples include:

  • Raw datasets

  • Source spreadsheets

  • Supporting documents

  • Original images

  • Appendices

  • Configuration files

  • Other supplementary material

Use an attachment annotation when the file is directly related to something visible on a particular page.

For example:

  • Source data for a chart

  • An original image associated with a figure

  • Supporting evidence for a paragraph

  • A downloadable template referenced in the text

  • A file associated with a specific section of a report

For general document packages, document-level attachments are usually simpler because they do not affect the page layout.

Attachment annotations are more useful when the position of the file provides additional context to the reader.

A Note About PDF Viewers

Embedded attachments are part of the PDF, but how users access them can vary between PDF viewers.

Desktop PDF applications generally provide an Attachments panel and support attachment annotations. Browser-based PDF viewers may expose these features differently or support only part of the functionality.

If attachments are an important part of a document workflow, it is worth opening the finished PDF in the same viewer your recipients are likely to use.

Final Thoughts

Embedding supporting files can be cleaner than distributing a PDF together with a collection of separate documents.

For files that apply to the entire PDF, document-level attachments keep the page layout untouched while storing the supporting material inside the same file.

When an attachment belongs to a particular chart, paragraph, or section, an attachment annotation gives readers a visible and more contextual way to access it.

The coding difference between the two approaches is small, but choosing the right attachment type can make the finished PDF much easier to navigate.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...