How to Convert HTML to PNG in Python

Cloudmersive
2 min readMar 19, 2024

--

Let’s run through a quick & easy solution for converting our HTML code to a PNG screenshot in Python.

We’ll be calling a free HTML to PNG API using complementary Python code examples provided below.

To start, we can install the SDK via pip install:

pip install cloudmersive-convert-api-client

Right after that, we can turn our attention to authorization. Let’s quickly grab a free Cloudmersive API key — this will allow us to make our conversion up to 800 times per month with zero commitments.

Finally, let’s add the imports and call the function:

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.ConvertWebApi(cloudmersive_convert_api_client.ApiClient(configuration))
input = cloudmersive_convert_api_client.HtmlToPngRequest() # HtmlToPngRequest | HTML to PNG request parameters

try:
# Convert HTML string to PNG screenshot
api_response = api_instance.convert_web_html_to_png(input)
pprint(api_response)
except ApiException as e:
print("Exception when calling ConvertWebApi->convert_web_html_to_png: %s\n" % e)

To structure our request input, we can refer to the below JSON example. We can optionally specify extra loading wait time, screenshot height & screenshot width in our request:

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

All done — now we can easily convert our HTML files to PNG screenshots using minimal Python code.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet