How to Convert HTML to PDF in Python

Cloudmersive
2 min readMar 12, 2024

--

We can make HTML to PDF conversions easy in Python by calling a free API with complementary code examples.

To begin structuring our API call, let’s start by installing the client SDK with pip install:

pip install cloudmersive-convert-api-client

Right after that, add the imports and call the function. Let’s include our HTML file path in the input_file variable, and then customize options to include background graphics and set our scale factor:

from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint

# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'



# create an instance of the API class
api_instance = cloudmersive_convert_api_client.ConvertDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))
input_file = '/path/to/inputfile' # file | Input file to perform the operation on.
include_background_graphics = true # bool | Optional: Set to true to include background graphics in the PDF, or false to not include. Default is true. (optional)
scale_factor = 56 # int | Optional: Set to 100 to scale at 100%, set to 50% to scale down to 50% scale, set to 200% to scale up to 200% scale, etc. Default is 100%. Maximum is 1000%. (optional)

try:
# Convert HTML document file to PDF Document
api_response = api_instance.convert_document_html_to_pdf(input_file, include_background_graphics=include_background_graphics, scale_factor=scale_factor)
pprint(api_response)
except ApiException as e:
print("Exception when calling ConvertDocumentApi->convert_document_html_to_pdf: %s\n" % e)

To authorize our API calls, we’ll just need a free Cloudmersive API key. This will allow a limit of 800 API calls per month with zero additional commitments.

Just like that, we’re all done — no more code required.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet