How to Add Images to PDF Files with Python

Learn how to use Python to add an image to a PDF by calling Add to PDF API Tool by pdfRest.
Share this page

Why Use Add to PDF with Python?

The pdfRest Add to PDF API Tool is a powerful resource for developers looking to automate the process of manipulating PDF documents. This tool allows you to seamlessly add images to existing PDF files, which can be particularly useful for generating reports, customizing documents, or simply adding visual content to your PDFs.

This tutorial will guide you through the process of sending an API call to the Add to PDF endpoint using Python, enabling you to enhance your PDFs programmatically.

In the real world, a user might need to add a company logo to a batch of invoices, insert a graph or chart into a financial report, or place a signature image onto a contract. Automating this process saves time and reduces the potential for errors that come with manual editing. By using Python, a widely-used programming language for automation, you can integrate this functionality into your applications or workflows with ease.

Add to PDF with Python Code Example

from requests_toolbelt import MultipartEncoder
import requests
import json

pdf_with_added_image_endpoint_url = 'https://api.pdfrest.com/pdf-with-added-image'

mp_encoder_pdfWithAddedImage = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
        'image_file': ('file_name.jpg', open('/path/to/file', 'rb'), 'image/jpeg'),
        'output' : 'example_out',
        'x' : '10',
        'y' : '10',
        'page' : '1',
    }
)

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

print("Sending POST request to pdf-with-added-image endpoint...")
response = requests.post(pdf_with_added_image_endpoint_url, data=mp_encoder_pdfWithAddedImage, 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 code obtained from the pdf-rest-api-samples repository on GitHub.

Breaking Down the Code

In the provided code, we first import necessary modules: MultipartEncoder from requests_toolbelt for encoding multipart form data, requests for making HTTP requests, and json for handling JSON data.

from requests_toolbelt import MultipartEncoder
import requests
import json

The MultipartEncoder is used to create a multipart-encoded payload containing the PDF and image files to be uploaded, along with additional parameters such as the desired output file name, the x and y coordinates for where the image should be placed on the PDF, and the page number where the image should be added.

mp_encoder_pdfWithAddedImage = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
        'image_file': ('file_name.jpg', open('/path/to/file', 'rb'), 'image/jpeg'),
        'output' : 'example_out',
        'x' : '10',
        'y' : '10',
        'page' : '1',
    }
)

Headers are set to accept JSON responses and to include the content type provided by the MultipartEncoder. An API key is also included in the headers for authentication. Replace 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' with your actual pdfRest API key.

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

A POST request is then sent to the pdf_with_added_image_endpoint_url with the encoded data and headers. The response is checked for success, and the resulting JSON is printed out if the request was successful. If not, the error text is displayed.

print("Sending POST request to pdf-with-added-image endpoint...")
response = requests.post(pdf_with_added_image_endpoint_url, data=mp_encoder_pdfWithAddedImage, 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)

Beyond the Tutorial

By following this tutorial, you've learned how to use Python to send a multipart API call to the pdfRest Add to PDF API Tool to add an image to a PDF. This can be integrated into larger applications or used as a standalone script to automate PDF manipulation tasks.

To explore more capabilities and demo all of the pdfRest API Tools, visit the API Lab. For detailed information about the API, refer to the API Reference Guide.

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

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