html2image

repository·master·Indexed 19 days ago

https://github.com/vgalin/html2image

A lightweight Python wrapper around headless web browsers (Chrome, Chromium, or Edge) used to generate images from URLs, HTML/CSS strings, or files. It provides both a Python API via the Html2Image class and a Command Line Interface (CLI) for batch processing screenshots with customizable resolutions and browser flags.

Tokens
6.7K
Snippets
18
Records
22
Agent score
63%

What's inside html2image

  1. Install html2image

    master

    Install the html2image package using pip or uv.

    Prerequisite: You must have at least one of the following browsers installed on your machine:

    • Google Chrome (Windows, MacOS)
    • Chromium Browser (Linux)
    • Microsoft Edge
    pip install --upgrade html2image
    uv pip install html2image
  2. Run html2image via Docker

    master

    To test the package and CLI without local installation, you can use a Docker container. The container includes html2image and chromium.

    1. Clone the repository and enter the directory.
    2. Build the image: docker build -t html2image .
    3. Run and enter the container: docker run -it html2image /bin/bash

    You can use Docker volumes to bind local directories to the container to retrieve generated images or load local HTML/CSS/Python files.

    git clone https://github.com/vgalin/html2image.git
    cd html2image
    docker build -t html2image .
    docker run -it html2image /bin/bash
  3. Use the html2image CLI

    master

    The html2image package includes a Command Line Interface (CLI) accessible via the hti or html2image commands. It allows you to generate screenshots from URLs, HTML files, HTML strings, or other files (like SVGs) directly from your terminal.

    Quick Start Examples

    Screenshot a URL with specific size and name:

    hti --url https://example.com --save-as example_page.png --size 1280,720

    Screenshot multiple HTML files with a common CSS file:

    hti --html-file page1.html page2.html --css-file common_styles.css --save-as shot1.jpg shot2.jpg

    Screenshot an HTML string with custom browser flags:

    hti --html-string "<h1>Test</h1><p>Content</p>" --custom-flags '--no-sandbox' -v
    hti --url https://example.com --save-as example_page.png --size 1280,720
  4. Troubleshooting: Common Questions

    master

    Full Page Screenshots

    Full page screenshots are not currently supported because the library relies on headless Chrome/Chromium modes which do not provide an easy way to request a full page capture. You may need to estimate the page size manually.

    Adding Delays

    You can add delays before a screenshot is taken by using --custom-flags to pass specific browser flags.

    Performance

    For high-volume screenshot tasks, use Parallel Processing or Multiprocessing to speed up the process.

    Since extensions are not supported in headless Chrome, you cannot use extensions like "I don't care about cookies". Instead, retrieve the page source code, modify it to remove/hide the element, and then screenshot the modified source.

  5. Batch processing with lists in screenshot()

    master

    You can pass lists to the screenshot() method parameters to perform batch operations.

    Batching Patterns:

    • One filename for multiple inputs: If save_as is a single string, outputs will be suffixed (e.g., ABC_0.png, ABC_1.png).
    • Multiple filenames for multiple inputs: If save_as is a list, it maps 1:1 to the input list.
    • Multiple resolutions: If size is a list, it applies different sizes to each item. If the list is shorter than the inputs, the last size is repeated.
    • Applying CSS to multiple HTML inputs: You can pass a single CSS string to multiple HTML strings, or a list of CSS strings to match a list of HTML strings.
    # Create three files from one filename (outputs ABC_0.png, ABC_1.png, ABC_2.png)
    hti.screenshot(html_str=['A', 'B', 'C'], save_as='ABC.png')
    
    # Create three files from different filenames (outputs A.png, B.png, C.png)
    hti.screenshot(html_str=['A', 'B', 'C'], save_as=['A.png', 'B.png', 'C.png'])
    
    # Multiple screenshots with different sizes
    # If not enough sizes are given, the last size in the list will be repeated
    hti.screenshot(
        html_str=['A', 'B', 'C', 'D'],
        size=[(100, 50), (100, 100), (50, 50)]
    )
    
    # Apply multiple CSS strings to multiple HTML strings
    hti.screenshot(
        html_str=['A', 'B'],
        css_str=['body {background: red;}', 'body {font-size: 50px;}']
    )
  6. Take screenshots with the screenshot() method

    master

    The screenshot() method is the primary way to generate images. It returns a list containing the file path(s) of the generated screenshot(s).

    Supported Input Parameters:

    • url: A URL string to capture.
    • html_file: Path to an HTML file.
    • css_file: Path to a CSS file.
    • html_str: An HTML string.
    • css_str: A CSS string.
    • other_file: Path to other file types (e.g., .svg).

    Optional Parameters:

    • size: A 2-tuple (width, height) to override the instance default.
    • save_as: A string or list of strings to specify the output filename(s).
    from html2image import Html2Image
    hti = Html2Image()
    
    # URL to image
    hti.screenshot(url='https://www.python.org', save_as='python_org.png')
    
    # HTML & CSS strings to image
    html = "<h1> Title </h1>" 
    css = "body {background: red;}"
    hti.screenshot(html_str=html, css_str=css, save_as='red_page.png')
    
    # HTML & CSS files to image
    hti.screenshot(html_file='page.html', css_file='style.css', save_as='page.png')
    
    # Other files (e.g. SVG)
    hti.screenshot(other_file='star.svg')
  7. Configure custom browser flags

    master

    You can pass custom command-line flags to the underlying headless browser (e.g., to hide scrollbars, add delays, or use --no-sandbox when running as root).

    Warning: Providing custom_flags or manually setting hti.browser.flags will override and replace the default flags (--default-background-color=000000 and --hide-scrollbars).

    Common Use Case: Adding a delay To wait for animations to finish, use the --virtual-time-budget flag with Chrome/Chromium.

    # At instantiation
    hti = Html2Image(custom_flags=['--virtual-time-budget=10000', '--hide-scrollbars'])
    
    # Or after instantiation
    hti.browser.flags = ['--my_flag', '--no-sandbox']
  8. Instantiate the Html2Image class

    master

    To use the package, import Html2Image and create an instance. You can configure several parameters during instantiation or update them on the instance later.

    Constructor Arguments:

    • browser: The browser to use. Options: 'chrome' (default) or 'edge'.
    • browser_executable: Path or command to the specific browser executable.
    • output_path: Folder where screenshots are saved. Defaults to the current working directory.
    • size: A 2-tuple (width, height) for screenshot resolution. Defaults to (1920, 1080).
    • temp_path: Path for temporary resources. Defaults to %TEMP%/html2image (Windows) or /tmp/html2image (Linux/MacOS).
    • keep_temp_files: If True, temporary files in temp_path are not automatically removed. Defaults to False.
    from html2image import Html2Image
    
    # Basic instantiation
    hti = Html2Image()
    
    # Custom configuration
    hti = Html2Image(size=(500, 200), browser='edge')
    
    # Updating configuration after instantiation
    hti.size = (500, 200)
    hti.output_path = 'my_screenshot_folder'
  9. Configure browser and output settings

    master

    The Html2Image instance allows fine-grained control over where files are saved and how the browser behaves.

    Output Path

    The output_path attribute determines where screenshots are saved. It is always converted to an absolute path. Setting this attribute also ensures the directory exists.

    h2i.output_path = '/absolute/path/to/images'

    Temporary Files

    The temp_path attribute defines where intermediate HTML/CSS files are stored. If not provided, it defaults to the system's /tmp or %TMP% directory under a subfolder named html2image.

    If keep_temp_files is set to False (default), the class will attempt to remove temporary files after they are used in screenshot() or screenshot_loaded_file() calls.

  10. Reference: CLI Screenshot Output Options

    master

    Control how the resulting images are named and sized.

    | Argument | Description | Example |
    |----------|-------------|---------|
    | `-S, --save-as [FILENAME ...]` | Filename(s) for output images. If not provided or fewer names than items, names are auto-generated (e.g., `screenshot.png`, `screenshot_0.png`). | `hti -U python.org example.com -S py.png ex.png`  |
    | `-s, --size [W,H ...]`| Size(s) screenshots as `Width,Height`. If one W,H pair is given, it applies to all screenshots. If multiple W,H pairs are given, they apply to corresponding screenshots sequentially; if fewer pairs than items, the last pair is repeated. If omitted, the library's default (1920,1080) is used. Width and height must be positive integers. | `hti -U python.org --size 800,600` <br> `hti -U python.org example.com -s 800,600 1024,768` |
  11. Reference: CLI General Options

    master

    Control logging and verbosity.

    | Argument | Description | Example |
    |----------|-------------|---------|
    | `-q, --quiet`| Suppress informational output from html2image library (sets `disable_logging=True`). | `hti -U python.org -q` |
    | `-v, --verbose` | Enable verbose output, including browser commands if supported by the browser handler.  | `hti -U python.org -v` |
  12. Reference: CLI Configuration Arguments

    master

    These arguments configure the underlying Html2Image instance behavior, such as browser selection and file paths.

    | Argument | Description | Example |
    |----------|-------------|---------|
    | `-h, --help` | Show the help message and exit. | `hti --help`  |
    | `-o, --output-path PATH` | Directory to save screenshots. (Default: current working directory)| `hti --url example.com -o my_images/`  |
    | `--browser BROWSER`| Browser to use. Choices: `chrome`, `chromium`, `google-chrome`, `google-chrome-stable`, `googlechrome`, `edge`, `chrome-cdp`, `chromium-cdp`. (Default: `chrome`)| `hti --url example.com --browser edge` |
    | `--browser-executable EXECUTABLE_PATH` | Path to the browser executable. Auto-detected if not provided. | `hti --browser-executable /usr/bin/google-chrome-stable`|
    | `--cdp-port PORT`  | CDP port for CDP-enabled browsers (e.g., `chrome-cdp`). (Default: library-dependent)| `hti --browser chrome-cdp --cdp-port 9222 --url example.com`  |
    | `--temp-path TEMP_DIR_PATH` | Directory for temporary files. (Default: system temp directory in an `html2image` subfolder)  | `hti --html-file page.html --temp-path /my/tmp`|
    | `--keep-temp-files`| Do not delete temporary files after screenshot generation.| `hti --html-file page.html --keep-temp-files`  |
    | `--custom-flags [FLAG ...]` | Custom flags to pass to the browser (e.g., `'--no-sandbox' '--disable-gpu'`). If provided, these flags will be used. | `hti --url example.com --custom-flags '--no-sandbox' '--disable-gpu'` <br> `hti --url example.com --custom-flags '--no-sandbox --disable-gpu'` |