Coverage for muutils / web / html_to_pdf.py: 0%
16 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-18 02:51 -0700
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-18 02:51 -0700
1from pathlib import Path
2import subprocess
4from weasyprint import HTML as WeasyHTML # type: ignore[import-untyped]
7def html_to_pdf(src: Path, dst: Path) -> None:
8 "write HTML file to PDF using WeasyPrint."
9 WeasyHTML(filename=src.as_posix()).write_pdf(dst.as_posix())
12def crop(pdf_in: Path, pdf_out: Path, margin_pt: int = 2) -> None:
13 """Run pdfcrop with a tiny safety margin."""
14 subprocess.run(
15 ["pdfcrop", "--margins", str(margin_pt), pdf_in.as_posix(), pdf_out.as_posix()],
16 check=True,
17 )
20def save_html_to_pdf(
21 html: str,
22 pdf_out: Path,
23 pdfcrop: bool = True,
24 margin_pt: int = 2,
25) -> None:
26 """Save HTML string to PDF file."""
27 if isinstance(pdf_out, str):
28 pdf_out = Path(pdf_out)
29 temp_html: Path = pdf_out.with_suffix(".html")
30 temp_html.write_text(html, encoding="utf-8")
32 html_to_pdf(temp_html, pdf_out)
34 if pdfcrop:
35 crop(pdf_out, pdf_out, margin_pt)
37 # Clean up temporary HTML file
38 temp_html.unlink(missing_ok=True)