gunk-dev/the-valley

build_pdf.py

sourcee534e27c2fbemain's published tip history
2.8 KiB
1#!/usr/bin/env python3
2"""Render the reader HTML as a fixed-page PDF for the Kindle Scribe."""
3
4from __future__ import annotations
5
6import argparse
7import base64
8from pathlib import Path
9import re
10import subprocess
11import tempfile
12
13
14def main() -> None:
15 parser = argparse.ArgumentParser(description=__doc__)
16 parser.add_argument("--html", type=Path, required=True, help="Reader HTML from build.py")
17 parser.add_argument("--weasyprint", default="weasyprint", help="WeasyPrint executable")
18 parser.add_argument("--output", type=Path, help="PDF destination")
19 args = parser.parse_args()
20
21 edition = Path(__file__).resolve().parent
22 output = args.output or edition.parent / "the-valley-research-scribe.pdf"
23 source = args.html.resolve().read_text(encoding="utf-8")
24 if 'id="report-11-' not in source or 'id="TOC"' not in source:
25 parser.error("Expected the complete reader HTML with its table of contents")
26
27 # The PDF has its own page layout. Reflowable EPUB styles do not apply here.
28 source = re.sub(r"<style\b[^>]*>.*?</style>", "", source, flags=re.DOTALL)
29 css = (edition / "pdf.css").read_text(encoding="utf-8")
30 source = source.replace("</head>", f"<style>\n{css}\n</style>\n</head>", 1)
31 cover = base64.b64encode((edition / "cover.svg").read_bytes()).decode("ascii")
32 source = re.sub(
33 r'<header id="title-block-header">.*?</header>',
34 '<div class="pdf-cover"><img alt="the-valley: Foundations and Research '
35 f'Opportunities" src="data:image/svg+xml;base64,{cover}" /></div>',
36 source,
37 count=1,
38 flags=re.DOTALL,
39 )
40 source = source.replace(
41 "with adjustable text and a linked table of contents",
42 "with pages sized for its screen, embedded fonts, and a linked table of contents",
43 1,
44 )
45 source = source.replace(
46 '<section id="footnotes" class="footnotes footnotes-end-of-document" '
47 'role="doc-endnotes">\n<hr />',
48 '<section id="footnotes" class="footnotes footnotes-end-of-document" '
49 'role="doc-endnotes">\n<h1 id="repository-source-notes">Repository source notes</h1>',
50 1,
51 )
52 nav_end = source.index("</nav>")
53 nav_close = source.rfind("</ul>", 0, nav_end)
54 source = (
55 source[:nav_close]
56 + '<li><a href="#repository-source-notes">Repository source notes</a></li>\n'
57 + source[nav_close:]
58 )
59
60 output = output.resolve()
61 output.parent.mkdir(parents=True, exist_ok=True)
62 with tempfile.TemporaryDirectory(prefix="the-valley-pdf-") as temporary:
63 html = Path(temporary) / "report.html"
64 html.write_text(source, encoding="utf-8")
65 subprocess.run(
66 [args.weasyprint, "--base-url", str(args.html.resolve().parent), str(html), str(output)],
67 check=True,
68 )
69 print(f"Wrote {output}")
70
71
72if __name__ == "__main__":
73 main()