How to convert an HTML String to PDF in Python

Today I will be demonstrating how to fully render an HTML string, then convert the website into a PDF document. This will have support for CSS, Javascript, and HTML5, among other things. Don’t worry, though, this isn’t going to be a very time-consuming process. We are using an API shortcut.

We will need the API client installed before we can do anything else:

pip install cloudmersive-convert-api-client

Now create an API instance using a key, and call convert_web_html_to_pdf from this instance:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest 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)

Now input our string and extra wait time allowed, like this:

{
"Html": "string",
"ExtraLoadingWait": 0
}

And your HTML will be rendered and converted to PDF, no problem.

Image for post
Image for post

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