How to Add Attachments to PDF Files with Python

Learn how to use PHP to add attachments to PDF files by calling Add to PDF API tool by pdfRest.
Share this page

Why Add Attachments to PDF with Python?

The pdfRest Add to PDF API Tool is a powerful resource for developers who need to programmatically add attachments to PDF documents. This tutorial will guide you through the process of sending an API call to Add to PDF using Python. For instance, if you're generating reports that require supplementary documents (like source data or additional references) to be bundled together for distribution, the Add to PDF API can automate this process, saving time and reducing the potential for errors.

Add Attachments to PDF with Python Code Example

from requests_toolbelt import MultipartEncoder
import requests
import json

pdf_with_added_attachment_endpoint_url = 'https://api.pdfrest.com/pdf-with-added-attachment'

mp_encoder_pdfWithAddedAttachment = MultipartEncoder(
    fields={
        'file': ('file_name', open('/path/to/file', 'rb'), 'application/pdf'),
        'file_to_attach': ('file_name', open('/path/to/file', 'rb'), 'application/xml'), # Update content type
        'output' : 'example_out',
    }
)

headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_pdfWithAddedAttachment.content_type,
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
}

print("Sending POST request to pdf-with-added-attachment endpoint...")
response = requests.post(pdf_with_added_attachment_endpoint_url, data=mp_encoder_pdfWithAddedAttachment, headers=headers)

print("Response status code: " + str(response.status_code))

if response.ok:
    response_json = response.json()
    print(json.dumps(response_json, indent = 2))
else:
    print(response.text)

Source: pdf-rest-api-samples

Breaking Down the Code

The code provided makes a POST request to the pdfRest Add to PDF API endpoint. Let's break down the key components:

mp_encoder_pdfWithAddedAttachment = MultipartEncoder(
    fields={
        'file': ('file_name', open('/path/to/file', 'rb'), 'application/pdf'),
        'file_to_attach': ('file_name', open('/path/to/file', 'rb'), 'application/xml'),
        'output' : 'example_out',
    }
)

This block creates a MultipartEncoder object with three fields:

  • file: The PDF file to which you want to add an attachment. Replace '/path/to/file' with the actual file path.
  • file_to_attach: The file you want to attach to the PDF. Update the content type (e.g., 'application/xml') to match the file's type.
  • output: The desired name for the output file.
headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_pdfWithAddedAttachment.content_type,
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
}

Here, headers for the request are set up, including the API key which you must replace with your own.

response = requests.post(pdf_with_added_attachment_endpoint_url, data=mp_encoder_pdfWithAddedAttachment, headers=headers)

This line sends the POST request to the specified endpoint with the data and headers configured above.

The rest of the code handles the response, printing out the status code and the response content, formatted as JSON if the request was successful.

Beyond the Tutorial

By following the steps above, you've learned how to send an API call to add attachments to a PDF using Python. This capability is essential for automating document workflows and integrating PDF functionalities into your applications.

Feel free to demo all of the pdfRest API Tools in the API Lab at https://pdfrest.com/apilab/ and refer to the API Reference documentation at https://pdfrest.com/documentation/ for more information.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at pdf-rest-api-samples.

Generate a self-service API Key now!

Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.

Compare Plans
Contact Us