html2image Library

2.0.7 · active · verified Tue Apr 14

The html2image package provides a Pythonic wrapper around headless web browsers (Chrome, Chromium, Edge, Firefox) to convert URLs, HTML strings, or HTML files (with CSS) into images. It's actively maintained with frequent updates, currently at version 2.0.7, focusing on browser compatibility and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `Html2Image` and use it to capture screenshots from both a URL and an HTML string. Remember that a compatible headless browser must be installed on your system for `html2image` to function.

from html2image import Html2Image
import os

# Ensure you have a headless browser (Chrome, Chromium, Edge, or Firefox) installed
# For example, on Ubuntu:
# sudo apt-get update
# sudo apt-get install chromium-browser

hti = Html2Image(size=(1920, 1080), browser='chrome')

# Take a screenshot of a website
hti.screenshot(
    url='https://www.python.org',
    save_as='python_org.png',
    # You can specify a custom executable path if the browser isn't in PATH
    # executable_path='/usr/bin/chromium-browser'
)
print("Screenshot of python.org saved as python_org.png")

# Take a screenshot of an HTML string
html_content = """
<h1 style="color: blue;">Hello, `html2image`!</h1>
<p>This is a test of string conversion.</p>
"""
hti.screenshot(html_str=html_content, save_as='hello_html.png')
print("Screenshot of HTML string saved as hello_html.png")

# Clean up generated files for demonstration
# os.remove('python_org.png')
# os.remove('hello_html.png')

view raw JSON →