cover_render.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. # -*- coding: utf-8 -*-
  2. """
  3. cover_render.py — ReportLab cover generator for the PDF skill.
  4. Renders a single-page A4 cover PDF (to be merged as page 1 of the body PDF via
  5. pypdf). Pure ReportLab — no HTML/Playwright/Chromium required.
  6. Nine templates (renumbered 01-09):
  7. 01 HUD Data Terminal (light) — report/tech
  8. 02 Corporate Editorial (light) — annual/financial
  9. 03 Monolith (light) — white paper/proposal/gov
  10. 04 Museum Minimal (light) — portfolio/gallery/luxury
  11. 05 Solid Sidebar (light) — institutional/bidding/legal
  12. 06 Academic Vertical (dark) — arXiv/preprint/tech report
  13. 07 Academic Symmetric (dark) — IEEE/ACM/thesis
  14. 08 Academic Journal (dark) — CJK journal/thesis w/ keywords
  15. 09 Institutional (white + black frame) — thesis proposal/gov
  16. Fonts: auto-detected from the host machine, chosen by cover style
  17. (sans for 01-05, serif for 06-09; kai optional). CFF/PostScript-outline fonts
  18. (PingFang, Hiragino, Noto CJK OTC, Source Han) are skipped — ReportLab's TTFont
  19. cannot embed them. Missing heavy weights are simulated with stroke faux-bold.
  20. CLI:
  21. "$(command -v zcode-python || command -v python3)" cover_render.py <template 01-09> --out cover.pdf [--content content.json]
  22. "$(command -v zcode-python || command -v python3)" cover_render.py --demo # renders all 9 with sample content
  23. """
  24. import os, sys, json, argparse, subprocess
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.colors import HexColor, Color
  27. from reportlab.pdfbase import pdfmetrics
  28. from reportlab.pdfbase.ttfonts import TTFont
  29. from reportlab.pdfbase.pdfmetrics import stringWidth
  30. from reportlab.platypus import Paragraph
  31. from reportlab.lib.styles import ParagraphStyle
  32. from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER
  33. # ── Page geometry (A4 pt); HTML design canvas was 794x1123 px ──
  34. W, H = 595.28, 841.89
  35. PXW, PXH = 794.0, 1123.0
  36. def X(px): return px * W / PXW
  37. def LW(px): return px * W / PXW
  38. def VH(px): return px * H / PXH
  39. def YT(px): return H - px * H / PXH
  40. def FSpx(px): return px * W / PXW
  41. # ── Default palette (override via palette dict) ──
  42. DEFAULT_PALETTE = {
  43. "primary": "#1e3a5f", "secondary": "#2d5f8a", "text": "#1a1a2e",
  44. "muted": "#6b7280", "bg": "#ffffff",
  45. # academic dark
  46. "ac_bg": "#162032", "ac_accent": "#4A90C4", "ac_gold": "#8B7E5A",
  47. "ac_text": "#FFFFFF", "ac_muted": "#90A8C0", "ac_foot": "#607080",
  48. }
  49. # ═══════════════════════════════════════════════════════════════════
  50. # Font detection — pick embeddable (TrueType-outline) CJK fonts by role
  51. # ═══════════════════════════════════════════════════════════════════
  52. _FONT_CANDIDATES = {
  53. # role: [(regname, [path candidates], subfontIndex)]
  54. "sans": [
  55. ("SimHei", ["/usr/share/fonts/truetype/chinese/SimHei.ttf",
  56. "~/Library/Fonts/SimHei.ttf", "C:/Windows/Fonts/simhei.ttf"], None),
  57. ("MSYaHei", ["/usr/share/fonts/truetype/chinese/msyh.ttf",
  58. "/usr/share/fonts/truetype/chinese/msyh.ttc",
  59. "C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/msyh.ttf"], 0),
  60. ("HeitiSC", ["/System/Library/Fonts/STHeiti Medium.ttc"], 1),
  61. ("WenQuanYiZenHei", ["/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"], 0),
  62. ("ArialUnicode", ["/Library/Fonts/Arial Unicode.ttf",
  63. "/System/Library/Fonts/Supplemental/Arial Unicode.ttf"], None),
  64. ],
  65. "serif": [
  66. ("SongtiSC", ["/System/Library/Fonts/Supplemental/Songti.ttc"], 0), # Black
  67. ("SimSun", ["/usr/share/fonts/truetype/chinese/simsun.ttc",
  68. "~/Library/Fonts/SimSun.ttf", "C:/Windows/Fonts/simsun.ttc"], 0),
  69. ("STSong", ["/System/Library/Fonts/Supplemental/Songti.ttc"], 4),
  70. ("ARPLUMing", ["/usr/share/fonts/truetype/arphic/uming.ttc"], 0),
  71. ],
  72. "kai": [
  73. ("KaiTi", ["/usr/share/fonts/truetype/chinese/simkai.ttf",
  74. "~/Library/Fonts/SimKai.ttf", "C:/Windows/Fonts/simkai.ttf"], None),
  75. ("KaitiSC", ["/System/Library/Fonts/Supplemental/Kaiti.ttc"], 2),
  76. ],
  77. "latin": [
  78. ("TNR", ["/usr/share/fonts/truetype/english/Times-New-Roman.ttf",
  79. "~/Library/Fonts/Times-New-Roman.ttf",
  80. "/System/Library/Fonts/Supplemental/Times New Roman.ttf",
  81. "C:/Windows/Fonts/times.ttf"], None),
  82. ],
  83. }
  84. def _try_register(name, path, idx):
  85. path = os.path.expanduser(path)
  86. if not os.path.exists(path):
  87. return False
  88. try:
  89. pdfmetrics.registerFont(TTFont(name, path) if idx is None
  90. else TTFont(name, path, subfontIndex=idx))
  91. return True # succeeds only for embeddable TrueType-outline fonts
  92. except Exception:
  93. return False # CFF/PostScript-outline (PingFang/Hiragino/Noto CJK) land here
  94. def _fc_fallback(role):
  95. """Last resort: query fontconfig for a zh font and try to embed it."""
  96. try:
  97. pat = ":lang=zh:spacing=100" if role == "sans" else ":lang=zh"
  98. out = subprocess.run(["fc-list", pat, "file"], capture_output=True,
  99. text=True, timeout=5).stdout
  100. except Exception:
  101. return None
  102. for line in out.splitlines():
  103. p = line.split(":")[0].strip()
  104. if p.lower().endswith((".ttf", ".ttc")):
  105. nm = "FC_%s_%d" % (role, abs(hash(p)) % 10000)
  106. if _try_register(nm, p, 0):
  107. return nm
  108. return None
  109. def detect_fonts(overrides=None):
  110. """Return {sans, serif, kai, latin} of registered, embeddable font names.
  111. `overrides` may map any role -> (regname, path, idx) to force a choice."""
  112. picks = {}
  113. overrides = overrides or {}
  114. for role, cands in _FONT_CANDIDATES.items():
  115. chosen = None
  116. if role in overrides:
  117. nm, p, i = overrides[role]
  118. if _try_register(nm, p, i):
  119. chosen = nm
  120. if not chosen:
  121. for nm, paths, idx in cands:
  122. for p in paths:
  123. if _try_register("F_%s_%s" % (role, nm), p, idx):
  124. chosen = "F_%s_%s" % (role, nm); break
  125. if chosen: break
  126. if not chosen and role in ("sans", "serif"):
  127. chosen = _fc_fallback(role)
  128. picks[role] = chosen
  129. # graceful fallbacks
  130. if not picks.get("sans"): picks["sans"] = picks.get("serif")
  131. if not picks.get("serif"): picks["serif"] = picks.get("sans")
  132. if not picks.get("latin"): picks["latin"] = picks.get("sans")
  133. if not picks.get("kai"): picks["kai"] = picks.get("serif") or picks.get("sans")
  134. if not picks.get("sans"):
  135. raise RuntimeError("No embeddable CJK font found on this machine. "
  136. "Install one of: SimHei, Microsoft YaHei, Songti/SimSun, "
  137. "Heiti SC, WenQuanYi Zen Hei.")
  138. return picks
  139. # ═══════════════════════════════════════════════════════════════════
  140. # primitives
  141. # ═══════════════════════════════════════════════════════════════════
  142. def _c(hexv): return HexColor(hexv)
  143. def fill_rect(c, x_px, top_px, w_px, h_px, color, alpha=1.0):
  144. c.saveState(); c.setFillColor(color); c.setFillAlpha(alpha)
  145. c.rect(X(x_px), YT(top_px) - VH(h_px), LW(w_px), VH(h_px), stroke=0, fill=1)
  146. c.restoreState()
  147. def hline(c, x_px, top_px, w_px, thick_px, color, alpha=1.0):
  148. c.saveState(); c.setStrokeColor(color); c.setStrokeAlpha(alpha); c.setLineWidth(LW(thick_px))
  149. c.line(X(x_px), YT(top_px), X(x_px + w_px), YT(top_px)); c.restoreState()
  150. def vline(c, x_px, top_px, h_px, thick_px, color, alpha=1.0):
  151. c.saveState(); c.setStrokeColor(color); c.setStrokeAlpha(alpha); c.setLineWidth(LW(thick_px))
  152. c.line(X(x_px), YT(top_px), X(x_px), YT(top_px + h_px)); c.restoreState()
  153. def _style(font, size, color, leading=None, align=TA_LEFT):
  154. return ParagraphStyle('s', fontName=font, fontSize=size, leading=leading or size * 1.2,
  155. textColor=color, alignment=align, wordWrap='CJK')
  156. def para(c, text, x_px, top_px, w_px, font, size, color, line_h=1.2, align=TA_LEFT, fauxbold=0.0):
  157. st = _style(font, size, color, leading=size * line_h, align=align)
  158. w = LW(w_px); x = X(x_px)
  159. p = Paragraph(text, st); _, h = p.wrap(w, H); y = YT(top_px) - h
  160. if fauxbold > 0:
  161. for dx, dy in [(0, 0), (fauxbold, 0), (0, fauxbold), (fauxbold, fauxbold), (fauxbold / 2, fauxbold / 2)]:
  162. pp = Paragraph(text, st); pp.wrap(w, H); pp.drawOn(c, x + dx, y - dy)
  163. else:
  164. p.drawOn(c, x, y)
  165. return h
  166. def line_text(c, text, x_px, top_px, font, size, color, ls_px=0.0, align=TA_LEFT,
  167. right_px=None, ascent=0.82, alpha=1.0):
  168. c.saveState(); c.setFillColor(color); c.setFillAlpha(alpha)
  169. ls = LW(ls_px); baseline = YT(top_px) - size * ascent
  170. if align == TA_RIGHT and right_px is not None:
  171. w = stringWidth(text, font, size) + ls * max(0, len(text) - 1); x = X(right_px) - w
  172. else:
  173. x = X(x_px)
  174. to = c.beginText(x, baseline); to.setFont(font, size)
  175. if ls: to.setCharSpace(ls)
  176. to.textOut(text); c.drawText(to); c.restoreState()
  177. def center_line(c, text, top_px, font, size, color, ls_px=0.0, fauxbold=0.0, line_h=1.3):
  178. ls = LW(ls_px); w = stringWidth(text, font, size) + ls * max(0, len(text) - 1)
  179. x = W / 2 - w / 2; baseline = YT(top_px) - size * 0.82
  180. c.saveState(); c.setFillColor(color)
  181. def draw(dx, dy):
  182. to = c.beginText(x + dx, baseline - dy); to.setFont(font, size)
  183. if ls: to.setCharSpace(ls)
  184. to.textOut(text); c.drawText(to)
  185. if fauxbold > 0:
  186. for dx, dy in [(0, 0), (fauxbold, 0), (0, fauxbold), (fauxbold, fauxbold), (fauxbold / 2, fauxbold / 2)]:
  187. draw(dx, dy)
  188. else:
  189. draw(0, 0)
  190. c.restoreState()
  191. return size * line_h
  192. # ═══════════════════════════════════════════════════════════════════
  193. # templates (F = detected font names, P = palette colors)
  194. # ═══════════════════════════════════════════════════════════════════
  195. def _t01_hud(c, ct, F, P):
  196. pri = _c(P["primary"]); txt = _c(P["text"]); mut = _c(P["muted"])
  197. c.saveState(); c.setStrokeColor(pri); c.setStrokeAlpha(0.05); c.setLineWidth(LW(0.5))
  198. x = 0
  199. while x <= PXW: c.line(X(x), 0, X(x), H); x += 50
  200. y = 0
  201. while y <= PXH: c.line(0, YT(y), W, YT(y)); y += 50
  202. c.restoreState()
  203. xc = 0.12 * PXW + 30
  204. vline(c, 0.12 * PXW, 0.10 * PXH, 0.80 * PXH, 6, pri)
  205. hline(c, xc, 0.72 * PXH - 12, 0.4 * PXW, 1, pri, alpha=0.4)
  206. line_text(c, ct["kicker"], xc, 0.15 * PXH, F["sans"], 16, mut, ls_px=3)
  207. para(c, ct["hero"], xc, 0.28 * PXH, 0.7 * PXW, F["sans"], 66, pri, line_h=1.15, fauxbold=1.4)
  208. para(c, ct["summary"], xc, 0.48 * PXH, 0.6 * PXW, F["sans"], 17, txt, line_h=1.6)
  209. para(c, ct["meta"], xc, 0.74 * PXH, 0.7 * PXW, F["sans"], 17, txt, line_h=1.7)
  210. def _t02_corporate(c, ct, F, P):
  211. pri = _c(P["primary"]); txt = _c(P["text"]); mut = _c(P["muted"])
  212. c.saveState(); c.setFillColor(pri); c.setFillAlpha(0.05)
  213. yr = ct.get("year", "")
  214. w = stringWidth(yr, F["sans"], 180)
  215. c.drawString((W - X(20)) - w, YT(0.15 * PXH) - 180 * 0.80, yr); c.restoreState()
  216. fill_rect(c, 0, 0, PXW, 15, pri)
  217. fill_rect(c, 0.88 * PXW, 0.75 * PXH, 4, 0.13 * PXH, pri)
  218. line_text(c, ct["kicker"], 0.12 * PXW, 0.15 * PXH, F["sans"], 16, mut, ls_px=3)
  219. para(c, ct["hero"], 0.12 * PXW, 0.15 * PXH + 44, 0.75 * PXW, F["sans"], 60, pri, line_h=1.15, fauxbold=1.3)
  220. para(c, ct["summary"], 0.12 * PXW, 0.50 * PXH, 0.5 * PXW, F["sans"], 17, txt, line_h=1.6)
  221. para(c, ct["meta"], 0.15 * PXW, 0.70 * PXH, (0.88 * PXW - 20) - 0.15 * PXW,
  222. F["sans"], 17, txt, line_h=1.8, align=TA_RIGHT)
  223. def _t03_monolith(c, ct, F, P):
  224. pri = _c(P["primary"]); txt = _c(P["text"]); mut = _c(P["muted"]); xc = 0.12 * PXW
  225. c.saveState(); c.setFillColor(pri); c.setFillAlpha(0.04)
  226. c.translate(X(0.85 * PXW), H / 2); c.rotate(-90)
  227. word = ct.get("word", "REPORT")
  228. tw = stringWidth(word, F["sans"], 170) + LW(8) * (len(word) - 1)
  229. to = c.beginText(-tw / 2, -170 * 0.35); to.setFont(F["sans"], 170); to.setCharSpace(LW(8))
  230. to.textOut(word); c.drawText(to); c.restoreState()
  231. fill_rect(c, xc, 0.15 * PXH, 50, 5, pri)
  232. vline(c, xc - 12, 0.70 * PXH, 0.12 * PXH, 2, pri, alpha=0.5)
  233. line_text(c, ct["kicker"], xc, 0.20 * PXH, F["sans"], 16, mut, ls_px=3)
  234. para(c, ct["hero"], xc, 0.28 * PXH, 0.7 * PXW, F["sans"], 60, pri, line_h=1.15, fauxbold=1.3)
  235. para(c, ct["summary"], xc, 0.45 * PXH, 0.55 * PXW, F["sans"], 17, txt, line_h=1.6)
  236. para(c, ct["meta"], xc, 0.70 * PXH, 0.7 * PXW, F["sans"], 18, txt, line_h=2.0)
  237. if ct.get("footer"):
  238. line_text(c, ct["footer"], 0, 0.90 * PXH, F["sans"], 16, mut, ls_px=1,
  239. align=TA_RIGHT, right_px=0.88 * PXW, alpha=0.85)
  240. def _t04_museum(c, ct, F, P):
  241. pri = _c(P["primary"]); txt = _c(P["text"]); mut = _c(P["muted"])
  242. M = 0.08 * PXW; arm = 30; lw = 2; op = 0.6
  243. def mk(hx, hy, vx, vy):
  244. fill_rect(c, hx, hy, arm, lw, pri, alpha=op); fill_rect(c, vx, vy, lw, arm, pri, alpha=op)
  245. mk(M, M, M, M); mk(PXW - M - arm, M, PXW - M - lw, M)
  246. mk(M, PXH - M - lw, M, PXH - M - arm); mk(PXW - M - arm, PXH - M - lw, PXW - M - lw, PXH - M - arm)
  247. styles = [
  248. (ct["kicker"], F["sans"], 16, mut, 1.3, 24, 0.84 * PXW, 0.0),
  249. (ct["hero"], F["sans"], 56, pri, 1.15, 20, 0.84 * PXW, 1.2),
  250. (ct["summary"], F["sans"], 17, txt, 1.6, 40, 0.6 * PXW, 0.0),
  251. (ct["meta"], F["sans"], 16, mut, 1.3, 0, 0.84 * PXW, 0.0),
  252. ]
  253. paras = []; total = 0
  254. for tx, fn, sz, col, lh, gap, wpx, fb in styles:
  255. st = _style(fn, sz, col, leading=sz * lh, align=TA_CENTER)
  256. p = Paragraph(tx, st); _, hh = p.wrap(LW(wpx), H)
  257. paras.append((tx, st, hh, gap, wpx, fb)); total += hh + VH(gap)
  258. y = H / 2 + total / 2
  259. for tx, st, hh, gap, wpx, fb in paras:
  260. x0 = (W - LW(wpx)) / 2
  261. if fb > 0:
  262. for dx, dy in [(0, 0), (fb, 0), (0, fb), (fb, fb), (fb / 2, fb / 2)]:
  263. pp = Paragraph(tx, st); pp.wrap(LW(wpx), H); pp.drawOn(c, x0 + dx, y - hh - dy)
  264. else:
  265. pp = Paragraph(tx, st); pp.wrap(LW(wpx), H); pp.drawOn(c, x0, y - hh)
  266. y -= hh + VH(gap)
  267. def _t05_sidebar(c, ct, F, P):
  268. pri = _c(P["primary"]); txt = _c(P["text"]); mut = _c(P["muted"]); white = _c("#ffffff")
  269. sb = 0.1 * PXW; le = sb + 40
  270. fill_rect(c, 0, 0, sb, PXH, pri)
  271. c.saveState(); pth = c.beginPath(); pth.rect(0, 0, X(sb), H); c.clipPath(pth, stroke=0)
  272. c.setFillColor(white); c.setFillAlpha(0.15)
  273. c.translate(X(sb / 2), H / 2); c.rotate(-90)
  274. wm = ct.get("year", ct.get("word", ""))
  275. tw = stringWidth(wm, F["sans"], FSpx(52)) + LW(14) * (len(wm) - 1)
  276. to = c.beginText(-tw / 2, -FSpx(52) * 0.35); to.setFont(F["sans"], FSpx(52)); to.setCharSpace(LW(14))
  277. to.textOut(wm); c.drawText(to); c.restoreState()
  278. hline(c, le, 0.90 * PXH, 0.90 * PXW - le, 1, pri, alpha=0.3)
  279. blk_w = 0.90 * PXW - le
  280. items = [
  281. (ct["kicker"], F["sans"], 16, mut, 1.3, 18, 0.0),
  282. (ct["hero"], F["sans"], 58, pri, 1.15, 24, 1.25),
  283. (ct["summary"], F["sans"], 17, txt, 1.6, 30, 0.0),
  284. (ct["meta"], F["sans"], 18, txt, 1.8, 0, 0.0),
  285. ]
  286. paras = []; total = 0
  287. for tx, fn, sz, col, lh, gap, fb in items:
  288. st = _style(fn, sz, col, leading=sz * lh, align=TA_LEFT)
  289. pp = Paragraph(tx, st); _, hh = pp.wrap(LW(blk_w), H)
  290. paras.append((tx, st, hh, gap, fb)); total += hh + VH(gap)
  291. y = H / 2 + total / 2
  292. for tx, st, hh, gap, fb in paras:
  293. if fb > 0:
  294. for dx, dy in [(0, 0), (fb, 0), (0, fb), (fb, fb), (fb / 2, fb / 2)]:
  295. pp = Paragraph(tx, st); pp.wrap(LW(blk_w), H); pp.drawOn(c, X(le) + dx, y - hh - dy)
  296. else:
  297. pp = Paragraph(tx, st); pp.wrap(LW(blk_w), H); pp.drawOn(c, X(le), y - hh)
  298. y -= hh + VH(gap)
  299. if ct.get("footer_left"):
  300. line_text(c, ct["footer_left"], le, 0.90 * PXH - 26, F["sans"], 16, mut, alpha=0.9)
  301. if ct.get("footer_right"):
  302. line_text(c, ct["footer_right"], 0, 0.90 * PXH - 26, F["sans"], 16, mut,
  303. ls_px=1, align=TA_RIGHT, right_px=0.90 * PXW, alpha=0.85)
  304. def _dark_bg(c, color): c.setFillColor(color); c.rect(0, 0, W, H, stroke=0, fill=1)
  305. def _t06_academic_vertical(c, ct, F, P):
  306. bg = _c(P["ac_bg"]); gold = _c(P["ac_gold"]); tx = _c(P["ac_text"]); mut = _c(P["ac_muted"]); foot = _c(P["ac_foot"])
  307. _dark_bg(c, bg)
  308. vline(c, 57, 76, PXH - 152, 2.5, gold)
  309. hline(c, 83, PXH - 132, PXW - 83 - 76, 0.5, gold)
  310. line_text(c, ct.get("label", ""), 83, 132, F["sans"], 9, gold, ls_px=3)
  311. para(c, ct["title"], 83, 228, 600, F["serif"], 30, tx, line_h=1.3)
  312. if ct.get("subtitle"): para(c, ct["subtitle"], 83, 560, 520, F["sans"], 12, mut, line_h=1.5)
  313. para(c, ct.get("authors", ""), 83, 700, 400, F["sans"], 12, tx, line_h=1.4)
  314. if ct.get("institution"): para(c, ct["institution"], 83, 740, 400, F["sans"], 10, mut, line_h=1.4)
  315. if ct.get("footer_left"): line_text(c, ct["footer_left"], 83, PXH - 76 - 9, F["sans"], 9, foot)
  316. if ct.get("footer_right"): line_text(c, ct["footer_right"], 0, PXH - 76 - 9, F["sans"], 9, foot,
  317. align=TA_RIGHT, right_px=PXW - 76)
  318. def _centered_dark(c, ct, F, P, divider_px, keywords):
  319. bg = _c(P["ac_bg"]); acc = _c(P["ac_accent"]); tx = _c(P["ac_text"]); mut = _c(P["ac_muted"])
  320. _dark_bg(c, bg)
  321. hline(c, 114, 114, PXW - 228, 2, acc); hline(c, 114, PXH - 114, PXW - 228, 2, acc)
  322. inner = PXW - 228
  323. blocks = [(ct.get("label", ""), F["sans"], 9, acc, 1.2, 40),
  324. (ct["title"], F["serif"], 30 if keywords else 28, tx, 1.3, 20 if keywords else 24),
  325. (ct.get("subtitle", ""), F["sans"], 13, mut, 1.5, 40)]
  326. paras = []; total = 0
  327. for tx0, fn, sz, col, lh, gap in blocks:
  328. pp = Paragraph(tx0, _style(fn, sz, col, leading=sz * lh, align=TA_CENTER))
  329. _, hh = pp.wrap(LW(inner), H); paras.append((pp, hh, gap)); total += hh + VH(gap)
  330. if keywords:
  331. tail = ct.get("keywords_lines", []); tail_h = len(tail) * 11 * 1.8
  332. else:
  333. tail_h = 12 * 1.2 + VH(12) + 10 * 1.2
  334. total += VH(0.5) + VH(40) + tail_h
  335. y = H / 2 + total / 2
  336. for pp, hh, gap in paras:
  337. pp.drawOn(c, (W - LW(inner)) / 2, y - hh); y -= hh + VH(gap)
  338. c.saveState(); c.setStrokeColor(acc); c.setLineWidth(LW(0.5))
  339. c.line(W / 2 - LW(divider_px) / 2, y, W / 2 + LW(divider_px) / 2, y); c.restoreState()
  340. y -= VH(40)
  341. if keywords:
  342. for ln in ct.get("keywords_lines", []):
  343. pp = Paragraph(ln, _style(F["sans"], 11, mut, leading=11 * 1.8, align=TA_CENTER))
  344. _, hh = pp.wrap(LW(inner), H); pp.drawOn(c, (W - LW(inner)) / 2, y - hh); y -= hh
  345. else:
  346. pp = Paragraph(ct.get("authors", ""), _style(F["sans"], 12, tx, leading=12 * 1.2, align=TA_CENTER))
  347. _, hh = pp.wrap(LW(inner), H); pp.drawOn(c, (W - LW(inner)) / 2, y - hh); y -= hh + VH(12)
  348. pp = Paragraph(ct.get("institution", ""), _style(F["sans"], 10, mut, leading=10 * 1.4, align=TA_CENTER))
  349. _, hh = pp.wrap(LW(inner), H); pp.drawOn(c, (W - LW(inner)) / 2, y - hh)
  350. foot = " · ".join([s for s in [ct.get("footer_left"), ct.get("footer_right")] if s])
  351. if foot:
  352. pp = Paragraph(foot, _style(F["sans"], 9, mut, leading=9 * 1.2, align=TA_CENTER))
  353. pp.wrap(LW(inner), H); pp.drawOn(c, (W - LW(inner)) / 2, YT(PXH - 57))
  354. def _t07_academic_symmetric(c, ct, F, P): _centered_dark(c, ct, F, P, 114, keywords=False)
  355. def _t08_academic_journal(c, ct, F, P): _centered_dark(c, ct, F, P, 152, keywords=True)
  356. def _t09_institutional(c, ct, F, P):
  357. black = _c("#1a1a1a"); linec = _c("#333333"); dmut = _c("#4a4a4a")
  358. # serif family: use kai if requested, else serif
  359. serif = F["kai"] if ct.get("style") == "kai" else F["serif"]
  360. c.saveState(); c.setStrokeColor(black); c.setLineWidth(LW(2.5))
  361. c.rect(X(40), YT(PXH - 56), X(PXW - 40) - X(40), YT(56) - YT(PXH - 56), stroke=1, fill=0); c.restoreState()
  362. cont_l = 90; cont_w = (PXW - 40 - 50) - 90; cont_bottom = PXH - 56 - 60
  363. y = 56 + 60
  364. y += center_line(c, ct["institution"], y, serif, 30, black, ls_px=6) + 30
  365. dw = 0.70 * cont_w
  366. hline(c, PXW / 2 - dw / 2, y, dw, 2, black); y += 2 + 40
  367. if ct.get("doc_type"):
  368. y += center_line(c, ct["doc_type"], y, F["sans"], 22, black, ls_px=4) + 50
  369. y += para(c, ct["title"], (PXW - 520) / 2, y, 520, serif, 24, black, line_h=1.4, align=TA_CENTER) + 110
  370. fld_w = 400; fld_x = (PXW - fld_w) / 2; label_w = 90
  371. for lbl, val in ct.get("fields", []):
  372. line_text(c, lbl, fld_x, y, F["sans"], 14, black, ls_px=2)
  373. vx = fld_x + label_w + 12; vw = fld_w - label_w - 12
  374. pp = Paragraph(val, _style(F["sans"], 14, black, leading=14 * 1.2, align=TA_CENTER))
  375. _, hh = pp.wrap(LW(vw), H); pp.drawOn(c, X(vx), YT(y) - hh)
  376. hline(c, vx, y + 26, vw, 1, linec); y += 58
  377. if ct.get("date"):
  378. center_line(c, ct["date"], cont_bottom - 26, F["sans"], 14, dmut, ls_px=2)
  379. TEMPLATES = {
  380. "01": (_t01_hud, "bg"), "02": (_t02_corporate, "bg"), "03": (_t03_monolith, "bg"),
  381. "04": (_t04_museum, "bg"), "05": (_t05_sidebar, "bg"),
  382. "06": (_t06_academic_vertical, "ac_bg"), "07": (_t07_academic_symmetric, "ac_bg"),
  383. "08": (_t08_academic_journal, "ac_bg"), "09": (_t09_institutional, "bg"),
  384. }
  385. # ═══════════════════════════════════════════════════════════════════
  386. # public API
  387. # ═══════════════════════════════════════════════════════════════════
  388. def render_cover(template, content, out_pdf, palette=None, fonts=None, font_overrides=None):
  389. """Render one cover to a single-page A4 PDF.
  390. template: "01".."09"; content: dict (keys depend on template family);
  391. palette: optional dict overriding DEFAULT_PALETTE; fonts: optional pre-detected
  392. dict from detect_fonts(); font_overrides: role->(name,path,idx)."""
  393. template = str(template).zfill(2)
  394. if template not in TEMPLATES:
  395. raise ValueError("unknown template %r (expected 01-09)" % template)
  396. P = dict(DEFAULT_PALETTE); P.update(palette or {})
  397. F = fonts or detect_fonts(font_overrides)
  398. fn, bgkey = TEMPLATES[template]
  399. c = canvas.Canvas(out_pdf, pagesize=(W, H))
  400. c.setFillColor(_c(P[bgkey])); c.rect(0, 0, W, H, stroke=0, fill=1)
  401. fn(c, content, F, P)
  402. c.showPage(); c.save()
  403. return out_pdf
  404. # ── demo sample content ──
  405. _DEMO_REPORT = {
  406. "kicker": "2025 年度可持续发展报告 · ANNUAL ESG REPORT", "hero": "青松环境科技",
  407. "summary": "本报告系统披露青松环境科技在 2025 财年的 ESG 实践、碳中和路径与核心运营数据,涵盖 Green Energy、循环经济与社会责任等关键议题。",
  408. "meta": "发布单位:青松环境科技集团 · 2026 年 3 月",
  409. "footer": "QINGSONG GREENTECH · DOC 2026-ESG-001",
  410. "footer_left": "青松环境科技集团 · 2026 年 3 月", "footer_right": "DOC 2026-ESG-001",
  411. "year": "2026", "word": "REPORT",
  412. }
  413. _DEMO_ACADEMIC = {
  414. "label": "博士学位论文 · DOCTORAL DISSERTATION",
  415. "title": "面向城市交通的深度强化学习信号协同优化方法研究",
  416. "subtitle": "A Study on Deep Reinforcement Learning for Urban Traffic Signal Coordination",
  417. "authors": "张明远", "institution": "清华大学 计算机科学与技术系",
  418. "keywords_lines": ["深度强化学习 · 交通信号控制", "多智能体协同 · 城市交通仿真"],
  419. "footer_left": "Journal of Intelligent Transportation", "footer_right": "2026 年 3 月",
  420. }
  421. _DEMO_INST = {
  422. "institution": "清华大学", "doc_type": "博士学位论文开题报告",
  423. "title": "面向城市交通的深度强化学习信号协同优化方法研究",
  424. "fields": [["姓  名", "张明远"], ["学  号", "2021210001"], ["导  师", "李国华 教授"],
  425. ["院  系", "计算机科学与技术系"], ["专  业", "计算机科学与技术"]],
  426. "date": "2026 年 3 月",
  427. }
  428. def _demo_content(t):
  429. if t in ("06", "07", "08"): return _DEMO_ACADEMIC
  430. if t == "09": return _DEMO_INST
  431. return _DEMO_REPORT
  432. def main(argv=None):
  433. ap = argparse.ArgumentParser(description="ReportLab cover generator (templates 01-09)")
  434. ap.add_argument("template", nargs="?", help="01-09")
  435. ap.add_argument("--out", default="cover.pdf")
  436. ap.add_argument("--content", help="path to JSON content file")
  437. ap.add_argument("--demo", action="store_true", help="render all 9 with sample content")
  438. ap.add_argument("--outdir", default=".")
  439. a = ap.parse_args(argv)
  440. F = detect_fonts()
  441. print("Detected fonts:", {k: v for k, v in F.items()})
  442. if a.demo:
  443. for t in TEMPLATES:
  444. out = os.path.join(a.outdir, "cover_%s.pdf" % t)
  445. render_cover(t, _demo_content(t), out, fonts=F); print("wrote", out)
  446. return
  447. if not a.template:
  448. ap.error("template (01-09) or --demo required")
  449. content = _demo_content(str(a.template).zfill(2))
  450. if a.content:
  451. with open(a.content, encoding="utf-8") as f: content = json.load(f)
  452. render_cover(a.template, content, a.out, fonts=F); print("wrote", a.out)
  453. if __name__ == "__main__":
  454. main()