#!/usr/bin/env python3 """Convert Quarto HTML outputs to PDF with WeasyPrint (typst-templates layout).""" from __future__ import annotations import os import sys from pathlib import Path def venv_python() -> Path | None: here = Path(__file__).resolve() for root in (here.parents[1], here.parents[2]): py = root / ".venv-pdf" / "bin" / "python" if py.is_file() and os.access(py, os.X_OK): return py return None def ensure_weasyprint(): try: import weasyprint # noqa: F401 return except ImportError: pass py = venv_python() if py is None: print( "html-to-pdf: WeasyPrint not found. Install with:\n" " uv venv .venv-pdf && uv pip install --python .venv-pdf/bin/python weasyprint", file=sys.stderr, ) raise SystemExit(1) os.execv(str(py), [str(py), str(Path(__file__).resolve()), *sys.argv[1:]]) def collect_html_files(project_dir: Path, output_dir: Path) -> list[Path]: # Quarto passes rendered output paths as argv after the script name. from_args = [] for arg in sys.argv[1:]: p = Path(arg) if not p.is_absolute(): p = (project_dir / p).resolve() if p.suffix.lower() == ".html" and p.is_file() and "files" not in p.parts: from_args.append(p) if from_args: return sorted(set(from_args)) html_files = sorted(output_dir.rglob("*.html")) return [p for p in html_files if "files" not in p.parts] def main() -> int: ensure_weasyprint() from weasyprint import HTML project_dir = Path(os.environ.get("QUARTO_PROJECT_DIR", Path.cwd())) output_dir = Path(os.environ.get("QUARTO_PROJECT_OUTPUT_DIR", project_dir / "_output")) html_files = collect_html_files(project_dir, output_dir) if not html_files: print("html-to-pdf: no HTML files found to convert", file=sys.stderr) return 0 for html_path in html_files: pdf_path = html_path.with_suffix(".pdf") print(f"html-to-pdf: {html_path} -> {pdf_path}") HTML(filename=str(html_path), base_url=str(html_path.parent)).write_pdf(str(pdf_path)) return 0 if __name__ == "__main__": raise SystemExit(main())