CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-html2image

Package acting as a wrapper around the headless mode of existing web browsers to generate images from URLs and from HTML+CSS strings or files.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

html2image

Html2image is a lightweight Python package that provides a wrapper around the headless mode of existing web browsers to generate high-quality images from HTML/CSS content, URLs, and files. It supports Chrome, Chromium, and Edge browsers and offers both programmatic API and command-line interface capabilities.

Package Information

  • Package Name: html2image
  • Language: Python
  • Installation: pip install html2image

Core Imports

import html2image
from html2image import Html2Image

For CLI usage:

from html2image import main

For type annotations:

from typing import Union, List, Tuple

Basic Usage

from html2image import Html2Image

# Initialize with default settings
hti = Html2Image()

# Take screenshot of a URL
hti.screenshot(url='https://www.example.com', save_as='example.png')

# Take screenshot from HTML string
html_content = '<h1>Hello World!</h1><p>This is a test.</p>'
hti.screenshot(html_str=html_content, save_as='hello.png')

# Take screenshot with custom size
hti.screenshot(
    html_str='<h1>Custom Size</h1>', 
    save_as='custom.png',
    size=(800, 600)
)

# Batch processing multiple sources
hti.screenshot(
    url=['https://www.example.com', 'https://www.google.com'],
    save_as=['example.png', 'google.png']
)

Capabilities

Html2Image Class

The main class for generating screenshots from various sources including URLs, HTML strings, HTML files, and CSS content.

class Html2Image:
    def __init__(
        self,
        browser: str = 'chrome',
        browser_executable: str = None,
        browser_cdp_port: int = None,
        output_path: str = None,
        size: tuple = (1920, 1080),
        temp_path: str = None,
        keep_temp_files: bool = False,
        custom_flags: Union[list, str] = None,
        disable_logging: bool = False
    ):
        """
        Initialize Html2Image instance.
        
        Parameters:
        - browser: Browser type ('chrome', 'chromium', 'google-chrome', 
                  'google-chrome-stable', 'googlechrome', 'edge', 
                  'chrome-cdp', 'chromium-cdp')
        - browser_executable: Path to browser executable
        - browser_cdp_port: CDP port for CDP-enabled browsers
        - output_path: Output directory for screenshots (default: current directory)
        - size: Default screenshot dimensions as (width, height)
        - temp_path: Temporary files directory
        - keep_temp_files: Whether to preserve temporary files
        - custom_flags: Additional browser flags as list or string
        - disable_logging: Suppress browser logging
        """

Screenshot Generation

Main method for taking screenshots from multiple types of sources with flexible configuration options.

def screenshot(
    self,
    html_str: Union[list, str] = None,
    html_file: Union[list, str] = None,
    css_str: Union[list, str] = None,
    css_file: Union[list, str] = None,
    other_file: Union[list, str] = None,
    url: Union[list, str] = None,
    save_as: Union[list, str] = 'screenshot.png',
    size: Union[list, tuple] = None
) -> List[str]:
    """
    Take screenshots from various sources.
    
    Parameters:
    - html_str: HTML string(s) to screenshot
    - html_file: HTML file path(s) to screenshot
    - css_str: CSS string(s) to apply
    - css_file: CSS file path(s) to load
    - other_file: Other file path(s) to screenshot (e.g., SVG)
    - url: URL(s) to screenshot
    - save_as: Output filename(s)
    - size: Screenshot size(s) as (width, height) tuple(s)
    
    Returns:
    List of screenshot file paths
    """

URL Screenshots

Direct method for taking screenshots of web URLs.

def screenshot_url(
    self,
    url: str,
    output_file: str = 'screenshot.png',
    size: tuple = None
) -> None:
    """
    Take screenshot of a single URL.
    
    Parameters:
    - url: URL to screenshot
    - output_file: Output filename
    - size: Screenshot dimensions as (width, height)
    """

File Management

Methods for loading and managing HTML/CSS content in temporary files.

def load_str(self, content: str, as_filename: str) -> None:
    """
    Load HTML/CSS string content to temp file.
    
    Parameters:
    - content: HTML/CSS content
    - as_filename: Filename to save as in temp directory
    """

def load_file(self, src: str, as_filename: str = None) -> None:
    """
    Copy file to temp directory.
    
    Parameters:
    - src: Source file path
    - as_filename: Destination filename (default: original name)
    """

