imgkit
imgkit is a Python 2 and 3 wrapper for the `wkhtmltoimage` utility, which converts HTML content into various image formats (JPG, PNG, etc.) using the Webkit rendering engine and Qt. The library currently stands at version 1.2.3 and is actively maintained, though releases occur on an irregular cadence, with the last major update in February 2023.
Warnings
- gotcha The most common issue is `IOError: 'No wkhtmltoimage executable found'`. imgkit is a wrapper and requires the external `wkhtmltoimage` binary (part of `wkhtmltopdf`) to be installed on your system and accessible in the system's PATH, or its path explicitly configured.
- gotcha On Debian/Ubuntu, the `wkhtmltopdf` package from official repositories often has reduced functionality (e.g., missing QT patches). This can lead to issues with outlines, headers, footers, or TOC.
- gotcha If using the `xvfb` option in imgkit (e.g., for headless environments), you might encounter `IOError: 'No xvfb executable found'`.
- gotcha A generic `IOError: 'Command Failed'` indicates that `wkhtmltoimage` was invoked but exited with a non-zero status, meaning it couldn't process the input for various reasons (e.g., invalid HTML, resource loading issues, out of memory).
Install
-
pip install imgkit -
sudo apt-get install wkhtmltopdf -
brew install --cask wkhtmltopdf -
Download installer from https://wkhtmltopdf.org/downloads.html
Imports
- imgkit
import imgkit
- config
import imgkit config = imgkit.config(wkhtmltoimage='/path/to/wkhtmltoimage')
Quickstart
import imgkit
import os
# --- Option 1: Convert from a URL ---
# imgkit.from_url takes a URL and an output filename
imgkit.from_url('http://google.com', 'google.jpg')
print('Converted Google to google.jpg')
# --- Option 2: Convert from an HTML file ---
# Create a dummy HTML file
with open('test.html', 'w') as f:
f.write('<h1>Hello from imgkit!</h1><p>This is a test.</p>')
imgkit.from_file('test.html', 'test_output.png')
print('Converted test.html to test_output.png')
# --- Option 3: Convert from an HTML string ---
html_string = '<html><body><h2>Inline HTML</h2><p style="color: blue;">Styled content.</p></body></html>'
imgkit.from_string(html_string, 'string_output.jpeg')
print('Converted HTML string to string_output.jpeg')
# --- Option 4: Configure wkhtmltoimage path (if not in PATH) ---
# Replace with the actual path to your wkhtmltoimage executable
# Example for Windows: r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe'
# Example for Linux: '/usr/local/bin/wkhtmltoimage'
WKHTMLTOIMAGE_PATH = os.environ.get('WKHTMLTOIMAGE_BINARY_PATH', '')
if WKHTMLTOIMAGE_PATH:
configuration = imgkit.config(wkhtmltoimage=WKHTMLTOIMAGE_PATH)
imgkit.from_string('<h1>Configured Path Test</h1>', 'path_config_output.jpg', config=configuration)
print('Converted with custom wkhtmltoimage path.')
else:
print('WKHTMLTOIMAGE_BINARY_PATH environment variable not set. Skipping custom path configuration example.')
# Clean up dummy file
os.remove('test.html')