How to Compress PDF with Python
Why Compress PDFs via API?
The pdfRest Compress PDF API Tool is a powerful resource for developers and businesses looking to reduce the size of their PDF files without compromising on quality.
This tutorial will guide you through the process of making an API call to the Compress PDF endpoint using Python. Compressing PDFs is particularly useful in scenarios where you need to save storage space, speed up file transfers, or meet file size requirements for email attachments or website uploads.
Python Code Example for Compression
from requests_toolbelt import MultipartEncoder
import requests
import json
compressed_pdf_endpoint_url = 'https://api.pdfrest.com/compressed-pdf'
# The /compressed-pdf endpoint can take a single PDF file or id as input.
# This sample demonstrates setting compression_level to 'medium'.
# We have preset 'high', 'medium', and 'low' compression levels available for use. These preset levels do not require the 'profile' parameter.
mp_encoder_compressedPdf = MultipartEncoder(
fields={
'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
'output' : 'example_compressedPdf_out',
'compression_level': 'medium',
}
)
# Let's set the headers that the compressed-pdf endpoint expects.
# Since MultipartEncoder is used, the 'Content-Type' header gets set to 'multipart/form-data' via the content_type attribute below.
headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_compressedPdf.content_type,
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
}
print("Sending POST request to compressed-pdf endpoint...")
response = requests.post(compressed_pdf_endpoint_url, data=mp_encoder_compressedPdf, 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)
# If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.py' sample.
The code above is sourced from the pdfRest API samples repository on GitHub, specifically from this file.
Breaking Down the Python Code
The sample uses requests to send the HTTP request, MultipartEncoder from requests-toolbelt to build a multipart body, and json to format the response. Install the two external packages with python -m pip install requests requests-toolbelt if they are not already available.
compressed_pdf_endpoint_url = 'https://api.pdfrest.com/compressed-pdf'
/compressed-pdf accepts either an uploaded PDF or an existing pdfRest resource ID. This multipart example uploads the source directly.
mp_encoder_compressedPdf = MultipartEncoder(
fields={
'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
'output': 'example_compressedPdf_out',
'compression_level': 'medium',
}
)
The file tuple supplies the multipart filename, binary stream, and PDF media type. output sets the generated filename without its extension. compression_level accepts low, medium, high, or custom. The preset levels balance output fidelity against size reduction; custom additionally requires a compression profile or profile resource ID.
headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_compressedPdf.content_type,
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
}
MultipartEncoder.content_type contains both multipart/form-data and the generated boundary, so it must be passed through unchanged. Api-Key authenticates the call, while Accept: application/json requests the standard resource response.
response = requests.post(
compressed_pdf_endpoint_url,
data=mp_encoder_compressedPdf,
headers=headers
)
The encoder is supplied as the request body rather than through json= or files=. This keeps the file and conversion parameters in the same multipart request.
if response.ok:
response_json = response.json()
print(json.dumps(response_json, indent=2))
else:
print(response.text)
A successful response describes the generated PDF resource, including the ID and retrieval information used by later API calls. The failure branch prints the service response so validation and processing errors are not hidden.
Compression and So Much More
In this tutorial, we walked through a Python script that calls the pdfRest Compress PDF API to compress a PDF file. By following the steps outlined, you can integrate this functionality into your own applications. To explore and demo all of the pdfRest API Tools, visit the API Lab. For more detailed information, refer to the API Reference documentation.
Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at this GitHub repository.