### Complete imgkit Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
A comprehensive example demonstrating setup, configuration, and conversion of both a URL and an HTML file using imgkit. Includes error handling for each conversion step.
```python
import imgkit
import os
# Setup
output_dir = 'outputs'
os.makedirs(output_dir, exist_ok=True)
# Configure
config = imgkit.config(meta_tag_prefix='app-')
# Define options
options = {
'format': 'png',
'width': '1920',
'height': '1080',
'margin-top': '0.5in',
'margin-bottom': '0.5in',
'encoding': 'UTF-8',
'quiet': ''
}
# Convert URL
try:
imgkit.from_url(
'http://example.com',
os.path.join(output_dir, 'webpage.png'),
options=options,
config=config
)
print("✓ Converted URL")
except OSError as e:
print(f"✗ URL conversion failed: {e}")
# Convert HTML file
try:
imgkit.from_file(
'document.html',
os.path.join(output_dir, 'document.png'),
options=options,
css='style.css',
config=config
)
print("✓ Converted file")
except OSError as e:
print(f"✗ File conversion failed: {e}")
```
--------------------------------
### Headless System Setup for imgkit
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Install xvfb on your system for running imgkit on headless servers. Use the 'xvfb' option or configure it explicitly in imgkit for proper execution.
```bash
# Install xvfb
sudo apt-get install xvfb # Ubuntu/Debian
sudo yum install xorg-x11-server-Xvfb # CentOS/RHEL
```
--------------------------------
### Comprehensive Example with Options, TOC, and Cover
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
A complete example demonstrating conversion of an HTML file with custom options, a table of contents, and a cover page, specifying the cover to appear first.
```python
import imgkit
options = {
'format': 'png',
'margin-top': '0.75in',
'margin-bottom': '0.75in'
}
toc = {
'xsl-style-sheet': 'toc_style.xsl'
}
cover = 'cover_page.html'
imgkit.from_file(
'main_content.html',
'complete_document.png',
options=options,
toc=toc,
cover=cover,
cover_first=True
)
```
--------------------------------
### Install IMGKit
Source: https://github.com/jarrekk/imgkit/blob/master/README.md
Install the imgkit library using pip. This is the first step before using the library.
```python
pip install imgkit
```
--------------------------------
### Complete imgkit Configuration Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Provides a comprehensive example of imgkit configuration, including explicit paths for wkhtmltoimage and xvfb, meta tag prefix, conversion options, TOC options, CSS files, cover page, and more.
```python
import imgkit
# Create configuration with explicit paths
config = imgkit.config(
wkhtmltoimage='/usr/local/bin/wkhtmltoimage',
xvfb='/usr/bin/xvfb-run',
meta_tag_prefix='myapp-'
)
# Define conversion options
options = {
'format': 'png',
'width': '1920',
'height': '1080',
'margin-top': '1in',
'margin-bottom': '1in',
'encoding': 'UTF-8',
'quiet': ''
}
# Define TOC options
toc = {
'xsl-style-sheet': '/path/to/toc.xsl'
}
# Convert with all options
imgkit.from_file(
'document.html',
'output.png',
options=options,
css=['reset.css', 'layout.css'],
toc=toc,
cover='cover.html',
cover_first=True,
config=config
)
```
--------------------------------
### Install imgkit and wkhtmltoimage
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Install the imgkit Python library using pip. Ensure the wkhtmltoimage binary is installed and accessible in your system's PATH. Installation instructions vary by operating system.
```bash
# Install imgkit library
pip install imgkit
# Install wkhtmltoimage binary (required dependency)
# Linux: sudo apt-get install wkhtmltopdf
# macOS: brew install --cask wkhtmltopdf
# Windows: Download from http://wkhtmltopdf.org
```
--------------------------------
### File-like Object Source Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Demonstrates creating a Source object from a file-like object.
```python
from imgkit.source import Source
with open('page.html') as f:
src = Source(f, 'file')
print(src.isFileObj()) # True
```
--------------------------------
### Quick Start: Basic Conversions
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Demonstrates the three main functions for converting URLs, files, and strings to images.
```python
import imgkit
# Basic usage - three main functions
imgkit.from_url('http://example.com', 'out.jpg')
imgkit.from_file('page.html', 'out.jpg')
imgkit.from_string('
Hello
', 'out.jpg')
```
--------------------------------
### xvfb-run Installation for Headless Systems
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Install xvfb on Ubuntu/Debian systems to enable headless image conversion when a display server is not available.
```bash
# Ubuntu/Debian
sudo apt-get install xvfb
```
--------------------------------
### Default Configuration Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Demonstrates creating a Config object with default settings, relying on auto-detection for binaries and the default meta tag prefix.
```python
from imgkit import config
conf = config()
# Uses auto-detected wkhtmltoimage, no xvfb, prefix is 'imgkit-'
```
--------------------------------
### URL Source Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Demonstrates creating a Source object for a URL.
```python
from imgkit.source import Source
src = Source('http://example.com', 'url')
print(src.isUrl()) # True
```
--------------------------------
### Example with File, CSS, and Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Convert an HTML file to an image, applying multiple CSS files and specific conversion options.
```python
import imgkit
# HTML file and CSS
options = {
'format': 'png',
'width': '1024'
}
imgkit.from_file(
'document.html',
'output.png',
css=['global.css', 'print.css'],
options=options
)
```
--------------------------------
### File Path Source Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Demonstrates creating a Source object for a local file path.
```python
from imgkit.source import Source
src = Source('page.html', 'file')
print(src.isFile()) # True
```
--------------------------------
### Complete Conversion Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/START_HERE.md
Demonstrates a comprehensive conversion process including directory creation, configuration, and setting advanced options. Requires imgkit, os modules, and specifies output format, dimensions, and quiet mode.
```python
import imgkit
import os
# Create output directory
os.makedirs('output', exist_ok=True)
# Configure
config = imgkit.config(meta_tag_prefix='app-')
# Set options
options = {
'format': 'png',
'width': '1920',
'height': '1080',
'quiet': ''
}
```
--------------------------------
### HTML String Source Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Demonstrates creating a Source object from an HTML string.
```python
from imgkit.source import Source
html = 'Test
'
src = Source(html, 'string')
print(src.isString()) # True
```
--------------------------------
### Install xvfb on Servers
Source: https://github.com/jarrekk/imgkit/blob/master/README.md
Installs xvfb (X virtual framebuffer) on Ubuntu/Debian and CentOS/RHEL servers, which may be required for headless environments.
```bash
# at ubuntu server, etc.
sudo apt-get install xvfb
# at centos server, etc.
yum install xorg-x11-server-Xvfb
```
--------------------------------
### Install wkhtmltopdf on MacOSX
Source: https://github.com/jarrekk/imgkit/blob/master/README.md
Install wkhtmltopdf using the Homebrew package manager on MacOSX systems.
```bash
brew install --cask wkhtmltopdf
```
--------------------------------
### wkhtmltoimage Command Structure Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Illustrates the structure of the command passed to subprocess.Popen, including optional prefixes, global options, and source/output arguments.
```python
[
'/usr/bin/wkhtmltoimage',
'--format', 'png',
'--width', '1024',
'--quiet',
'toc',
'--xsl-style-sheet', 'toc.xsl',
'cover',
'cover.html',
'http://example.com',
'output.png'
]
```
--------------------------------
### wkhtmltoimage Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Provides an example of passing a dictionary of wkhtmltoimage options to customize the image output, including format, dimensions, margins, and encoding.
```python
import imgkit
options = {
'format': 'png',
'width': '1920',
'height': '1080',
'margin-top': '1in',
'margin-bottom': '1in',
'encoding': 'UTF-8'
}
imgkit.from_url('http://example.com', 'out.png', options=options)
```
--------------------------------
### Configure xvfb for CentOS/RHEL
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Installs xvfb on CentOS/RHEL systems and shows how to configure imgkit to use it for headless image generation from URLs.
```bash
sudo yum install xorg-x11-server-Xvfb
```
--------------------------------
### Install wkhtmltopdf on Debian/Ubuntu
Source: https://github.com/jarrekk/imgkit/blob/master/README.md
Install wkhtmltopdf using the apt-get package manager on Debian or Ubuntu systems. Note that repository versions may have reduced functionality.
```bash
sudo apt-get install wkhtmltopdf
```
--------------------------------
### Use xvfb with imgkit
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Demonstrates configuring imgkit to use xvfb for headless image generation from a URL. Ensure xvfb is installed and accessible.
```python
import imgkit
conf = imgkit.config(xvfb='/usr/bin/xvfb-run')
imgkit.from_url(
'http://example.com',
'out.png',
config=conf,
options={'xvfb': ''}
)
```
--------------------------------
### Handle 'No xvfb executable found' Error
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/errors.md
This example shows how to catch and handle the OSError when the xvfb executable is not found, which is common on headless servers. It includes setting up the config with an explicit xvfb path and enabling the xvfb option.
```Python
import imgkit
# Install xvfb:
# - Ubuntu/Debian: sudo apt-get install xvfb
# - CentOS/RHEL: sudo yum install xorg-x11-server-Xvfb
# Then use with explicit path:
config = imgkit.config(xvfb='/usr/bin/xvfb-run')
options = {'xvfb': ''} # Enable xvfb
try:
imgkit.from_url('http://example.com', 'out.png', config=config, options=options)
except OSError as e:
print(f"System error: {e}")
```
--------------------------------
### Convert URL with Headless System Option
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Converts a URL to an image using xvfb for headless environments. Ensure xvfb is installed and accessible.
```python
import imgkit
options = {'xvfb': ''}
imgkit.from_url('http://example.com', 'out.png', options=options)
```
--------------------------------
### Get wkhtmltoimage with Auto-detection
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Shows how to use get_wkhtmltoimage() when the path is not explicitly set, triggering auto-detection via system commands.
```python
from imgkit.config import Config
conf = Config() # wkhtmltoimage=''
path = conf.get_wkhtmltoimage()
# Searches PATH and returns first found binary path
```
--------------------------------
### isFileObj Method Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Checks if the source is a file-like object with a read() method.
```python
from imgkit.source import Source
with open('page.html') as f:
src = Source(f, 'file')
print(src.isFileObj()) # True
path_src = Source('page.html', 'file')
print(path_src.isFileObj()) # False
```
--------------------------------
### Get wkhtmltoimage with Explicit Path
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Demonstrates retrieving the wkhtmltoimage binary path after explicitly setting it in the Config object.
```python
from imgkit.config import Config
conf = Config(wkhtmltoimage='/usr/bin/wkhtmltoimage')
path = conf.get_wkhtmltoimage()
print(path) # Output: /usr/bin/wkhtmltoimage
```
--------------------------------
### Get Binary Image Output from URL
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Fetches an image from a URL and returns its binary content, which can then be saved to a file. Uses the 'quiet' option to suppress output.
```python
import imgkit
import os
output_dir = '.' # Replace with your desired output directory
config = imgkit.config() # Ensure config is initialized if needed
try:
img_bytes = imgkit.from_url(
'http://example.com',
False, # Set to False to get binary output
options={'quiet': ''},
config=config
)
with open(os.path.join(output_dir, 'binary.png'), 'wb') as f:
f.write(img_bytes)
print("✓ Got binary output")
except OSError as e:
print(f"✗ Binary output failed: {e}")
```
--------------------------------
### Handle CSS Injection Errors with Different Source Types
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/errors.md
This example illustrates how to correctly use the CSS parameter with imgkit and handle the IMGKit.SourceError that arises from attempting to use CSS with incompatible source types like URLs or multiple files. It shows correct usage with from_file, from_string, and demonstrates valid scenarios.
```Python
import imgkit
# Wrong - CSS with URL
try:
imgkit.from_url('http://example.com', 'out.png', css='style.css')
except imgkit.IMGKit.SourceError as e:
print(f"Source error: {e.message}")
# Correct - CSS with file
imgkit.from_file('page.html', 'out.png', css='style.css')
# Correct - CSS with string
html = 'Content'
imgkit.from_string(html, 'out.png', css='style.css')
# Correct - Multiple files, no CSS
files = ['page1.html', 'page2.html']
imgkit.from_file(files, 'out.png')
# Correct - URL with embedded styles
html = '''
Content
'''
imgkit.from_string(html, 'out.png')
```
--------------------------------
### CSS Injection: Prepending {}'.format(css_content, original_html)
```
--------------------------------
### Headless Server with xvfb Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Demonstrates configuring imgkit to use xvfb-run on a headless server by providing its path and triggering its usage.
```python
from imgkit import config, from_url
conf = config(xvfb='/usr/bin/xvfb-run')
from_url(
'http://example.com',
'out.png',
config=conf,
options={'xvfb': ''} # Triggers xvfb usage
)
```
--------------------------------
### isUrl Method Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Checks if the source type is a URL.
```python
from imgkit.source import Source
url_src = Source('http://example.com', 'url')
print(url_src.isUrl()) # True
file_src = Source('page.html', 'file')
print(file_src.isUrl()) # False
```
--------------------------------
### isString Method Example
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Checks if the source type is an HTML string.
```python
from imgkit.source import Source
html = 'Content'
str_src = Source(html, 'string')
print(str_src.isString()) # True
```
--------------------------------
### Initialize IMGKit from File with CSS
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/imgkit-class.md
Create an IMGKit instance to convert a local HTML file to an image, applying custom CSS. Specify output format using options.
```python
from imgkit import IMGKit
kit = IMGKit('page.html', 'file', css='style.css', options={'format': 'jpg'})
```
--------------------------------
### Initialize IMGKit from URL
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/imgkit-class.md
Create an IMGKit instance to convert a web URL to an image. Specify output format using options.
```python
from imgkit import IMGKit
kit = IMGKit('http://example.com', 'url', options={'format': 'png'})
```
--------------------------------
### Custom Binary Paths Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Illustrates how to instantiate a Config object with explicit paths for the wkhtmltoimage and xvfb-run binaries.
```python
from imgkit import config
conf = config(
wkhtmltoimage='/opt/bin/wkhtmltoimage',
xvfb='/opt/bin/xvfb-run'
)
```
--------------------------------
### Config Constructor
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Initializes the Config class with optional paths for wkhtmltoimage and xvfb binaries, and a custom meta tag prefix.
```APIDOC
## Config Constructor
### Description
Initializes the Config class with optional paths for wkhtmltoimage and xvfb binaries, and a custom meta tag prefix.
### Parameters
#### Path Parameters
- **wkhtmltoimage** (str) - Optional - Path to wkhtmltoimage binary. Empty string triggers auto-detection via `which` (Unix) or `where` (Windows).
- **xvfb** (str) - Optional - Path to xvfb-run binary. Empty string triggers auto-detection.
- **meta_tag_prefix** (str) - Optional - Prefix for HTML meta tag options. Used to parse `` tags. Default is 'imgkit-'.
### Attributes
- **wkhtmltoimage** (str) - Resolved path to wkhtmltoimage binary after first get_wkhtmltoimage() call.
- **xvfb** (str) - Resolved path to xvfb-run binary after first get_xvfb() call.
- **meta_tag_prefix** (str) - Prefix for meta tag parsing.
### Examples
**Default configuration:**
```python
from imgkit import config
conf = config()
# Uses auto-detected wkhtmltoimage, no xvfb, prefix is 'imgkit-'
```
**Custom binary paths:**
```python
from imgkit import config
conf = config(
wkhtmltoimage='/opt/bin/wkhtmltoimage',
xvfb='/opt/bin/xvfb-run'
)
```
**Custom meta tag prefix:**
```python
from imgkit import config
conf = config(meta_tag_prefix='mytool-')
html = """
Content
"""
import imgkit
imgkit.from_string(html, 'out.png', config=conf)
```
```
--------------------------------
### Functional API: With Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Demonstrates how to specify a custom path for the wkhtmltoimage binary using the config function.
```python
import imgkit
# With configuration
config = imgkit.config(wkhtmltoimage='/custom/path/wkhtmltoimage')
imgkit.from_url('http://example.com', 'out.png', config=config)
```
--------------------------------
### Convert HTML String to PNG
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Converts an HTML string to a PNG image file. Requires wkhtmltoimage to be installed and configured.
```python
import imgkit
import os
html = '''
Report
Generated with imgkit
'''
output_dir = '.' # Replace with your desired output directory
config = imgkit.config() # Ensure config is initialized if needed
try:
imgkit.from_string(
html,
os.path.join(output_dir, 'report.png'),
config=config
)
print("✓ Converted string")
except OSError as e:
print(f"✗ String conversion failed: {e}")
```
--------------------------------
### Use xvfb Option with IMGKit
Source: https://github.com/jarrekk/imgkit/blob/master/README.md
Enables the xvfb option in IMGKit, typically used in headless server environments after installing xvfb.
```python
{"xvfb": ""}
```
--------------------------------
### Initializing Source Objects
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Demonstrates how to initialize Source objects for both file paths and URLs. The `to_s()` method returns the source identifier.
```python
from imgkit.source import Source
path_src = Source('page.html', 'file')
print(path_src.to_s()) # 'page.html'
url_src = Source('http://example.com', 'url')
print(url_src.to_s()) # 'http://example.com'
```
--------------------------------
### Command Generation Algorithm: Global options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Shows the yielding of the wkhtmltoimage binary path and flattened options from the normalized options dictionary.
```python
yield wkhtmltoimage_path
for key, value in options.items():
yield key
yield value
```
--------------------------------
### Class-Based API: Instance Creation
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Shows how to create an instance of the IMGKit class for more granular control over the conversion process.
```python
from imgkit import IMGKit
# Create instance
kit = IMGKit('http://example.com', 'url', options={'format': 'png'})
```
--------------------------------
### Basic HTML to Image Conversions
Source: https://github.com/jarrekk/imgkit/blob/master/README.md
Demonstrates basic usage of imgkit for converting URLs, files, and strings to image files.
```python
import imgkit
imgkit.from_url('http://google.com', 'out.jpg')
imgkit.from_file('test.html', 'out.jpg')
imgkit.from_string('Hello!', 'out.jpg')
```
--------------------------------
### Configuration - Custom Paths
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Specify custom paths for the wkhtmltoimage and xvfb-run binaries if they are not in the system's PATH.
```APIDOC
## Custom Paths
```python
import imgkit
config = imgkit.config(
wkhtmltoimage='/opt/bin/wkhtmltoimage',
xvfb='/usr/bin/xvfb-run'
)
imgkit.from_url('http://example.com', 'out.png', config=config)
```
```
--------------------------------
### Get Image as Binary String
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/core-functions.md
Instead of saving to a file, retrieve the image data directly as a binary string. This is useful for further processing or in-memory operations.
```python
import imgkit
img_binary = imgkit.from_url('http://google.com', False)
# img_binary contains the PNG/JPG binary data
```
--------------------------------
### Command Generation Algorithm: xvfb prefix
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Demonstrates how the command generator yields the xvfb-run binary path and the -a flag when the --xvfb option is present.
```python
yield 'xvfb-run'
yield '-a'
```
--------------------------------
### Initialize IMGKit from HTML String
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/imgkit-class.md
Create an IMGKit instance to convert an HTML string directly to an image. Set image width using options.
```python
from imgkit import IMGKit
html = 'Test
'
kit = IMGKit(html, 'string', options={'width': '1024'})
```
--------------------------------
### Get Image as Bytes
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/imgkit-class.md
Generate an image from an IMGKit instance and retrieve its raw binary data without writing to disk. This is useful for further processing or in-memory storage.
```python
from imgkit import IMGKit
kit = IMGKit('http://example.com', 'url')
image_bytes = kit.to_img() # Returns bytes
with open('output.png', 'wb') as f:
f.write(image_bytes)
```
--------------------------------
### Convert Web Content to Image
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/START_HERE.md
Shows how to convert content from a URL, an HTML file with CSS, or an HTML string to an image file. Requires wkhtmltoimage binary and optionally xvfb.
```python
try:
# From URL
imgkit.from_url('http://example.com', 'output/webpage.png',
options=options, config=config)
# From file with CSS
imgkit.from_file('page.html', 'output/page.png',
css='style.css', options=options, config=config)
# From string
html = ''
imgkit.from_string(html, 'output/string.png', config=config)
except OSError as e:
print(f"Error: {e}")
```
--------------------------------
### Functional API: With Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Illustrates how to pass custom options, such as format and width, to the conversion functions.
```python
import imgkit
# With options
options = {'format': 'png', 'width': '1024'}
imgkit.from_file('page.html', 'out.png', options=options)
```
--------------------------------
### Handling wkhtmltoimage Reported Errors
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/errors.md
This code demonstrates how to catch and report OS errors that occur when wkhtmltoimage encounters invalid input, parameters, or inaccessible resources. It includes examples for invalid format options, inaccessible remote resources, and missing CSS files.
```python
import imgkit
# Invalid format option
try:
imgkit.from_string(html, 'out.png', options={'format': 'invalid'})
except OSError as e:
print(f"Error: {e}")
# Inaccessible remote resource
try:
imgkit.from_url('http://invalid.example.local', 'out.png', options={'quiet': ''})
except OSError as e:
print(f"Error: {e}")
# Invalid CSS path
try:
imgkit.from_file('page.html', 'out.png', css='missing.css')
except OSError as e:
print(f"Error: {e}")
```
--------------------------------
### Enable xvfb for Headless Server
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Enables the use of xvfb-run for headless server environments and sets the output format to PNG.
```python
options = {
'xvfb': '', # Enable xvfb-run
'format': 'png'
}
imgkit.from_url('http://example.com', 'out.png', options=options)
```
--------------------------------
### Lazy Initialization: Binary path detection
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Illustrates the caching mechanism in Config.get_wkhtmltoimage() and get_xvfb() to locate binary paths only when needed.
```python
if not self.wkhtmltoimage_path:
self.wkhtmltoimage_path = self.find_program('wkhtmltoimage')
return self.wkhtmltoimage_path
```
--------------------------------
### Command Generation Algorithm: Source (URLs)
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Illustrates yielding URL(s) when the source is one or more URLs.
```python
for url in source_urls:
yield url
```
--------------------------------
### Command Generation Algorithm: TOC section
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Illustrates yielding the 'toc' keyword and normalized toc options when toc options are provided.
```python
yield 'toc'
for key, value in toc_options.items():
yield key
yield value
```
--------------------------------
### HTML Meta Tags for Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Illustrates how to embed imgkit-specific configuration options (like format and width) directly within HTML meta tags in the source string.
```html
Content
```
```python
import imgkit
imgkit.from_string(html, 'out.png')
```
--------------------------------
### External CSS: Multiple Files
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Shows how to apply multiple external CSS files to style the generated image. Styles are applied in the order provided.
```python
imgkit.from_file('page.html', 'out.png', css=['style1.css', 'style2.css'])
```
--------------------------------
### Command Generation Algorithm: Cover section (cover_first=False)
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Demonstrates yielding the 'cover' keyword and cover path at the end of the command when cover_first is set to False.
```python
yield 'cover'
yield cover_path
```
--------------------------------
### Check and Create Output Directory
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Ensures the output directory exists before converting a URL to an image. Creates the directory if it does not exist.
```python
import imgkit
import os
output_path = 'output.png'
output_dir = os.path.dirname(output_path) or '.'
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
imgkit.from_url('http://example.com', output_path)
```
--------------------------------
### Create imgkit configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/core-functions.md
Initializes a configuration object for imgkit. This is useful for specifying custom paths to wkhtmltoimage or xvfb binaries, or for setting a custom prefix for meta tags.
```python
from imgkit import config
config(wkhtmltoimage='', xvfb='', meta_tag_prefix='imgkit-')
```
--------------------------------
### Using xvfb with imgkit
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Configure imgkit to use xvfb for headless environments. This can be done via options or by explicitly setting the xvfb path in the configuration.
```python
# Use in imgkit
options = {'xvfb': ''}
imgkit.from_url('http://example.com', 'out.png', options=options)
# Or explicitly configure
config = imgkit.config(xvfb='/usr/bin/xvfb-run')
imgkit.from_url('http://example.com', 'out.png',
config=config, options={'xvfb': ''})
```
--------------------------------
### Fixing X Server Connection Errors with xvfb
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/errors.md
Use this snippet to configure imgkit to run within a virtual X server using xvfb, essential for headless systems. It demonstrates setting up xvfb configuration and options.
```python
import imgkit
# Option 1: Install and configure xvfb
# sudo apt-get install xvfb
config = imgkit.config(xvfb='/usr/bin/xvfb-run')
options = {'xvfb': ''}
imgkit.from_url('http://example.com', 'out.png', config=config, options=options)
# Option 2: Run entire script within xvfb-run
# In shell: xvfb-run -a python script.py
```
--------------------------------
### Class-Based API: Inspect Command
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Demonstrates how to inspect the generated command-line arguments before executing the conversion.
```python
# Inspect command before execution
cmd = kit.command('output.png')
print(cmd)
```
--------------------------------
### Custom Meta Tag Prefix Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Shows how to set a custom prefix for meta tags and demonstrates its usage in imgkit.from_string.
```python
from imgkit import config
conf = config(meta_tag_prefix='mytool-')
html = """
Content
"""
import imgkit
imgkit.from_string(html, 'out.png', config=conf)
```
--------------------------------
### Source Constructor
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Initializes a Source object to handle HTML content from various sources like URLs, file paths, or strings. It validates file paths if the type is 'file'.
```APIDOC
## Constructor Source
### Description
Initializes a Source object to handle HTML content from various sources like URLs, file paths, or strings. It validates file paths if the type is 'file'.
### Parameters
#### Path Parameters
- **url_or_file** (str, list, or file-like) - Required - HTML source: URL, file path, list of URLs/paths, file-like object, or HTML string.
- **type_** (str) - Required - One of: `'url'`, `'file'`, or `'string'`. Determines interpretation of url_or_file.
### Behavior
For `'file'` type sources, validates that all file paths exist during initialization. Lists are expanded and each path is checked.
### Raises
- **OSError**: If file source path does not exist and type is `'file'`.
### Examples
**URL source:**
```python
from imgkit.source import Source
src = Source('http://example.com', 'url')
print(src.isUrl()) # True
```
**File path source:**
```python
from imgkit.source import Source
src = Source('page.html', 'file')
print(src.isFile()) # True
```
**HTML string source:**
```python
from imgkit.source import Source
html = 'Test
'
src = Source(html, 'string')
print(src.isString()) # True
```
**File-like object source:**
```python
from imgkit.source import Source
with open('page.html') as f:
src = Source(f, 'file')
print(src.isFileObj()) # True
```
```
--------------------------------
### Create Config with Custom Meta Tag Prefix
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Creates an imgkit configuration object using a custom prefix for HTML meta tags, allowing embedded wkhtmltoimage options.
```python
import imgkit
# Custom meta tag prefix
config3 = imgkit.config(meta_tag_prefix='mytool-')
imgkit.from_string(html, 'out.png', config=config3)
```
--------------------------------
### External CSS: Single File
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Demonstrates how to apply a single external CSS file to style the generated image.
```python
import imgkit
imgkit.from_file('page.html', 'out.png', css='style.css')
```
--------------------------------
### CSS Injection: Handling missing
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Demonstrates prepending the \n{}'.format(css_content, original_html)
```
--------------------------------
### Basic Meta Tag Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Configure basic conversion options like format, quality, and orientation using meta tags in HTML.
```html
Report
This page will be rendered as JPEG with landscape orientation.
```
--------------------------------
### imgkit Common Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Configure image output format, dimensions, quality, margins, and encoding. Use empty values for options like 'quiet' and 'xvfb' to enable them.
```python
{'format': 'png'}
```
```python
{'format': 'jpg'}
```
```python
{'width': '1024'}
```
```python
{'height': '768'}
```
```python
{'quality': '95'}
```
```python
{'margin-top': '1in', 'margin-left': '0.5in'}
```
```python
{'encoding': 'UTF-8'}
```
```python
{'quiet': ''}
```
```python
{'xvfb': ''}
```
--------------------------------
### Convert HTML File to PNG using pathlib
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Demonstrates converting an HTML file to a PNG image using the pathlib module for path manipulation. Creates an 'output' directory if it doesn't exist.
```python
import imgkit
from pathlib import Path
# Create output directory
output = Path('output')
output.mkdir(exist_ok=True)
# Convert with pathlib
imgkit.from_file(
'input.html',
str(output / 'result.png')
)
```
--------------------------------
### Set Format and Dimensions Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Configures output format, quality, and dimensions for the generated image.
```python
options = {
'format': 'jpeg',
'quality': '95',
'width': '1920',
'height': '1080'
}
imgkit.from_url('http://example.com', 'out.jpg', options=options)
```
--------------------------------
### Source Constructor
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/source-class.md
Initializes a Source object with a given HTML source and its type.
```python
Source(url_or_file, type_)
```
--------------------------------
### Create Default Config
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Creates a default configuration object for imgkit, automatically detecting binary paths.
```python
import imgkit
# Default configuration (auto-detect binaries, standard prefix)
config1 = imgkit.config()
```
--------------------------------
### Auto-detection of xvfb on Headless System
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Shows how to rely on auto-detection for the xvfb-run binary path on a headless system by leaving the xvfb parameter empty.
```python
from imgkit import config, from_url
conf = config() # xvfb=''
from_url(
'http://example.com',
'out.png',
config=conf,
options={'xvfb': ''} # Triggers auto-detection
)
```
--------------------------------
### Set String Value Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Configures wkhtmltoimage options using string values for format, dimensions, encoding, and margins.
```python
options = {
'format': 'png',
'width': '1024',
'height': '768',
'encoding': 'UTF-8',
'margin-top': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '1in',
'margin-right': '1in'
}
imgkit.from_url('http://example.com', 'out.png', options=options)
```
--------------------------------
### imgkit Low-Level API
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Utilize the low-level IMGKit API to create an instance, inspect the generated command, and execute the conversion to an image file.
```python
from imgkit import IMGKit
# Create instance
kit = IMGKit('http://example.com', 'url', options={'format': 'png'})
# Inspect command
cmd = kit.command('output.png')
print(cmd)
# Execute
kit.to_img('output.png')
```
--------------------------------
### IMGKit Constructor
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/imgkit-class.md
Initializes the IMGKit class to prepare for HTML to image conversion. It accepts various parameters to define the source, conversion options, configuration, and styling.
```APIDOC
## IMGKit Constructor
### Description
Initializes the IMGKit class to prepare for HTML to image conversion. It accepts various parameters to define the source, conversion options, configuration, and styling.
### Parameters
- **url_or_file** (str, list, or file-like) - Required - HTML source: URL, file path, file-like object, or string. String is passed as HTML content. List of URLs or file paths converts all to single image.
- **source_type** (str) - Required - One of: 'url', 'file', or 'string'. Determines how url_or_file is interpreted.
- **options** (dict) - Optional - Dictionary of wkhtmltoimage options. Keys may include or omit `--` prefix. See Configuration section for option format.
- **config** (Config) - Optional - Instance of imgkit.config() for custom binary paths or meta tag prefix.
- **toc** (dict) - Optional - Dictionary of table-of-contents options.
- **cover** (str) - Optional - URL or file path to HTML cover page.
- **cover_first** (bool) - Optional - If True, cover page appears before TOC.
- **css** (str or list) - Optional - Path to CSS file(s). Only valid for file or string sources.
### Raises
- **OSError** - If file source path does not exist.
- **OSError** - If wkhtmltoimage binary is not found.
- **IMGKit.SourceError** - If CSS is provided with URL source or list of files.
### Examples
**Create from URL:**
```python
from imgkit import IMGKit
kit = IMGKit('http://example.com', 'url', options={'format': 'png'})
```
**Create from file with CSS:**
```python
from imgkit import IMGKit
kit = IMGKit('page.html', 'file', css='style.css', options={'format': 'jpg'})
```
**Create from HTML string:**
```python
from imgkit import IMGKit
html = 'Test
'
kit = IMGKit(html, 'string', options={'width': '1024'})
```
```
--------------------------------
### TOC Configuration with File Input
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/configuration.md
Configure table-of-contents generation for an HTML file conversion by passing a dictionary of TOC options.
```python
import imgkit
toc = {
'xsl-style-sheet': 'toc.xsl',
'margin-top': '0.5in',
'text-size-shrink': '0.8'
}
imgkit.from_file('document.html', 'out.png', toc=toc)
```
--------------------------------
### Configuration - wkhtmltoimage Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Pass wkhtmltoimage specific options to customize the image output, such as format, dimensions, and encoding.
```APIDOC
## wkhtmltoimage Options
```python
import imgkit
options = {
'format': 'png',
'width': '1920',
'height': '1080',
'margin-top': '1in',
'margin-bottom': '1in',
'encoding': 'UTF-8'
}
imgkit.from_url('http://example.com', 'out.png', options=options)
```
```
--------------------------------
### imgkit Configuration
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/quick-reference.md
Configure imgkit by specifying explicit paths to the wkhtmltoimage and xvfb binaries. You can also customize the meta tag prefix used for configuration within HTML.
```python
# Explicit binary paths
config = imgkit.config(
wkhtmltoimage='/usr/local/bin/wkhtmltoimage',
xvfb='/usr/bin/xvfb-run'
)
# Custom meta tag prefix
config = imgkit.config(meta_tag_prefix='mytool-')
# Use config
imgkit.from_url('http://example.com', 'out.png', config=config)
```
--------------------------------
### imgkit.config
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/core-functions.md
Creates a Config instance for custom imgkit configuration, allowing specification of binary paths and meta tag prefixes.
```APIDOC
## config
Create a Config instance for custom imgkit configuration.
### Method
config(wkhtmltoimage='', xvfb='', meta_tag_prefix='imgkit-')
### Parameters
#### Path Parameters
- **wkhtmltoimage** (str) - Optional - Full path to wkhtmltoimage binary. If empty, imgkit attempts to locate via `which` (Unix) or `where` (Windows).
- **xvfb** (str) - Optional - Full path to xvfb-run binary. Required for headless systems without display server. If empty, auto-detects.
- **meta_tag_prefix** (str) - Optional - Prefix for HTML meta tag options in `from_string()`. For example, with default prefix, `` sets format to PNG.
### Return Type
Returns a `Config` instance that can be passed to `from_url()`, `from_file()`, or `from_string()`.
### Raises
- **OSError** - If wkhtmltoimage path is invalid and file cannot be read.
- **OSError** - If xvfb path is invalid and file cannot be read.
### Examples
**Custom wkhtmltoimage path:**
```python
import imgkit
conf = imgkit.config(wkhtmltoimage='/opt/bin/wkhtmltoimage')
imgkit.from_string(html_string, 'out.jpg', config=conf)
```
**With xvfb for headless servers:**
```python
import imgkit
conf = imgkit.config(
wkhtmltoimage='/usr/bin/wkhtmltoimage',
xvfb='/usr/bin/xvfb-run'
)
imgkit.from_string(html_string, 'out.jpg', config=conf, options={'xvfb': ''})
```
**Custom meta tag prefix:**
```python
import imgkit
conf = imgkit.config(meta_tag_prefix='custom-')
html = ''
imgkit.from_string(html, 'out.png', config=conf)
```
```
--------------------------------
### Configuration - External CSS
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Link external CSS files to style the HTML content before conversion.
```APIDOC
## External CSS
```python
import imgkit
imgkit.from_file('page.html', 'out.png', css='style.css')
imgkit.from_file('page.html', 'out.png', css=['style1.css', 'style2.css'])
```
```
--------------------------------
### Conversion with Custom Options
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/INDEX.md
Performs image conversion using a dictionary of custom options. Options like format, width, and quality can be specified.
```python
options = {'format': 'png', 'width': '1024', 'quality': '95'}
imgkit.from_url(url, 'out.png', options=options)
```
--------------------------------
### Error Handling for wkhtmltoimage
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Illustrates how to catch OSError when the wkhtmltoimage binary is not found or the specified path is not readable.
```python
from imgkit.config import Config
conf = Config(wkhtmltoimage='/invalid/path/wkhtmltoimage')
try:
conf.get_wkhtmltoimage()
except OSError as e:
print(f"Binary not found: {e}")
```
--------------------------------
### Table of Contents Generation
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/overview.md
Demonstrates how to generate a table of contents for the output image by providing an XSL stylesheet path.
```python
import imgkit
toc = {
'xsl-style-sheet': 'toc.xsl'
}
imgkit.from_file(
'document.html',
'out.png',
toc=toc
)
```
--------------------------------
### Command Generation Algorithm: Source (file path)
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Shows yielding the file path string when the source is a file path.
```python
yield source_path
```
--------------------------------
### command
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/imgkit-class.md
Generates the complete wkhtmltoimage command as a list of arguments, which can be useful for debugging or direct execution via subprocess.
```APIDOC
## command
### Description
Generate the complete wkhtmltoimage command as a list of arguments.
### Parameters
- **path** (str or None) - Optional - Output file path. If provided, appended as final argument. If None, `-` is appended to output to stdout.
### Return Type
List of command-line arguments ready to pass to subprocess.
### Examples
**Inspect the generated command:**
```python
from imgkit import IMGKit
kit = IMGKit('http://example.com', 'url', options={'format': 'png'})
cmd = kit.command('output.png')
print(cmd)
# Output: ['/usr/bin/wkhtmltoimage', '--format', 'png', 'http://example.com', 'output.png']
```
```
--------------------------------
### Config Class Definition
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/api-reference/config-class.md
Defines the Config class for setting up wkhtmltoimage, xvfb-run, and meta tag prefix.
```python
from imgkit import config
from imgkit.config import Config
class Config:
"""Config class to configure wkhtmltoimage, xvfb-run and meta tag prefix."""
```
--------------------------------
### Thread-Safe URL Conversion with Separate IMGKit Instances
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Demonstrates the recommended pattern for concurrent URL conversions using multiple threads. Each thread should instantiate its own IMGKit object to ensure thread safety, as imgkit is not thread-safe for shared instances.
```Python
import imgkit
import threading
def convert_url(url):
# Each thread gets its own IMGKit instance
imgkit.from_url(url, 'out.png')
threads = [threading.Thread(target=convert_url, args=(url,))
for url in urls]
for t in threads:
t.start()
for t in threads:
t.join()
```
--------------------------------
### Command Generation Algorithm: Output (file path)
Source: https://github.com/jarrekk/imgkit/blob/master/_autodocs/architecture.md
Shows yielding the output path string when a path is specified for the output.
```python
yield output_path
```