imgkit

1.2.3 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to convert HTML from a URL, a local file, or a direct string into an image using `imgkit`. It also includes an example of how to configure the path to the `wkhtmltoimage` executable, which is a common requirement for the library to function correctly.

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')

view raw JSON →