HTML to IMAGE using Python

You can do this by using imgkit

import imgkit

imgkit.from_file('test.html', 'out.jpg')

Or you can also use htmlcsstoimage Api

# pip3 install requests
import requests

HCTI_API_ENDPOINT = "https://hcti.io/v1/image"
HCTI_API_USER_ID = 'your-user-id'
HCTI_API_KEY = 'your-api-key'

data = { 'html': "<div class='box'>Hello, world!</div>",
         'css': ".box { color: white; background-color: #0f79b9; padding: 10px; font-family: Roboto }",
         'google_fonts': "Roboto" }

image = requests.post(url = HCTI_API_ENDPOINT, data = data, auth=(HCTI_API_USER_ID, HCTI_API_KEY))

print("Your image URL is: %s"%image.json()['url'])
# https://hcti.io/v1/image/7ed741b8-f012-431e-8282-7eedb9910b32

from html2image import Html2Image
hti = Html2Image()
with open('./test.html') as f:
    hti.screenshot(f.read(), save_as='out.png')

If you don't want your project to depend on wkhtmltopdf, like other Python modules use, I recommend html2image.

You can get it using the pip install html2image command. A web browser shall also be installed on your machine (Chrome/Chromium for now).

Once installed, you can take a screenshot of an HTML string like so:

from html2image import Html2Image
hti = Html2Image()

html = '<h1> A title </h1> Some text.'
css = 'body {background: red;}'

# screenshot an HTML string (css is optional)
hti.screenshot(html_str=html, css_str=css, save_as='page.png')

You can also directly take screenshots of existing HTML files or URLs:

# screenshot an HTML file
hti.screenshot(
    html_file='page.html', css_file='style.css', save_as='page2.png'
)

# screenshot an URL
hti.screenshot(url='https://www.python.org', save_as='python_org.png')

For documentation and more examples, you can check out the the GitHub page of the project.


Another very useful tool to render HTML sites is the headless Chromium browser.

In javascript you would use the puppeteer api to interact with it but there is a unofficial python port of puppeteer called pyppeteer

From my experience with python tools like imgkit the Chromium solution is far more reliable when it comes to loading in external assets like images or iFrames.

To get an image version of the rendered HTML using pyppeteer you simply load the page and then make a full page screenshot:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('http://example.com')
    await page.screenshot({'path': 'example.png', 'fullPage': 'true'})
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())