0
# html2image
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: html2image
7
- **Language**: Python
8
- **Installation**: `pip install html2image`
9
10
## Core Imports
11
12
```python
13
import html2image
14
from html2image import Html2Image
15
```
16
17
For CLI usage:
18
```python
19
from html2image import main
20
```
21
22
For type annotations:
23
```python
24
from typing import Union, List, Tuple
25
```
26
27
## Basic Usage
28
29
```python
30
from html2image import Html2Image
31
32
# Initialize with default settings
33
hti = Html2Image()
34
35
# Take screenshot of a URL
36
hti.screenshot(url='https://www.example.com', save_as='example.png')
37
38
# Take screenshot from HTML string
39
html_content = '<h1>Hello World!</h1><p>This is a test.</p>'
40
hti.screenshot(html_str=html_content, save_as='hello.png')
41
42
# Take screenshot with custom size
43
hti.screenshot(
44
html_str='<h1>Custom Size</h1>',
45
save_as='custom.png',
46
size=(800, 600)
47
)
48
49
# Batch processing multiple sources
50
hti.screenshot(
51
url=['https://www.example.com', 'https://www.google.com'],
52
save_as=['example.png', 'google.png']
53
)
54
```
55
56
## Capabilities
57
58
### Html2Image Class
59
60
The main class for generating screenshots from various sources including URLs, HTML strings, HTML files, and CSS content.
61
62
```python { .api }
63
class Html2Image:
64
def __init__(
65
self,
66
browser: str = 'chrome',
67
browser_executable: str = None,
68
browser_cdp_port: int = None,
69
output_path: str = None,
70
size: tuple = (1920, 1080),
71
temp_path: str = None,
72
keep_temp_files: bool = False,
73
custom_flags: Union[list, str] = None,
74
disable_logging: bool = False
75
):
76
"""
77
Initialize Html2Image instance.
78
79
Parameters:
80
- browser: Browser type ('chrome', 'chromium', 'google-chrome',
81
'google-chrome-stable', 'googlechrome', 'edge',
82
'chrome-cdp', 'chromium-cdp')
83
- browser_executable: Path to browser executable
84
- browser_cdp_port: CDP port for CDP-enabled browsers
85
- output_path: Output directory for screenshots (default: current directory)
86
- size: Default screenshot dimensions as (width, height)
87
- temp_path: Temporary files directory
88
- keep_temp_files: Whether to preserve temporary files
89
- custom_flags: Additional browser flags as list or string
90
- disable_logging: Suppress browser logging
91
"""
92
```
93
94
### Screenshot Generation
95
96
Main method for taking screenshots from multiple types of sources with flexible configuration options.
97
98
```python { .api }
99
def screenshot(
100
self,
101
html_str: Union[list, str] = None,
102
html_file: Union[list, str] = None,
103
css_str: Union[list, str] = None,
104
css_file: Union[list, str] = None,
105
other_file: Union[list, str] = None,
106
url: Union[list, str] = None,
107
save_as: Union[list, str] = 'screenshot.png',
108
size: Union[list, tuple] = None
109
) -> List[str]:
110
"""
111
Take screenshots from various sources.
112
113
Parameters:
114
- html_str: HTML string(s) to screenshot
115
- html_file: HTML file path(s) to screenshot
116
- css_str: CSS string(s) to apply
117
- css_file: CSS file path(s) to load
118
- other_file: Other file path(s) to screenshot (e.g., SVG)
119
- url: URL(s) to screenshot
120
- save_as: Output filename(s)
121
- size: Screenshot size(s) as (width, height) tuple(s)
122
123
Returns:
124
List of screenshot file paths
125
"""
126
```
127
128
### URL Screenshots
129
130
Direct method for taking screenshots of web URLs.
131
132
```python { .api }
133
def screenshot_url(
134
self,
135
url: str,
136
output_file: str = 'screenshot.png',
137
size: tuple = None
138
) -> None:
139
"""
140
Take screenshot of a single URL.
141
142
Parameters:
143
- url: URL to screenshot
144
- output_file: Output filename
145
- size: Screenshot dimensions as (width, height)
146
"""
147
```
148
149
### File Management
150
151
Methods for loading and managing HTML/CSS content in temporary files.
152
153
```python { .api }
154
def load_str(self, content: str, as_filename: str) -> None:
155
"""
156
Load HTML/CSS string content to temp file.
157
158
Parameters:
159
- content: HTML/CSS content
160
- as_filename: Filename to save as in temp directory
161
"""
162
163
def load_file(self, src: str, as_filename: str = None) -> None:
164
"""
165
Copy file to temp directory.
166
167
Parameters:
168
- src: Source file path
169
- as_filename: Destination filename (default: original name)
170
"""
171
172
def screenshot_loaded_file(
173
self,
174
file: str,
175
output_file: str = 'screenshot.png',
176
size: tuple = None
177
) -> None:
178
"""
179
Screenshot a previously loaded file from temp directory.
180
181
Parameters:
182
- file: Filename in temp directory
183
- output_file: Output filename
184
- size: Screenshot dimensions
185
"""
186
```
187
188
### Properties
189
190
Configurable properties for controlling screenshot behavior.
191
192
```python { .api }
193
@property
194
def output_path(self) -> str:
195
"""Get/set output directory path."""
196
197
@output_path.setter
198
def output_path(self, value: str) -> None:
199
"""Set output directory path."""
200
201
@property
202
def temp_path(self) -> str:
203
"""Get/set temporary files directory."""
204
205
@temp_path.setter
206
def temp_path(self, value: str) -> None:
207
"""Set temporary files directory."""
208
209
size: tuple
210
# Screenshot dimensions as (width, height)
211
212
browser: Browser
213
# Browser instance being used
214
```
215
216
### Context Manager Support
217
218
Html2Image supports context manager protocol for automatic resource cleanup.
219
220
```python { .api }
221
def __enter__(self) -> 'Html2Image':
222
"""Enter context manager."""
223
224
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
225
"""Exit context manager."""
226
```
227
228
### Command Line Interface
229
230
CLI entry point for command-line usage of html2image functionality.
231
232
```python { .api }
233
def main() -> None:
234
"""
235
Command-line interface entry point.
236
237
Exits with appropriate status code.
238
"""
239
```
240
241
### CLI Size Validation
242
243
Utility function for validating size parameters in CLI usage.
244
245
```python { .api }
246
def size_type(string: str) -> Tuple[int, int]:
247
"""
248
Argument parser type function for size validation.
249
250
Parameters:
251
- string: Size string in format "width,height"
252
253
Returns:
254
(width, height) tuple
255
256
Raises:
257
argparse.ArgumentTypeError: For invalid format
258
"""
259
```
260
261
## Browser Support
262
263
Html2image supports multiple browser engines:
264
265
- **Chrome/Chromium**: Primary support with full feature set
266
- **Microsoft Edge**: Full compatibility with Chrome features
267
- **Chrome DevTools Protocol (CDP)**: Enhanced control and debugging capabilities
268
269
Browser selection is automatic by default but can be customized via the `browser` parameter.
270
271
## Environment Variables
272
273
Html2image recognizes several environment variables for browser executable discovery:
274
275
- `HTML2IMAGE_CHROME_BIN`: Chrome executable path
276
- `HTML2IMAGE_CHROME_EXE`: Chrome executable path
277
- `CHROME_BIN`: Chrome executable path
278
- `CHROME_EXE`: Chrome executable path
279
- `HTML2IMAGE_TOGGLE_ENV_VAR_LOOKUP`: Toggle environment variable lookup
280
281
## Error Handling
282
283
Common exceptions that may be raised:
284
285
- `ValueError`: Invalid browser name or parameters
286
- `FileNotFoundError`: Missing browser executable or input files
287
- `argparse.ArgumentTypeError`: Invalid CLI argument format (CLI usage only)
288
289
## Usage Examples
290
291
### Context Manager Usage
292
293
```python
294
from html2image import Html2Image
295
296
with Html2Image(size=(1200, 800)) as hti:
297
hti.screenshot_url('https://www.python.org', 'python_homepage.png')
298
hti.screenshot(
299
html_str='<h1>Hello from context manager!</h1>',
300
save_as='context_test.png'
301
)
302
```
303
304
### Custom Browser Configuration
305
306
```python
307
from html2image import Html2Image
308
309
# Use specific browser executable
310
hti = Html2Image(
311
browser='chrome',
312
browser_executable='/usr/bin/google-chrome-stable',
313
custom_flags=['--no-sandbox', '--disable-dev-shm-usage']
314
)
315
316
hti.screenshot_url('https://www.example.com', 'example.png')
317
```
318
319
### Batch Processing with Different Sizes
320
321
```python
322
from html2image import Html2Image
323
324
hti = Html2Image(output_path='./screenshots')
325
326
# Different sizes for different screenshots
327
urls = ['https://www.example.com', 'https://www.google.com']
328
sizes = [(1920, 1080), (800, 600)]
329
filenames = ['example_full.png', 'google_small.png']
330
331
hti.screenshot(url=urls, save_as=filenames, size=sizes)
332
```
333
334
### HTML + CSS Processing
335
336
```python
337
from html2image import Html2Image
338
339
hti = Html2Image()
340
341
html_content = '''
342
<div class="container">
343
<h1>Styled Content</h1>
344
<p>This content has custom styling applied.</p>
345
</div>
346
'''
347
348
css_content = '''
349
.container {
350
background: linear-gradient(45deg, #f06, #4a90e2);
351
padding: 20px;
352
border-radius: 10px;
353
color: white;
354
font-family: Arial, sans-serif;
355
text-align: center;
356
}
357
'''
358
359
hti.screenshot(
360
html_str=html_content,
361
css_str=css_content,
362
save_as='styled_content.png'
363
)
364
```