How to convert an HTML String to PDF in Python

To go from an HTML string to a PDF file can be a bit of a process. Essentially we will need to fully render the HTML, accounting for Javascript, CSS, etc, and then convert that render into a PDF document, a difficult task unto itself. Complicated? Yes. Necessary? Not if you have an API. Let’s investigate that route to save time.

Our API will need to have its client imported before we do anything else.

pip install cloudmersive-convert-api-client

Now we go ahead and run convert_web_html_to_pdf, the setup for which is below.

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.ConvertWebApi(cloudmersive_convert_api_client.ApiClient(configuration))input = cloudmersive_convert_api_client.HtmlToPdfRequest() # HtmlToPdfRequest | HTML to PDF request parameterstry:# Convert HTML string to PDFapi_response = api_instance.convert_web_html_to_pdf(input)pprint(api_response)except ApiException as e:print("Exception when calling ConvertWebApi->convert_web_html_to_pdf: %s\n" % e)

And with that, you have the PDF version of your HTML! Simple.

Image for post
Image for post
No tricky coding required today!

Written by

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store