How to Add Vector Lines and Rectangles to PDF Files with Python

Learn how to use Add to PDF API Tool from pdfRest with Python to add vector shapes to PDF documents.
Share this page

Why Add Vector Lines and Rectangles to PDF Files with Python?

The pdfRest Add to PDF API Tool is a powerful feature that allows developers to programmatically add shapes, such as rectangles and lines, to existing PDF documents. 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 with custom graphical elements seamlessly.

In a real-world scenario, a user might want to use the Add to PDF feature to annotate documents with review panels or highlight sections of a report for emphasis. For instance, a project manager could add shaded rectangles to a project proposal PDF to draw attention to key sections or use lines to divide different parts of a document, making it more visually organized and easier to navigate for stakeholders.

Add Vector Lines and Rectangles to PDF Files with Python Code Example

import json

import requests
from requests_toolbelt import MultipartEncoder

# By default, we use the US-based API service. This is the primary endpoint for global use.
api_url = "https://api.pdfrest.com"

# For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
# For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
# api_url = "https://eu-api.pdfrest.com"

# Add a lightly shaded review panel and a divider line to page one.
# Coordinates are measured from the lower-left corner in PDF units (72 units = 1 inch).
shape_objects = [
    {
        "type": "rectangle",
        "page": 1,
        "x": 54,
        "y": 540,
        "width": 504,
        "height": 108,
        "fill_color_rgb": "245,247,250",
        "stroke_color_rgb": "26,72,112",
        "stroke_width": 1,
        "tag_is_artifact": True,
    },
    {
        "type": "line",
        "page": 1,
        "x1": 72,
        "y1": 576,
        "x2": 540,
        "y2": 576,
        "stroke_color_rgb": "26,72,112",
        "stroke_width": 1.5,
        "tag_actual_text": "Review section divider",
        "tag_structure_type": "Figure",
    },
]

with open("/path/to/input.pdf", "rb") as input_file:
    multipart = MultipartEncoder(
        fields={
            "file": ("input.pdf", input_file, "application/pdf"),
            "shape_objects": json.dumps(shape_objects),
            "tag_enabled": "true",
            "output": "review-panel",
        }
    )
    response = requests.post(
        f"{api_url}/pdf-with-added-shapes",
        data=multipart,
        headers={
            "Accept": "application/json",
            "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",  # Replace with your API key.
            "Content-Type": multipart.content_type,
        },
    )

print(f"Response status code: {response.status_code}")
print(json.dumps(response.json(), indent=2) if response.ok else response.text)

# To download the returned file, use the outputId with the get-resource-id endpoint sample.

Source: GitHub

Breaking Down the Code

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

api_url = "https://api.pdfrest.com"

This line sets the API URL to the US-based service. If you need GDPR compliance, you can switch to the EU-based service by using the commented URL.

shape_objects = [
    {
        "type": "rectangle",
        "page": 1,
        "x": 54,
        "y": 540,
        "width": 504,
        "height": 108,
        "fill_color_rgb": "245,247,250",
        "stroke_color_rgb": "26,72,112",
        "stroke_width": 1,
        "tag_is_artifact": True,
    },
    {
        "type": "line",
        "page": 1,
        "x1": 72,
        "y1": 576,
        "x2": 540,
        "y2": 576,
        "stroke_color_rgb": "26,72,112",
        "stroke_width": 1.5,
        "tag_actual_text": "Review section divider",
        "tag_structure_type": "Figure",
    },
]

The shape_objects list contains dictionaries defining the shapes to be added to the PDF. Each dictionary specifies the shape type, position, dimensions, color, and additional tagging information.

with open("/path/to/input.pdf", "rb") as input_file:
    multipart = MultipartEncoder(
        fields={
            "file": ("input.pdf", input_file, "application/pdf"),
            "shape_objects": json.dumps(shape_objects),
            "tag_enabled": "true",
            "output": "review-panel",
        }
    )

This snippet opens the input PDF file and creates a MultipartEncoder object with the file and shape data. The tag_enabled field is set to "true" to enable tagging, and the output field specifies the output file name.

response = requests.post(
    f"{api_url}/pdf-with-added-shapes",
    data=multipart,
    headers={
        "Accept": "application/json",
        "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",  # Replace with your API key.
        "Content-Type": multipart.content_type,
    },
)

The API call is made using requests.post(), sending the multipart data to the endpoint. Headers include the API key and content type.

Beyond the Tutorial

In this tutorial, you learned how to use Python to send an API call to the pdfRest Add to PDF endpoint, allowing you to add shapes to a PDF document. This powerful feature can be used to enhance documents with custom graphics and annotations.

To explore more functionalities, try out all the pdfRest API Tools in the API Lab. For more detailed information, refer to the API Reference Guide. Note that this is an example of a multipart API call, and code samples using JSON payloads can be found here.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.