imgkit Documentation

repository·master·Indexed 21 days ago

https://github.com/jarrekk/imgkit

A Python wrapper for the wkhtmltoimage utility that converts HTML strings, files, or URLs into images using the Webkit engine. It provides functionality to configure binary paths for wkhtmltoimage and xvfb, inject custom CSS, and manage conversion options via Python dictionaries or HTML meta tags.

Tokens
4.1K
Snippets
17
Records
20
Agent score
74%

What's inside imgkit

  1. Configure imgkit via meta tags in HTML

    master

    You can pass options directly through HTML <meta> tags. By default, these tags must use the imgkit- prefix.

    body = """
    <html
      <head>
        <meta name="imgkit-format" content="png"/>
        <meta name="imgkit-orientation" content="Landscape"/>
      </head>
      Hello World!
    </html>
    """
    
    imgkit.from_string(body, 'out.png')
  2. How to use xvfb on headless servers

    master

    On headless servers (like Ubuntu or CentOS), you may need to install and use xvfb to run the conversion.

    1. Install xvfb:

      • Ubuntu: sudo apt-get install xvfb
      • CentOS: yum install xorg-x11-server-Xvfb
    2. Use with imgkit: Pass xvfb as an empty string in your options dictionary.

    options = {
        'xvfb': ''
    }
    imgkit.from_url('http://google.com', 'out.jpg', options=options)
  3. Install imgkit and wkhtmltopdf

    master

    To use imgkit, you must install both the Python library and the wkhtmltopdf (specifically wkhtmltoimage) binary.

    1. Install the Python library:

      pip install imgkit
    2. Install the wkhtmltopdf binary:

      • Debian/Ubuntu: sudo apt-get install wkhtmltopdf. Warning: Repo versions may lack features like headers/footers due to missing QT patches. Consider using a static binary from the official site.
      • MacOSX: brew install --cask wkhtmltopdf
      • Windows: Download binary installers from the wkhtmltopdf homepage.
    pip install imgkit
  4. Basic usage of imgkit

    master

    imgkit provides several methods to convert HTML sources (URLs, files, or strings) into images. You can specify an output file path or pass False to return the image data as a variable.

    import imgkit
    
    # From a URL
    imgkit.from_url('http://google.com', 'out.jpg')
    
    # From a local file
    imgkit.from_file('test.html', 'out.jpg')
    
    # From a string
    imgkit.from_string('Hello!', 'out.jpg')
    
    # Using an opened file object
    with open('file.html') as f:
        imgkit.from_file(f, 'out.jpg')
    
    # Save image to a variable instead of a file
    img = imgkit.from_url('http://google.com', False)
  5. Use HTML meta tags to configure imgkit options

    master

    If your source is a string, IMGKit can automatically extract configuration options from HTML <meta> tags. This allows you to embed wkhtmltoimage settings directly within the HTML content.

    IMGKit looks for meta tags matching a specific prefix (configured in the Config object) and uses the name and content attributes to populate the options dictionary.

  6. Troubleshoot imgkit errors

    master

    Common errors and solutions:

    • IOError: 'No wkhtmltopdf executable found': Ensure wkhtmltoimage is in your $PATH or provide the path via imgkit.config(wkhtmltoimage='...').
    • IOError: 'No xvfb executable found': Ensure xvfb-run is in your $PATH or provide the path via imgkit.config(xvfb='...').
    • IOError: 'Command Failed': The input could not be processed. Try running the exact command shown in the error message manually to debug (this can sometimes indicate segmentation faults in certain wkhtmltoimage versions).
  7. Configure wkhtmltoimage options

    master

    You can pass a dictionary of options to any imgkit method to control the conversion process. These options correspond to wkhtmltoimage command-line flags (remove the -- prefix).

    • Boolean/Flag options: Use None, False, or '' (e.g., {'no-outline': None}).
    • Repeatable options: Use a list or tuple (e.g., cookie, custom-header).
    • Options with multiple values: Use a 2-tuple (e.g., ('Header-Name', 'Value')).
    • Quiet mode: To suppress output, use {'quiet': ''}.
    options = {
        'format': 'png',
        'crop-h': '3',
        'crop-w': '3',
        'crop-x': '3',
        'crop-y': '3',
        'encoding': "UTF-8",
        'custom-header' : [
            ('Accept-Encoding', 'gzip')
        ],
        'cookie': [
            ('cookie-name1', 'cookie-value1'),
            ('cookie-name2', 'cookie-value2'),
        ],
        'no-outline': None
    }
    
    imgkit.from_url('http://google.com', 'out.png', options=options)
  8. Use external CSS files

    master

    You can apply external CSS to your conversion using the css parameter. It accepts either a single string (path to one file) or a list of strings (multiple files).

    # Single CSS file
    imgkit.from_file('file.html', options=options, css='example.css')
    
    # Multiple CSS files
    imgkit.from_file('file.html', options=options, css=['example.css', 'example2.css'])
  9. Configure imgkit with custom binary paths

    master

    If wkhtmltoimage or xvfb-run are not in your system $PATH, use imgkit.config() to specify their locations explicitly.

    config = imgkit.config(wkhtmltoimage='/opt/bin/wkhtmltoimage', xvfb='/opt/bin/xvfb-run')
    imgkit.from_string(html_string, output_file, config=config)
  10. Troubleshoot X server and xvfb errors

    master

    When running on headless servers (like Ubuntu or CentOS), wkhtmltoimage may fail because it requires an X server to render.

    Common Scenarios:

    1. Error: cannot connect to X server

      • Solution: Run wkhtmltoimage within a virtual X server. Use xvfb.
    2. Error: QXcbConnection

      • Solution:
        • Install xvfb (e.g., sudo apt-get install xvfb on Ubuntu or yum install xorg-x11-server-Xvfb on CentOS).
        • Pass the xvfb option in your IMGKit configuration: options={'xvfb': ''}.

    Note: When the xvfb option is used, IMGKit automatically appends the -a flag to wkhtmltoimage to prevent failures during concurrent runs on the same server.

  11. Initialize IMGKit for HTML to image conversion

    master

    The IMGKit class is the primary entry point for converting HTML (from a URL, a file, or a string) into images using wkhtmltoimage.

    Parameters:

    • url_or_file: The source of the HTML. Can be a URL string, a file path string, a file-like object, or an HTML string.
    • source_type: Specifies the type of the source (e.g., 'url', 'file', 'string').
    • options (optional): A dictionary of wkhtmltoimage command-line options. Keys can be provided with or without the -- prefix.
    • config (optional): An instance of Config to customize the wkhtmltoimage path or other settings.
    • toc (optional keyword argument): A dictionary of Table of Contents options.
    • cover (optional keyword argument): A path to a cover image.
    • cover_first (optional keyword argument): Boolean; if true, the cover is placed at the beginning.
    • css (optional keyword argument): A path to a single CSS file or a list of CSS file paths to be injected into the HTML.
    from imgkit.imgkit import IMGKit
    
    # Example: Convert a URL to an image file
    imgkit = IMGKit('http://google.com', 'url', options={'format': 'png'})
    imgkit.to_img('output.png')
  12. Convert HTML to image using to_img()

    master

    The to_img(path=None) method executes the conversion process.

    • If path is provided: The generated image is saved to the specified file path. Returns True on success.
    • If path is False or None: The generated image data is returned as a bytes object (via stdout).

    Error Handling:

    • Raises OSError if wkhtmltoimage fails or returns a non-zero exit code.
    • If the error message contains cannot connect to X server, you must run wkhtmltoimage within a virtual X server (like xvfb).
    • If the error message contains QXcbConnection, it suggests installing xvfb and adding {"xvfb": ""} to your options.
    # Save to a file
    imgkit = IMGKit('<html><body><h1>Hello</h1></body></html>', 'string')
    imgkit.to_img('result.png')
    
    # Get image data as bytes instead of saving to a file
    image_bytes = imgkit.to_img(None)