Repository navigation
Expand file tree
/
Copy pathhtml2pdf
More file actions
327 lines (279 loc) · 11.7 KB
/
Copy pathhtml2pdf
File metadata and controls
327 lines (279 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python3
"""html2pdf — Convert HTML to PDF via headless Chrome.
Accepts a local HTML file or a URL as input. Downloads remote images
referenced via <img src="https://..."> so Chrome can resolve them locally.
Outputs either a PDF file or base64-encoded PDF to stdout (for piping to
agent tool results).
Usage:
html2pdf input.html # → input.pdf (same dir)
html2pdf input.html -o report.pdf # → report.pdf
html2pdf input.html --base64 # → base64 string to stdout
html2pdf input.html --base64 --stdout # (same — explicit)
html2pdf https://example.com -o page.pdf # URL input
html2pdf input.html --paper a4 # paper size (default: a4)
html2pdf input.html --paper letter
html2pdf input.html --landscape # landscape orientation
html2pdf input.html --no-header # suppress Chrome header/footer
html2pdf input.html --margins "25mm 20mm" # custom margins (top right bottom left)
html2pdf input.html --fetch-images # download remote <img src> for offline render
html2pdf input.html --timeout 60 # Chrome timeout in seconds (default: 30)
html2pdf input.html --inject-css style.css # inject additional CSS before render
html2pdf input.html --scale 1.5 # print scale factor (default: 1.0)
Requires: google-chrome-stable (or chromium) on PATH.
License: MIT
Repository: https://github.com/nicedoc/html2pdf-cli
"""
__version__ = "1.0.0"
import argparse
import base64
import os
import re
import subprocess
import sys
import tempfile
import urllib.request
import urllib.error
from pathlib import Path
CHROME_NAMES = [
"google-chrome-stable",
"google-chrome",
"chromium-browser",
"chromium",
]
PAPER_SIZES = {
"a3": (11.69, 16.54),
"a4": (8.27, 11.69),
"a5": (5.83, 8.27),
"letter": (8.5, 11.0),
"legal": (8.5, 14.0),
"tabloid": (11.0, 17.0),
}
IMG_SRC_RE = re.compile(
r'(<img\s[^>]*?\bsrc\s*=\s*)([\"\'])(\s*https?://[^\"\']+)\2',
re.IGNORECASE,
)
def find_chrome() -> str:
"""Locate a Chrome/Chromium binary on PATH."""
for name in CHROME_NAMES:
try:
subprocess.run(
[name, "--version"],
capture_output=True,
timeout=5,
)
return name
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
print("Error: no Chrome or Chromium found on PATH.", file=sys.stderr)
print(f"Looked for: {', '.join(CHROME_NAMES)}", file=sys.stderr)
sys.exit(1)
def download_image(url: str, dest_dir: str) -> str | None:
"""Download a remote image to dest_dir. Returns local filename or None."""
filename = re.sub(r'[^\w.\-]', '_', url.split('/')[-1].split('?')[0])
if not filename or len(filename) > 200:
filename = f"img_{abs(hash(url)) % 10**8}.bin"
dest = os.path.join(dest_dir, filename)
if os.path.exists(dest):
return filename
try:
req = urllib.request.Request(url, headers={"User-Agent": "html2pdf/1.0"})
with urllib.request.urlopen(req, timeout=15) as resp:
with open(dest, "wb") as f:
f.write(resp.read())
return filename
except (urllib.error.URLError, OSError, TimeoutError) as e:
print(f"Warning: failed to download {url}: {e}", file=sys.stderr)
return None
def fetch_remote_images(html: str, work_dir: str) -> str:
"""Download remote <img src="https://..."> images and rewrite to local refs."""
img_dir = os.path.join(work_dir, "_images")
os.makedirs(img_dir, exist_ok=True)
def replacer(m: re.Match) -> str:
prefix, quote, url = m.group(1), m.group(2), m.group(3).strip()
local_name = download_image(url, img_dir)
if local_name:
local_path = os.path.join("_images", local_name)
return f'{prefix}{quote}{local_path}{quote}'
return m.group(0)
return IMG_SRC_RE.sub(replacer, html)
def inject_css(html: str, css_path: str) -> str:
"""Inject a CSS file as a <style> block before </head> or at top of <body>."""
with open(css_path) as f:
css = f.read()
style_tag = f"\n<style>\n{css}\n</style>\n"
if "</head>" in html:
return html.replace("</head>", style_tag + "</head>", 1)
if "<body" in html:
idx = html.index("<body")
close = html.index(">", idx) + 1
return html[:close] + style_tag + html[close:]
return style_tag + html
def resolve_input(source: str, work_dir: str) -> str:
"""Resolve input to a local file path. Downloads URLs to work_dir."""
if source.startswith(("http://", "https://")):
dest = os.path.join(work_dir, "input.html")
try:
req = urllib.request.Request(
source, headers={"User-Agent": "html2pdf/1.0"}
)
with urllib.request.urlopen(req, timeout=30) as resp:
with open(dest, "wb") as f:
f.write(resp.read())
except (urllib.error.URLError, OSError) as e:
print(f"Error: failed to fetch {source}: {e}", file=sys.stderr)
sys.exit(1)
return dest
if not os.path.isfile(source):
print(f"Error: file not found: {source}", file=sys.stderr)
sys.exit(1)
return os.path.abspath(source)
def build_chrome_args(
chrome: str,
input_path: str,
output_path: str,
paper: str,
landscape: bool,
no_header: bool,
scale: float,
) -> list[str]:
"""Assemble the Chrome headless command."""
args = [
chrome,
"--headless",
"--no-sandbox",
"--disable-gpu",
"--disable-software-rasterizer",
"--disable-dev-shm-usage",
f"--print-to-pdf={output_path}",
]
if no_header:
args.append("--print-to-pdf-no-header")
paper_key = paper.lower()
if paper_key in PAPER_SIZES:
w, h = PAPER_SIZES[paper_key]
if landscape:
w, h = h, w
args.extend([f"--paper-width={w}", f"--paper-height={h}"])
else:
parts = paper_key.split("x")
if len(parts) == 2:
try:
w, h = float(parts[0]), float(parts[1])
if landscape:
w, h = h, w
args.extend([f"--paper-width={w}", f"--paper-height={h}"])
except ValueError:
print(f"Warning: unknown paper size '{paper}', using Chrome default.", file=sys.stderr)
if scale != 1.0:
args.append(f"--scale={scale}")
args.append(f"file://{input_path}")
return args
def main() -> None:
parser = argparse.ArgumentParser(
description="Convert HTML to PDF via headless Chrome.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__.split("Requires:")[0],
)
parser.add_argument("input", help="HTML file path or URL")
parser.add_argument("-o", "--output", help="Output PDF path (default: <input>.pdf)")
parser.add_argument("--base64", action="store_true", help="Output base64-encoded PDF to stdout")
parser.add_argument("--stdout", action="store_true", help="Alias for --base64")
parser.add_argument("--paper", default="a4", help="Paper size: a4, letter, legal, tabloid, a3, a5, or WxH in inches (default: a4)")
parser.add_argument("--landscape", action="store_true", help="Landscape orientation")
parser.add_argument("--no-header", action="store_true", help="Suppress default Chrome header/footer")
parser.add_argument("--margins", help="Page margins (CSS format, applied via injected style)")
parser.add_argument("--fetch-images", action="store_true", help="Download remote <img src> images for offline render")
parser.add_argument("--inject-css", metavar="FILE", help="Inject additional CSS file before render")
parser.add_argument("--scale", type=float, default=1.0, help="Print scale factor (default: 1.0)")
parser.add_argument("--timeout", type=int, default=30, help="Chrome render timeout in seconds (default: 30)")
parser.add_argument("--chrome", help="Chrome binary path (auto-detected if omitted)")
parser.add_argument("--version", action="version", version=f"html2pdf {__version__}")
args = parser.parse_args()
if args.stdout:
args.base64 = True
chrome = args.chrome or find_chrome()
with tempfile.TemporaryDirectory(prefix="html2pdf_") as work_dir:
input_path = resolve_input(args.input, work_dir)
needs_rewrite = False
if args.fetch_images or args.inject_css or args.margins:
with open(input_path) as f:
html = f.read()
if args.fetch_images:
html = fetch_remote_images(html, work_dir)
needs_rewrite = True
if args.inject_css:
if not os.path.isfile(args.inject_css):
print(f"Error: CSS file not found: {args.inject_css}", file=sys.stderr)
sys.exit(1)
html = inject_css(html, args.inject_css)
needs_rewrite = True
if args.margins:
margin_css = f"@page {{ margin: {args.margins}; }}"
html = inject_css_string(html, margin_css)
needs_rewrite = True
if needs_rewrite:
rewritten = os.path.join(work_dir, "rewritten.html")
with open(rewritten, "w") as f:
f.write(html)
input_path = rewritten
if args.output:
output_path = os.path.abspath(args.output)
elif args.base64:
output_path = os.path.join(work_dir, "output.pdf")
else:
base = os.path.splitext(os.path.basename(args.input))[0]
output_path = os.path.abspath(f"{base}.pdf")
cmd = build_chrome_args(
chrome=chrome,
input_path=input_path,
output_path=output_path,
paper=args.paper,
landscape=args.landscape,
no_header=args.no_header,
scale=args.scale,
)
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=args.timeout + 10,
)
if result.returncode != 0:
print(f"Chrome exited with code {result.returncode}", file=sys.stderr)
if result.stderr:
for line in result.stderr.strip().split("\n"):
if "ERROR" in line or "error" in line.lower():
print(f" {line}", file=sys.stderr)
sys.exit(1)
if not os.path.isfile(output_path):
print("Error: Chrome did not produce output PDF.", file=sys.stderr)
sys.exit(1)
file_size = os.path.getsize(output_path)
if args.base64:
with open(output_path, "rb") as f:
encoded = base64.b64encode(f.read()).decode("ascii")
print(encoded)
print(
f"PDF generated: {file_size} bytes "
f"({file_size / 1024:.0f} KB, "
f"~{len(encoded) // 4000} model tokens for base64)",
file=sys.stderr,
)
else:
print(
f"PDF generated: {output_path} "
f"({file_size} bytes, {file_size / 1024:.0f} KB)",
file=sys.stderr,
)
def inject_css_string(html: str, css: str) -> str:
"""Inject a raw CSS string as a <style> block."""
style_tag = f"\n<style>\n{css}\n</style>\n"
if "</head>" in html:
return html.replace("</head>", style_tag + "</head>", 1)
if "<body" in html:
idx = html.index("<body")
close = html.index(">", idx) + 1
return html[:close] + style_tag + html[close:]
return style_tag + html
if __name__ == "__main__":
main()