How to Convert JPG to PDF with Python

Learn how to use pdfRest Convert to PDF API Tool with Python to convert JPG to PDF
Share this page

Why Use Convert to PDF with Python?

The pdfRest Convert to PDF API Tool is a powerful resource for developers looking to integrate PDF conversion functionality into their applications. By using this API, you can programmatically convert various file types to PDF, ensuring consistency and quality in document handling. This tutorial will guide you through the process of sending an API call to the /pdf endpoint using Python, a popular programming language known for its simplicity and readability.

There are countless scenarios where converting files to PDF can be beneficial. For instance, a business may need to convert scanned documents, such as invoices or contracts, into PDF format to ensure that they are easily accessible, shareable, and compliant with archival standards. By automating this process with the Convert to PDF API, businesses can save time, reduce errors, and maintain a consistent workflow.

Convert JPG to PDF with Python Code Example

The following code is a complete example of how to call the pdfRest Convert to PDF API using Python. This code is sourced from the pdf-rest-api-samples repository on GitHub.

from requests_toolbelt import MultipartEncoder
import requests
import json

pdf_endpoint_url = 'https://api.pdfrest.com/pdf'

mp_encoder_pdf = MultipartEncoder(
    fields={
        'file': ('file_name.jpg', open('/path/to/file', 'rb'), 'image/jpeg'),
        'output' : 'example_pdf_out',
    }
)

headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_pdf.content_type,
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
}

print("Sending POST request to pdf endpoint...")
response = requests.post(pdf_endpoint_url, data=mp_encoder_pdf, 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)

Breaking Down the Code

The code snippet above demonstrates how to use Python to make a multipart API call to the pdfRest Convert to PDF endpoint. Let's break down the key components:

from requests_toolbelt import MultipartEncoder
import requests
import json

This imports the necessary libraries. MultipartEncoder from requests_toolbelt is used to encode the files and fields for the multipart request, while requests handles the HTTP request, and json processes the JSON response.

pdf_endpoint_url = 'https://api.pdfrest.com/pdf'

This sets the API endpoint URL that the request will be sent to.

mp_encoder_pdf = MultipartEncoder(
    fields={
        'file': ('file_name.jpg', open('/path/to/file', 'rb'), 'image/jpeg'),
        'output' : 'example_pdf_out',
    }
)

This section creates a MultipartEncoder object with the fields needed for the request. The 'file' field contains a tuple with the filename, file object, and MIME type. The 'output' field specifies the desired name for the output PDF file.

headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_pdf.content_type,
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
}

Here, we set the HTTP headers for the request. The 'Content-Type' is automatically set to 'multipart/form-data' by the MultipartEncoder, and 'Api-Key' should be replaced with your actual API key.

response = requests.post(pdf_endpoint_url, data=mp_encoder_pdf, headers=headers)

This sends a POST request to the specified endpoint with the encoded data and headers.

if response.ok:
    response_json = response.json()
    print(json.dumps(response_json, indent = 2))
else:
    print(response.text)

Finally, the code checks if the response is successful and prints the JSON response. If not, it prints the error text.

Beyond the Tutorial

This tutorial has demonstrated how to call the pdfRest Convert to PDF API using Python to convert a JPG file to PDF. By understanding the structure of the API call and the necessary parameters, you can adapt this example to convert other file types supported by the API.

To further explore and demo all of the pdfRest API Tools, visit the API Lab. For a comprehensive guide to the API, including additional endpoints and parameters, refer to the API Reference Guide.

Note: This example uses a multipart API call. For code samples using JSON payloads, visit this 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