html2image Library
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
- gotcha The `html2image` library requires a compatible headless web browser (Chrome, Chromium, Edge, or Firefox) to be installed on your system. It does not automatically install one. Ensure your chosen browser is in your system's PATH, or provide its executable path via the `executable_path` parameter during initialization.
- breaking Version 2.0.0 introduced significant internal structural changes and revamped how browser flags are handled. Custom browser configurations or direct manipulation of browser arguments from pre-2.0.0 versions might require updates.
- breaking Starting with version 2.0.5, `html2image` defaults to using Chrome's `--headless=new` flag for improved compatibility with newer browser versions. If you encounter issues with older browser versions or specific environments, you might need to revert to the old headless mode.
- deprecated Version 2.0.3 fixed an issue where the default background color flag for Chrome/Chromium changed from '0' to '000000'. If you were relying on the '0' value, it might no longer be supported on newer Chromium versions.
- gotcha Version 2.0.2 was yanked from PyPI shortly after its release due to a problematic wheel file. Avoid installing or using this specific version.
- gotcha Version 2.0.7 introduced a new and improved Command Line Interface (CLI). Existing shell scripts or automation relying on the `html2image` command-line utility might need updates to match the new argument structure and syntax.
Install
-
pip install html2image
Imports
- Html2Image
from html2image import Html2Image
Quickstart
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')