How to convert an HTML String to PDF in Python
1 min readJun 10, 2020
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 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)
And with that, you have the PDF version of your HTML! Simple.