How to Resize PDF Pages with Python

Learn how to use Set Page Boxes API by pdfRest to resize PDF pages with Python.
Share this page

Why Resize PDF Pages with Python?

The pdfRest Set Page Boxes API Tool allows you to modify the page boxes of a PDF document, specifically the MediaBox, to control the physical dimensions of the pages. This tutorial will guide you through the process of sending an API call to the Set Page Boxes API Tool endpoint using Python to resize all pages of a PDF document.

Imagine you have a PDF document where all pages need to conform to a specific standard dimension for consistent display or processing. By using the Set Page Boxes API Tool and the "all" range, you can efficiently resize all PDF pages to meet your requirements in a single API call.

Resize PDF Pages with Python Code Example

from requests_toolbelt import MultipartEncoder
import requests
import json

pdf_with_page_boxes_endpoint_url = 'https://api.pdfrest.com/pdf-with-page-boxes-set'

# Define the MediaBox adjustments to resize all pages from Letter to A4
# Letter: 612 x 792 points
# A4:    595 x 842 points
delta_width_inward = (612 - 595) / 2   # Positive margin to shrink width inward
delta_height_outward = (792 - 842) / 2  # Negative margin to expand height outward

resize_box_options = {
    "boxes": [
        {
            "box": "media",
            "pages": [
                {
                    "range": "all",
                    "left": delta_width_inward,
                    "top": delta_height_outward,
                    "bottom": delta_height_outward,
                    "right": delta_width_inward
                }
            ]
        }
    ]
}

mp_encoder_setBoxesPDF = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/your/file.pdf', 'rb'), 'application/pdf'), # Replace with your file path
        'boxes': json.dumps(resize_box_options),
        'output' : 'resized_all_to_a4_out'
    }
)

headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_setBoxesPDF.content_type,
    'Api-Key': 'YOUR_API_KEY' # Replace with your actual API key
}

print("Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4...")
response = requests.post(pdf_with_page_boxes_endpoint_url, data=mp_encoder_setBoxesPDF, 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 (Note: This example has been modified to focus on resizing all pages)

Breaking Down the Code for Resizing All Pages

The code starts by importing the necessary libraries for making API calls and handling data.

pdf_with_page_boxes_endpoint_url = 'https://api.pdfrest.com/pdf-with-page-boxes-set'

This line defines the API endpoint URL for setting page boxes.

# Define the MediaBox adjustments to resize all pages from Letter to A4
# Letter: 612 x 792 points
# A4:    595 x 842 points
delta_width_inward = (612 - 595) / 2   # Positive margin to shrink width inward
delta_height_outward = (792 - 842) / 2  # Negative margin to expand height outward

resize_box_options = {
    "boxes": [
        {
            "box": "media",
            "pages": [
                {
                    "range": "all",
                    "left": delta_width_inward,
                    "top": delta_height_outward,
                    "bottom": delta_height_outward,
                    "right": delta_width_inward
                }
            ]
        }
    ]
}

The resize_box_options dictionary is configured to resize all PDF pages by adjusting the MediaBox. The "box" key is set to "media". The key difference here is within the "pages" array: setting "range" to "all" instructs the API to apply these MediaBox adjustments to every page in the input PDF. The `left` and `right` margins are positive to shrink the width, and the `top` and `bottom` margins are negative (due to the coordinate system) to expand the height.

mp_encoder_setBoxesPDF = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/your/file.pdf', 'rb'), 'application/pdf'), # Replace with your file path
        'boxes': json.dumps(resize_box_options),
        'output' : 'resized_all_to_a4_out'
    }
)

Here, we create a MultipartEncoder to send the PDF file and the resize_box_options as multipart form data. Make sure to replace '/path/to/your/file.pdf' with the actual path to your PDF file.

headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_setBoxesPDF.content_type,
    'Api-Key': 'YOUR_API_KEY' # Replace with your actual API key
}

The headers dictionary includes the necessary information for the API request, including your unique API key. Remember to replace 'YOUR_API_KEY' with your actual pdfRest API key.

response = requests.post(pdf_with_page_boxes_endpoint_url, data=mp_encoder_setBoxesPDF, headers=headers)

This line sends the POST request to the pdfRest API endpoint to resize all PDF pages using the specified MediaBox adjustments.

Next Steps for Resizing All PDF Pages

This tutorial demonstrated how to use Python and the pdfRest Set Page Boxes API Tool to resize all pages of a PDF from US Letter to A4 by setting the MediaBox with the "range": "all" option. You can adapt the delta_width_inward and delta_height_outward calculations to resize to other dimensions. This approach efficiently applies the same resizing to every page in your document.

To learn more about the Set Page Boxes API Tool and its capabilities, including setting other page boxes and using different page ranges, you can demo all of the pdfRest API Tools in the API Lab and refer to the API Reference Guide for detailed documentation.

Note: This example uses a multipart API call. JSON payload examples for setting page boxes, including the MediaBox, can be found at GitHub.

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