def screenshot_loaded_file(
    self,
    file: str,
    output_file: str = 'screenshot.png',
    size: tuple = None
) -> None:
    """
    Screenshot a previously loaded file from temp directory.
    
    Parameters:
    - file: Filename in temp directory
    - output_file: Output filename
    - size: Screenshot dimensions
    """

Properties

Configurable properties for controlling screenshot behavior.

@property
def output_path(self) -> str:
    """Get/set output directory path."""

@output_path.setter
def output_path(self, value: str) -> None:
    """Set output directory path."""

@property
def temp_path(self) -> str:
    """Get/set temporary files directory."""

@temp_path.setter
def temp_path(self, value: str) -> None:
    """Set temporary files directory."""

size: tuple
    # Screenshot dimensions as (width, height)

browser: Browser
    # Browser instance being used

Context Manager Support

Html2Image supports context manager protocol for automatic resource cleanup.

def __enter__(self) -> 'Html2Image':
    """Enter context manager."""

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
    """Exit context manager."""

Command Line Interface

CLI entry point for command-line usage of html2image functionality.

def main() -> None:
    """
    Command-line interface entry point.
    
    Exits with appropriate status code.
    """

CLI Size Validation

Utility function for validating size parameters in CLI usage.

def size_type(string: str) -> Tuple[int, int]:
    """
    Argument parser type function for size validation.
    
    Parameters:
    - string: Size string in format "width,height"
    
    Returns:
    (width, height) tuple
    
    Raises:
    argparse.ArgumentTypeError: For invalid format
    """

Browser Support

Html2image supports multiple browser engines:

  • Chrome/Chromium: Primary support with full feature set
  • Microsoft Edge: Full compatibility with Chrome features
  • Chrome DevTools Protocol (CDP): Enhanced control and debugging capabilities

Browser selection is automatic by default but can be customized via the browser parameter.

Environment Variables

Html2image recognizes several environment variables for browser executable discovery:

  • HTML2IMAGE_CHROME_BIN: Chrome executable path
  • HTML2IMAGE_CHROME_EXE: Chrome executable path
  • CHROME_BIN: Chrome executable path
  • CHROME_EXE: Chrome executable path
  • HTML2IMAGE_TOGGLE_ENV_VAR_LOOKUP: Toggle environment variable lookup

Error Handling

Common exceptions that may be raised:

  • ValueError: Invalid browser name or parameters
  • FileNotFoundError: Missing browser executable or input files
  • argparse.ArgumentTypeError: Invalid CLI argument format (CLI usage only)

Usage Examples

Context Manager Usage

from html2image import Html2Image

with Html2Image(size=(1200, 800)) as hti:
    hti.screenshot_url('https://www.python.org', 'python_homepage.png')
    hti.screenshot(
        html_str='<h1>Hello from context manager!</h1>',
        save_as='context_test.png'
    )

Custom Browser Configuration

from html2image import Html2Image

# Use specific browser executable
hti = Html2Image(
    browser='chrome',
    browser_executable='/usr/bin/google-chrome-stable',
    custom_flags=['--no-sandbox', '--disable-dev-shm-usage']
)

hti.screenshot_url('https://www.example.com', 'example.png')

Batch Processing with Different Sizes

from html2image import Html2Image

hti = Html2Image(output_path='./screenshots')

# Different sizes for different screenshots
urls = ['https://www.example.com', 'https://www.google.com']
sizes = [(1920, 1080), (800, 600)]
filenames = ['example_full.png', 'google_small.png']

hti.screenshot(url=urls, save_as=filenames, size=sizes)

HTML + CSS Processing

from html2image import Html2Image

hti = Html2Image()

html_content = '''
<div class="container">
    <h1>Styled Content</h1>
    <p>This content has custom styling applied.</p>
</div>
'''

css_content = '''
.container {
    background: linear-gradient(45deg, #f06, #4a90e2);
    padding: 20px;
    border-radius: 10px;
    color: white;
    font-family: Arial, sans-serif;
    text-align: center;
}
'''

hti.screenshot(
    html_str=html_content,
    css_str=css_content,
    save_as='styled_content.png'
)
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/html2image@2.0.x
Publish Source
CLI
Badge
tessl/pypi-html2image badge