How to Add Text to PDF Files with Python

Learn how to insert text into a PDF using pdfRest Add to PDF API Tool with Python
Share this page

Why Add to PDF Files with Python?

The pdfRest Add to PDF API Tool is a powerful resource for developers looking to programmatically add text to PDF documents. This tutorial will guide you through the process of sending an API call to the Add to PDF endpoint using Python. By leveraging this tool, you can automate the process of modifying PDF files, which is particularly useful for applications that require dynamic PDF content generation or updates.

Consider a scenario where a business needs to generate personalized invoices for its customers. By using the Add to PDF API, the business can automatically insert customer names, addresses, and invoice details into a PDF template, streamlining the invoicing process and reducing the potential for manual errors. This approach not only enhances efficiency but also ensures a consistent and professional appearance for all generated documents.

Add Text to PDF Files with Python Code Example

from requests_toolbelt import MultipartEncoder
import requests
import json

pdf_with_added_text_endpoint_url = 'https://api.pdfrest.com/pdf-with-added-text'

text_options = [{
    "font":"Times New Roman",
    "max_width":"175",
    "opacity":"1",
    "page":"1",
    "rotation":"0",
    "text":"sample text in PDF",
    "text_color_rgb":"0,0,0",
    "text_size":"30",
    "x":"72",
    "y":"144"
}]

mp_encoder_addedtextPDF = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
        'text_objects': json.dumps(text_options),
        'output' : 'example_out'
    }
)

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

print("Sending POST request to pdf-with-added-text endpoint...")
response = requests.post(pdf_with_added_text_endpoint_url, data=mp_encoder_addedtextPDF, 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: GitHub Repository

Breaking Down the Code

The code begins by importing necessary libraries: requests_toolbelt for handling multipart encoding, requests for making HTTP requests, and json for handling JSON data.

pdf_with_added_text_endpoint_url = 'https://api.pdfrest.com/pdf-with-added-text'

This line sets the endpoint URL for the Add to PDF API.

text_options = [{
    "font":"Times New Roman",
    "max_width":"175",
    "opacity":"1",
    "page":"1",
    "rotation":"0",
    "text":"sample text in PDF",
    "text_color_rgb":"0,0,0",
    "text_size":"30",
    "x":"72",
    "y":"144"
}]

The text_options dictionary specifies the text attributes to be added to the PDF. Each key-value pair defines a property such as font, max_width, opacity, page, rotation, text, text_color_rgb, text_size, x, and y. These options allow precise control over the appearance and placement of the text.

mp_encoder_addedtextPDF = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
        'text_objects': json.dumps(text_options),
        'output' : 'example_out'
    }
)

The MultipartEncoder is used to prepare the multipart form-data payload. The fields parameter includes the PDF file, the JSON-encoded text_objects, and the desired output filename.

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

The headers dictionary sets the request headers, including the Accept type, Content-Type derived from the MultipartEncoder, and the Api-Key, which you need to replace with your actual API key.

response = requests.post(pdf_with_added_text_endpoint_url, data=mp_encoder_addedtextPDF, headers=headers)

This line sends the POST request to the API endpoint, passing the encoded data and headers.

Beyond the Tutorial

In this tutorial, you successfully learned how to use Python to send an API request to the pdfRest Add to PDF endpoint, allowing you to add text to a PDF document programmatically. This is a versatile tool that can be integrated into various applications requiring PDF modifications.

For further exploration, you can demo all of the pdfRest API Tools in the API Lab. Additionally, the API Reference Guide provides comprehensive details on all available endpoints and parameters.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub Repository.

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