#!/usr/bin/env python3 # -*- coding: utf-8 -*- """md → 渲染产物三件套:HTML + 全长度 PNG + A4 PDF。 用法: python3 tools/render.py 模板.md -o build/模板 # 产出 build/模板.html、build/模板.png(完整长图,非第一页)、build/模板.pdf(A4 分页) PNG 先量出文档真实高度再整页截取;超过单次截取上限时自动分带截取并用 Pillow 拼接。 PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截断。 """ from __future__ import annotations import argparse import re import subprocess import tempfile from pathlib import Path from urllib.parse import unquote CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素) PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接 # KaTeX 公式渲染(CDN 引入一次并缓存到本地,此后渲染不依赖网络) KATEX_CSS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" KATEX_JS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js" KATEX_AUTO = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" CSS = """ :root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; } * { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; } body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg); font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif; -webkit-font-smoothing:antialiased; } h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); } h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); } h3 { font-size:18px; margin:28px 0 12px; } h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); } p, li { margin:10px 0; } blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head); color:#33404d; border-radius:0 6px 6px 0; } blockquote p { margin:6px 0; } code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px; font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; } pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; } pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; } table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; } th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; } th { background:var(--head); font-weight:600; } tr:nth-child(even) td { background:#fbfcfd; } img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; } em { color:var(--muted); font-size:14px; } hr { border:0; border-top:1px solid var(--line); margin:32px 0; } a { color:#0969da; } .katex-display { margin:18px 0; } @page { size: A4; margin: 14mm 12mm; } @media print { body { max-width:none; padding:0; font-size:12pt; } h2, h3 { page-break-after:avoid; break-after:avoid; } tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; } thead { display:table-header-group; } } """ def chrome(args: list[str], timeout: int = 300) -> subprocess.CompletedProcess: return subprocess.run( [CHROME, "--headless", "--disable-gpu", "--hide-scrollbars", "--run-all-compositor-stages-before-draw", *args], capture_output=True, text=True, timeout=timeout, ) def doc_title(md: str, fallback: str) -> str: """标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。""" m = re.search(r"(?m)^#\s+(.+?)\s*$", md) if not m: return fallback return re.sub(r"", "", m.group(1), flags=re.S).strip() or fallback def md_to_html(md: str) -> str: with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f: f.write(md) tmp = f.name try: res = subprocess.run(["npx", "--yes", "marked@15", "-i", tmp], capture_output=True, text=True, check=True) finally: Path(tmp).unlink(missing_ok=True) return res.stdout def build_html(src: Path) -> tuple[str, str]: """渲染出完整 HTML 文本,返回 (html, 标题)。""" text = src.read_text(encoding="utf-8") body = md_to_html(text) base = src.resolve().parent # 相对图片路径改为绝对 file:// URI;marked 输出已做一次百分号编码,先 unquote 再转 def absolutize(m: re.Match) -> str: s = m.group(1) if s.startswith(("http://", "https://", "file://", "data:")): return m.group(0) return m.group(0).replace(s, (base / unquote(s)).as_uri(), 1) body = re.sub(r'").replace("&", "&") def _display(m: re.Match) -> str: # KaTeX 把裸 % 当注释符,须转义 return "\\(\\displaystyle " + m.group(1).replace("%", "\\%") + " \\)" def _inline(m: re.Match) -> str: return "\\(" + m.group(1).replace("%", "\\%") + " \\)" body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S) body = re.sub(r"(?\n\n\n\n' f"{title}\n" f'\n' f"\n\n" ) if has_math: init = ( "" ) body += "\n" + init scripts = "\n".join(f'' for _, u in js_local) body = scripts + "\n" + body html = head + f"\n{body}\n\n\n" return html, title def local_assets(name: str, url: str) -> tuple[str, str]: """CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。""" d = Path(__file__).resolve().parent.parent / ".cache" / "assets" d.mkdir(parents=True, exist_ok=True) f = d / name if not f.exists() or f.stat().st_size == 0: r = subprocess.run(["curl", "-sSL", "-o", str(f), url], capture_output=True) if not f.exists() or f.stat().st_size == 0: if f.exists(): f.unlink() return "", url # 回退 CDN return f.as_uri(), f.as_uri() def measure_height(html_path: Path) -> int: """注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。""" probe = html_path.with_name("_measure.html") script = ("") probe.write_text(html_path.read_text(encoding="utf-8").replace("", script + ""), encoding="utf-8") try: res = chrome(["--virtual-time-budget=30000", "--dump-dom", probe.as_uri()]) finally: probe.unlink(missing_ok=True) hits = re.findall(r"PAGEH:(\d+)", res.stdout) if not hits: raise RuntimeError("量取页面高度失败:" + res.stderr[-300:]) return int(hits[-1]) def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None: h = measure_height(html_path) uri = html_path.as_uri() if h <= PNG_BAND: chrome([f"--screenshot={png_path}", f"--window-size={width},{h}", "--virtual-time-budget=30000", uri]) else: bands: list[Path] = [] offset, i = 0, 0 while offset < h: bh = min(PNG_BAND, h - offset) band_html = html_path.with_name(f"_band{i}.html") band_html.write_text( html_path.read_text(encoding="utf-8").replace( "", f"body{{margin-top:-{offset}px}}", 1), encoding="utf-8") out = html_path.parent / f"_band{i}.png" chrome([f"--screenshot={out}", f"--window-size={width},{bh}", "--virtual-time-budget=30000", band_html.as_uri()]) bands.append(out) band_html.unlink(missing_ok=True) offset += bh i += 1 from PIL import Image imgs = [Image.open(b) for b in bands] total = sum(im.height for im in imgs) canvas = Image.new("RGB", (imgs[0].width, total), "white") y = 0 for im in imgs: canvas.paste(im, (0, y)) y += im.height canvas.save(png_path) for b, im in zip(bands, imgs): b.unlink(missing_ok=True) im.close() def render_pdf(html_path: Path, pdf_path: Path) -> None: chrome([f"--print-to-pdf={pdf_path}", "--no-pdf-header-footer", "--virtual-time-budget=30000", html_path.as_uri()]) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板") ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度") a = ap.parse_args() src = Path(a.src) stem = Path(a.out).resolve() stem.parent.mkdir(parents=True, exist_ok=True) html_path = stem.with_suffix(".html") html, _ = build_html(src) html_path.write_text(html, encoding="utf-8") png_path = stem.with_suffix(".png") render_png(html_path, png_path, a.width) pdf_path = stem.with_suffix(".pdf") render_pdf(html_path, pdf_path) for p in (html_path, png_path, pdf_path): size = p.stat().st_size extra = "" if p.suffix == ".png": try: from PIL import Image with Image.open(p) as im: extra = f",{im.width}×{im.height}px" except ImportError: pass if p.suffix == ".pdf": try: import subprocess as sp r = sp.run(["mdls", "-name", "kMDItemNumberOfPages", "-raw", str(p)], capture_output=True, text=True) if r.stdout.strip().isdigit(): extra = f",{r.stdout.strip()} 页" except Exception: pass print(f" {p} ({size / 1024:.0f} KB{extra})") return 0 if __name__ == "__main__": raise SystemExit(main())