|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Render the single-page book edition (site/book.html) into a downloadable PDF. |
| 3 | +
|
| 4 | +This is the second half of the book build: `site/generate.py` emits |
| 5 | +`site/book.html` (all chapters on one printable page); this script loads that page |
| 6 | +in headless Chromium (Playwright) and prints it to `site/gh-aw-book.pdf` with page |
| 7 | +numbers, a running footer, and a PDF outline. Chromium runs highlight.js, so code |
| 8 | +blocks keep their syntax colors in the PDF. |
| 9 | +
|
| 10 | +The PDF is a binary BUILD ARTIFACT: it is gitignored and produced fresh here (in CI |
| 11 | +on every book change, and locally on demand) rather than committed to `main`. |
| 12 | +
|
| 13 | +Usage: |
| 14 | + python site/generate.py # 1. (re)build site/book.html |
| 15 | + python scripts/build_pdf.py # 2. render the PDF |
| 16 | +
|
| 17 | +Requirements (see scripts/requirements-pdf.txt): |
| 18 | + python -m pip install -r scripts/requirements-pdf.txt |
| 19 | + python -m playwright install chromium # add --with-deps on Linux/CI |
| 20 | +""" |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import functools |
| 24 | +import http.server |
| 25 | +import socketserver |
| 26 | +import sys |
| 27 | +import threading |
| 28 | +from pathlib import Path |
| 29 | + |
| 30 | +ROOT = Path(__file__).resolve().parents[1] |
| 31 | +SITE = ROOT / "site" |
| 32 | +BOOK_PAGE = "book.html" |
| 33 | +PDF_PATH = SITE / "gh-aw-book.pdf" |
| 34 | + |
| 35 | +# Running footer: book title on the left, "Page N / M" on the right. The |
| 36 | +# pageNumber / totalPages spans are filled in by Chromium. |
| 37 | +FOOTER_TEMPLATE = ( |
| 38 | + '<div style="width:100%;font-family:\'Hanken Grotesk\',Arial,sans-serif;' |
| 39 | + 'font-size:8px;color:#8a93a6;padding:0 14mm;display:flex;' |
| 40 | + 'justify-content:space-between;align-items:center;">' |
| 41 | + '<span>GitHub Agentic Workflows \u2014 An Interactive Book</span>' |
| 42 | + '<span>Page <span class="pageNumber"></span> / <span class="totalPages"></span></span>' |
| 43 | + "</div>" |
| 44 | +) |
| 45 | +HEADER_TEMPLATE = '<div style="height:0"></div>' |
| 46 | + |
| 47 | +PDF_MARGIN = {"top": "16mm", "bottom": "18mm", "left": "15mm", "right": "15mm"} |
| 48 | + |
| 49 | + |
| 50 | +class _QuietHandler(http.server.SimpleHTTPRequestHandler): |
| 51 | + def log_message(self, *args): # noqa: D401 - silence per-request logging |
| 52 | + pass |
| 53 | + |
| 54 | + |
| 55 | +def _serve(directory: Path) -> tuple[socketserver.TCPServer, int]: |
| 56 | + """Serve `directory` on an ephemeral localhost port in a background thread.""" |
| 57 | + handler = functools.partial(_QuietHandler, directory=str(directory)) |
| 58 | + httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) |
| 59 | + port = httpd.server_address[1] |
| 60 | + threading.Thread(target=httpd.serve_forever, daemon=True).start() |
| 61 | + return httpd, port |
| 62 | + |
| 63 | + |
| 64 | +def build_pdf() -> Path: |
| 65 | + try: |
| 66 | + from playwright.sync_api import sync_playwright |
| 67 | + except ImportError as exc: # pragma: no cover - dependency guard |
| 68 | + raise SystemExit( |
| 69 | + "Playwright is not installed. Run:\n" |
| 70 | + " python -m pip install -r scripts/requirements-pdf.txt\n" |
| 71 | + " python -m playwright install chromium" |
| 72 | + ) from exc |
| 73 | + |
| 74 | + book = SITE / BOOK_PAGE |
| 75 | + if not book.exists(): |
| 76 | + raise SystemExit( |
| 77 | + f"{book} not found. Run `python site/generate.py` first to build it." |
| 78 | + ) |
| 79 | + |
| 80 | + httpd, port = _serve(SITE) |
| 81 | + url = f"http://127.0.0.1:{port}/{BOOK_PAGE}" |
| 82 | + try: |
| 83 | + with sync_playwright() as playwright: |
| 84 | + browser = playwright.chromium.launch() |
| 85 | + page = browser.new_page() |
| 86 | + page.goto(url, wait_until="networkidle", timeout=90_000) |
| 87 | + # Wait for the page's load handler to run highlight.js and flag readiness. |
| 88 | + try: |
| 89 | + page.wait_for_function( |
| 90 | + "document.documentElement.getAttribute('data-book-ready') === '1'", |
| 91 | + timeout=20_000, |
| 92 | + ) |
| 93 | + except Exception: # highlight.js CDN slow/unavailable — print anyway |
| 94 | + pass |
| 95 | + # Ensure web fonts are laid out before measuring page breaks. |
| 96 | + page.evaluate("() => (document.fonts ? document.fonts.ready : true)") |
| 97 | + page.wait_for_timeout(400) |
| 98 | + |
| 99 | + pdf_kwargs = dict( |
| 100 | + path=str(PDF_PATH), |
| 101 | + format="A4", |
| 102 | + print_background=True, |
| 103 | + display_header_footer=True, |
| 104 | + header_template=HEADER_TEMPLATE, |
| 105 | + footer_template=FOOTER_TEMPLATE, |
| 106 | + margin=PDF_MARGIN, |
| 107 | + ) |
| 108 | + # `outline`/`tagged` add PDF bookmarks + accessibility on newer |
| 109 | + # Playwright; fall back cleanly if the installed version lacks them. |
| 110 | + try: |
| 111 | + page.pdf(outline=True, tagged=True, **pdf_kwargs) |
| 112 | + except TypeError: |
| 113 | + page.pdf(**pdf_kwargs) |
| 114 | + browser.close() |
| 115 | + finally: |
| 116 | + httpd.shutdown() |
| 117 | + |
| 118 | + return PDF_PATH |
| 119 | + |
| 120 | + |
| 121 | +def main() -> None: |
| 122 | + pdf = build_pdf() |
| 123 | + size_kb = pdf.stat().st_size / 1024 |
| 124 | + print(f"Wrote {pdf} ({size_kb:,.0f} KB)") |
| 125 | + if size_kb < 20: |
| 126 | + print("Warning: PDF is unexpectedly small — check the render.", file=sys.stderr) |
| 127 | + sys.exit(1) |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + main() |
0 commit comments