How to convert an HTML Document to PNG Array in Python

Today we are going to create a means by which we may fully render all the elements in an HTML document, and convert this render into a set of PNG images. If this sounds complicated, don’t be alarmed. We are not going to be doing this in the normal, time-consuming manner. Rather, we will be harnessing an API to do all the busy work. Start with this installation command:

pip install cloudmersive-convert-api-client

Following that, call convert_document_html_to_png, providing your HTML file.

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.ConvertDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Convert HTML document file to PNG image arrayapi_response = api_instance.convert_document_html_to_png(input_file)pprint(api_response)except ApiException as e:print("Exception when calling ConvertDocumentApi->convert_document_html_to_png: %s\n" % e)

Now the API will render everything in the file, including all the complicated stuff, like JavaScript and CSS elements. Wait a moment and it will send back your PNGs.

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