Coverage for app / documents / pdf.py: 95%

347 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Render a :class:`DocumentSpec` to PDF. 

3 

4Deterministic layout from structured data: no model, no HTML engine and no 

5network. The Markdown body is parsed by markdown-it with raw HTML disabled 

6and turned into reportlab flowables here, so the only markup reportlab ever 

7sees is what this module writes. Every piece of document text is escaped 

8first, which keeps the model's text from ever becoming reportlab markup. 

9That matters because reportlab's paragraph markup can load images from 

10paths. Only ``http(s)`` links become link annotations, which the reader's own 

11viewer opens. 

12 

13Images: the caller passes the stored copies of the images the body shows 

14(``images``, keyed by each image's normalised link), as bytes it has already 

15verified (``images.load_for_pdf``). Those are drawn as figures, each with a 

16caption naming where it came from. Any other image — not embedded when the 

17document was made, or not stored — is drawn as its alt text, as every image 

18was before. Nothing here opens a file or a URL. 

19 

20Visuals: a ```chart, ```plot, ```graph, ```map or ```mermaid fence in the 

21body is drawn as vector graphics by ``visuals`` (one registered class a 

22kind), or is a short note saying why it could not be — never its source. 

23 

24Fonts: DejaVu (wide Unicode coverage) when installed — the image installs 

25``fonts-dejavu-core`` — else reportlab's built-in Helvetica, which covers 

26Western European text. 

27""" 

28 

29from __future__ import annotations 

30 

31import io 

32import os 

33from collections.abc import Mapping 

34from dataclasses import dataclass 

35from datetime import UTC, datetime 

36from typing import Any 

37from urllib.parse import urlsplit 

38from xml.sax.saxutils import escape 

39 

40from markdown_it.token import Token 

41from reportlab.lib.enums import TA_CENTER, TA_LEFT 

42from reportlab.lib.pagesizes import A4 

43from reportlab.lib.styles import ParagraphStyle 

44from reportlab.lib.units import mm 

45from reportlab.pdfbase import pdfmetrics 

46from reportlab.pdfbase.ttfonts import TTFont 

47from reportlab.platypus import ( 

48 HRFlowable, 

49 Image, 

50 KeepTogether, 

51 ListFlowable, 

52 ListItem, 

53 Paragraph, 

54 SimpleDocTemplate, 

55 Spacer, 

56 Table, 

57 TableStyle, 

58 XPreformatted, 

59) 

60 

61from app.util import vocab 

62 

63from .markdown import MD 

64from .spec import Confidence, DocumentSpec 

65from .visuals import kind_of 

66from .visuals import render as visuals 

67from .visuals.theme import ACCENT as _ACCENT 

68from .visuals.theme import INK as _INK 

69from .visuals.theme import MUTED as _MUTED 

70from .visuals.theme import PANEL as _PANEL 

71from .visuals.theme import PX as _PT_PER_PX 

72from .visuals.theme import RULE as _RULE 

73from .visuals.theme import Theme 

74 

75# --------------------------------------------------------------------------- 

76# Fonts 

77# --------------------------------------------------------------------------- 

78 

79_DEJAVU_DIRS = ( 

80 "/usr/share/fonts/truetype/dejavu", 

81 "/usr/share/fonts/dejavu", 

82) 

83#: What ``fonts-dejavu-core`` ships. The oblique faces are in 

84#: ``fonts-dejavu-extra``, so italics fall back to upright when absent. 

85_DEJAVU_FILES = { 

86 "DejaVuSans": "DejaVuSans.ttf", 

87 "DejaVuSans-Bold": "DejaVuSans-Bold.ttf", 

88 "DejaVuSansMono": "DejaVuSansMono.ttf", 

89} 

90_DEJAVU_OPTIONAL = { 

91 "DejaVuSans-Oblique": "DejaVuSans-Oblique.ttf", 

92 "DejaVuSans-BoldOblique": "DejaVuSans-BoldOblique.ttf", 

93} 

94 

95 

96@dataclass(frozen=True) 

97class _Fonts: 

98 regular: str 

99 bold: str 

100 mono: str 

101 

102 

103def _register_fonts() -> _Fonts: 

104 for directory in _DEJAVU_DIRS: 

105 paths = {name: os.path.join(directory, f) for name, f in _DEJAVU_FILES.items()} 

106 if not all(os.path.isfile(p) for p in paths.values()): 

107 continue 

108 optional = { 

109 name: os.path.join(directory, f) 

110 for name, f in _DEJAVU_OPTIONAL.items() 

111 if os.path.isfile(os.path.join(directory, f)) 

112 } 

113 try: 

114 for name, path in {**paths, **optional}.items(): 

115 if name not in pdfmetrics.getRegisteredFontNames(): 

116 pdfmetrics.registerFont(TTFont(name, path)) 

117 pdfmetrics.registerFontFamily( 

118 "DejaVuSans", 

119 normal="DejaVuSans", 

120 bold="DejaVuSans-Bold", 

121 italic=( 

122 "DejaVuSans-Oblique" 

123 if "DejaVuSans-Oblique" in optional 

124 else "DejaVuSans" 

125 ), 

126 boldItalic=( 

127 "DejaVuSans-BoldOblique" 

128 if "DejaVuSans-BoldOblique" in optional 

129 else "DejaVuSans-Bold" 

130 ), 

131 ) 

132 return _Fonts("DejaVuSans", "DejaVuSans-Bold", "DejaVuSansMono") 

133 except Exception: # a broken font file must not stop rendering 

134 break 

135 return _Fonts("Helvetica", "Helvetica-Bold", "Courier") 

136 

137 

138_FONTS: _Fonts | None = None 

139 

140 

141def _fonts() -> _Fonts: 

142 global _FONTS 

143 if _FONTS is None: 

144 _FONTS = _register_fonts() 

145 return _FONTS 

146 

147 

148# --------------------------------------------------------------------------- 

149# Styles 

150# --------------------------------------------------------------------------- 

151 

152 

153def _styles(f: _Fonts) -> dict[str, ParagraphStyle]: 

154 base = ParagraphStyle( 

155 "body", 

156 fontName=f.regular, 

157 fontSize=10, 

158 leading=14.5, 

159 textColor=_INK, 

160 alignment=TA_LEFT, 

161 spaceAfter=6, 

162 ) 

163 

164 def derive(name: str, **kw: Any) -> ParagraphStyle: 

165 return ParagraphStyle(name, parent=base, **kw) 

166 

167 return { 

168 "body": base, 

169 "title": derive( 

170 "title", fontName=f.bold, fontSize=22, leading=27, spaceAfter=4 

171 ), 

172 "subtitle": derive("subtitle", fontSize=12, leading=16, textColor=_MUTED), 

173 "meta": derive( 

174 "meta", fontSize=8.5, leading=11, textColor=_MUTED, spaceAfter=10 

175 ), 

176 "label": derive( 

177 "label", fontName=f.bold, fontSize=8.5, leading=11, textColor=_ACCENT 

178 ), 

179 # A heading stays on the page with what follows it — a figure that 

180 # moves to the next page would otherwise leave its heading behind. 

181 "h1": derive( 

182 "h1", 

183 fontName=f.bold, 

184 fontSize=16, 

185 leading=20, 

186 spaceBefore=12, 

187 keepWithNext=1, 

188 ), 

189 "h2": derive( 

190 "h2", 

191 fontName=f.bold, 

192 fontSize=13.5, 

193 leading=17, 

194 spaceBefore=10, 

195 keepWithNext=1, 

196 ), 

197 "h3": derive( 

198 "h3", 

199 fontName=f.bold, 

200 fontSize=11.5, 

201 leading=15, 

202 spaceBefore=8, 

203 keepWithNext=1, 

204 ), 

205 "h4": derive( 

206 "h4", 

207 fontName=f.bold, 

208 fontSize=10.5, 

209 leading=14, 

210 spaceBefore=6, 

211 keepWithNext=1, 

212 ), 

213 "quote": derive("quote", leftIndent=10, textColor=_MUTED), 

214 "code": derive( 

215 "code", fontName=f.mono, fontSize=8.5, leading=11, backColor=_PANEL 

216 ), 

217 "cell": derive("cell", fontSize=9, leading=12, spaceAfter=0), 

218 "cell_head": derive("cell_head", fontName=f.bold, fontSize=9, leading=12), 

219 "source": derive("source", fontSize=8.5, leading=11.5, spaceAfter=2), 

220 "caption": derive( 

221 "caption", 

222 fontSize=8, 

223 leading=10.5, 

224 textColor=_MUTED, 

225 alignment=TA_CENTER, 

226 spaceBefore=3, 

227 spaceAfter=8, 

228 ), 

229 "footer": derive("footer", fontSize=7.5, leading=9, textColor=_MUTED), 

230 # A visual's title stays with it, and a heading kept with the title 

231 # joins them (``keepWithNext`` chains, as a figure's does). 

232 "figure_title": derive( 

233 "figure_title", 

234 fontName=f.bold, 

235 fontSize=9.5, 

236 leading=12, 

237 alignment=TA_CENTER, 

238 spaceBefore=4, 

239 spaceAfter=4, 

240 keepWithNext=1, 

241 ), 

242 "figure_note": derive( 

243 "figure_note", 

244 fontSize=8.5, 

245 leading=11, 

246 textColor=_MUTED, 

247 backColor=_PANEL, 

248 borderPadding=4, 

249 spaceBefore=4, 

250 spaceAfter=8, 

251 ), 

252 } 

253 

254 

255# --------------------------------------------------------------------------- 

256# Markdown → flowables 

257# --------------------------------------------------------------------------- 

258 

259_SAFE_SCHEMES = ("http://", "https://") 

260 

261 

262#: What an image the document could not embed reads as — fe-core's card 

263#: says the same (``DocumentImages.tsx``, ``unavailableImage``). 

264IMAGE_UNAVAILABLE = "Image not available" 

265 

266 

267def unavailable_image(alt: str | None) -> str: 

268 """The text an image that was not embedded is drawn as.""" 

269 alt = (alt or "").strip() 

270 return f"{IMAGE_UNAVAILABLE}: {alt}" if alt else IMAGE_UNAVAILABLE 

271 

272 

273@dataclass(frozen=True) 

274class EmbeddedImage: 

275 """A stored copy of an image, verified, ready to draw.""" 

276 

277 data: bytes 

278 #: Its size in pixels. 

279 width: int 

280 height: int 

281 

282 

283@dataclass(frozen=True) 

284class _Figure: 

285 image: EmbeddedImage 

286 src: str 

287 alt: str 

288 

289 

290def _safe_href(href: str) -> str | None: 

291 return href if href.lower().startswith(_SAFE_SCHEMES) else None 

292 

293 

294def _attr(value: str) -> str: 

295 return escape(value, {chr(34): """}) 

296 

297 

298def _segments( 

299 token: Token | None, f: _Fonts, images: Mapping[str, EmbeddedImage] | None = None 

300) -> list[str | _Figure]: 

301 """One inline token as reportlab paragraph markup, every text escaped, 

302 split at each image in ``images``. 

303 

304 Each string is a complete paragraph's markup: the formatting open where 

305 an image splits it is closed before the figure and opened again after, 

306 so an image inside **bold** text or a link leaves both intact. An image 

307 not in ``images`` is its alt text. 

308 """ 

309 if token is None or not token.children: 

310 return [escape(token.content) if token is not None else ""] 

311 parts: list[str | _Figure] = [] 

312 out: list[str] = [] 

313 visible = False 

314 # Each open tag as (opening markup, closing markup); a link with an 

315 # unsafe destination opens nothing, so its close writes nothing. 

316 stack: list[tuple[str, str]] = [] 

317 

318 def push(opening: str, closing: str) -> None: 

319 stack.append((opening, closing)) 

320 out.append(opening) 

321 

322 def pop() -> None: 

323 if stack: 

324 out.append(stack.pop()[1]) 

325 

326 def flush(*, reopen: bool) -> None: 

327 nonlocal out, visible 

328 closing = [c for _, c in reversed(stack)] 

329 if visible: 

330 parts.append("".join(out + closing)) 

331 out = [o for o, _ in stack] if reopen else [] 

332 visible = False 

333 

334 for child in token.children: 

335 kind = child.type 

336 if kind == "text": 

337 out.append(escape(child.content)) 

338 visible = visible or bool(child.content.strip()) 

339 elif kind == "code_inline": 

340 out.append(f'<font face="{f.mono}">{escape(child.content)}</font>') 

341 visible = True 

342 elif kind in ("softbreak",): 

343 out.append(" ") 

344 elif kind == "hardbreak": 

345 out.append("<br/>") 

346 elif kind == "strong_open": 

347 push("<b>", "</b>") 

348 elif kind == "em_open": 

349 push("<i>", "</i>") 

350 elif kind == "s_open": 

351 push("<strike>", "</strike>") 

352 elif kind == "link_open": 

353 href = _safe_href(str(child.attrs.get("href") or "")) 

354 # Any other scheme (javascript:, file:, a relative path) stays 

355 # plain text. 

356 if href: 

357 push(f'<link href="{_attr(href)}" color="#6d28d9">', "</link>") 

358 else: 

359 push("", "") 

360 elif kind in ("strong_close", "em_close", "s_close", "link_close"): 

361 pop() 

362 elif kind == "image": 

363 src = str(child.attrs.get("src") or "") 

364 embedded = images.get(src) if images else None 

365 if embedded is not None: 

366 flush(reopen=True) 

367 parts.append(_Figure(embedded, src, child.content or "")) 

368 else: 

369 # Not embedded: said so, with what it would have shown. 

370 out.append(f"<i>{escape(unavailable_image(child.content))}</i>") 

371 visible = True 

372 else: 

373 out.append(escape(child.content or "")) 

374 visible = visible or bool((child.content or "").strip()) 

375 flush(reopen=False) 

376 if not parts: 

377 # Nothing visible at all (an empty cell): one empty paragraph, as 

378 # before images could split one. 

379 return [""] 

380 return parts 

381 

382 

383def _inline(token: Token | None, f: _Fonts) -> str: 

384 """reportlab paragraph markup for one inline token, every text escaped; 

385 every image is its alt text (a heading's, say).""" 

386 return "".join(p for p in _segments(token, f) if isinstance(p, str)) 

387 

388 

389#: A picture's natural size: its pixels at 96 per inch (``_PT_PER_PX``, 

390#: the visuals' ``PX``). 

391 

392 

393class _FittedImage(Image): 

394 """An image that fits the width it is given and a fixed height. 

395 

396 reportlab's ``Image.wrap`` ignores the space available, so an image wider 

397 than a table column or a list item's indent would spill out of it. This 

398 one scales down to the width, and to ``max_height`` — never to the height 

399 left on the page, which would shrink a figure at a page's foot instead of 

400 moving it to the next. 

401 """ 

402 

403 def __init__(self, image: EmbeddedImage, max_height: float) -> None: 

404 super().__init__( 

405 io.BytesIO(image.data), 

406 width=image.width * _PT_PER_PX, 

407 height=image.height * _PT_PER_PX, 

408 mask="auto", 

409 ) 

410 self._max_height = max_height 

411 # Its caption follows it onto the next page if it moves — and a 

412 # heading kept with the image joins the same group. (A KeepTogether 

413 # here would not: reportlab never chains keepWithNext into one.) 

414 self.keepWithNext = 1 

415 

416 def wrap(self, availWidth: float, availHeight: float) -> tuple[float, float]: 

417 self._unRestrictSize() 

418 return self._restrictSize(availWidth, self._max_height) 

419 

420 

421@dataclass(frozen=True) 

422class DrawnVisual: 

423 """One visual fence of a document's body, as its PDF met it.""" 

424 

425 kind: str 

426 #: Drawn, or a note said why not ("Chart not shown — it has no data"). 

427 drawn: bool 

428 

429 

430class _Builder: 

431 def __init__( 

432 self, 

433 styles: dict[str, ParagraphStyle], 

434 fonts: _Fonts, 

435 width: float, 

436 height: float, 

437 images: Mapping[str, EmbeddedImage] | None = None, 

438 ): 

439 self.s = styles 

440 self.f = fonts 

441 self.width = width 

442 #: The tallest a figure in the body may be: half a page, so a 

443 #: document of pictures stays a document to read. 

444 self.figure_height = height * 0.5 

445 #: A diagram may run to most of the frame. 

446 self.tall_height = height * 0.85 

447 self.images = images or {} 

448 self.theme = Theme(fonts.regular, fonts.bold, fonts.mono) 

449 #: What this document has left to draw (``visuals.Budget``). 

450 self.budget = visuals.Budget() 

451 #: Each visual fence met, in order: its kind and whether it was 

452 #: drawn (else a note says why not). What ``render_pdf`` reports. 

453 self.drawn: list[DrawnVisual] = [] 

454 

455 def build(self, tokens: list[Token]) -> list[Any]: 

456 flow, _ = self._blocks(tokens, 0, None) 

457 return flow 

458 

459 def _caption(self, figure: _Figure) -> Paragraph: 

460 parts: list[str] = [] 

461 if figure.alt.strip(): 

462 parts.append(escape(figure.alt.strip())) 

463 host = urlsplit(figure.src).hostname or "" 

464 source = escape(f"Image: {host}" if host else "Image") 

465 href = _safe_href(figure.src) 

466 parts.append( 

467 f'<link href="{_attr(href)}" color="#6d28d9">{source}</link>' 

468 if href 

469 else source 

470 ) 

471 return Paragraph(" — ".join(parts), self.s["caption"]) 

472 

473 def _figure(self, figure: _Figure, *, max_height: float) -> list[Any]: 

474 return [_FittedImage(figure.image, max_height), self._caption(figure)] 

475 

476 def _visual(self, kind: str, source: str) -> list[Any]: 

477 """A visual fence drawn, or a note saying why it is not — never its 

478 source (``visuals.prepare``).""" 

479 tall = visuals.VISUALS[kind].tall 

480 result = visuals.prepare( 

481 kind, 

482 source, 

483 theme=self.theme, 

484 width=self.width, 

485 max_height=self.tall_height if tall else self.figure_height, 

486 budget=self.budget, 

487 ) 

488 self.drawn.append( 

489 DrawnVisual(kind, drawn=not isinstance(result, visuals.Unshown)) 

490 ) 

491 if isinstance(result, visuals.Unshown): 

492 named = f": {escape(result.title)}" if result.title else "" 

493 return [ 

494 Paragraph( 

495 f"<b>{escape(result.noun)} not shown{named}</b> — " 

496 f"{escape(result.reason)}.", 

497 self.s["figure_note"], 

498 ) 

499 ] 

500 flow: list[Any] = [] 

501 if result.title: 

502 flow.append(Paragraph(escape(result.title), self.s["figure_title"])) 

503 if result.credit: 

504 result.flowable.keepWithNext = 1 

505 flow.append(result.flowable) 

506 if result.credit: 

507 flow.append(Paragraph(escape(result.credit), self.s["caption"])) 

508 flow.append(Spacer(1, 8)) 

509 return flow 

510 

511 def _flow(self, token: Token, style: str) -> list[Any]: 

512 """A paragraph's flowables: its text, and a figure for each image 

513 embedded in it.""" 

514 flow: list[Any] = [] 

515 for part in _segments(token, self.f, self.images): 

516 if isinstance(part, _Figure): 

517 flow += self._figure(part, max_height=self.figure_height) 

518 else: 

519 flow.append(Paragraph(part, self.s[style])) 

520 return flow 

521 

522 def _blocks( 

523 self, tokens: list[Token], i: int, until: str | None, text: str = "body" 

524 ) -> tuple[list[Any], int]: 

525 flow: list[Any] = [] 

526 while i < len(tokens): 

527 t = tokens[i] 

528 if until and t.type == until: 

529 return flow, i + 1 

530 if t.type == "heading_open": 

531 level = min(int(t.tag[1]), 4) 

532 flow.append( 

533 Paragraph(_inline(tokens[i + 1], self.f), self.s[f"h{level}"]) 

534 ) 

535 i += 3 

536 elif t.type == "paragraph_open": 

537 flow.extend(self._flow(tokens[i + 1], text)) 

538 i += 3 

539 elif t.type in ("bullet_list_open", "ordered_list_open"): 

540 items, i = self._list(tokens, i + 1, t.type.replace("_open", "_close")) 

541 ordered = t.type == "ordered_list_open" 

542 flow.append( 

543 ListFlowable( 

544 items, 

545 bulletType="1" if ordered else "bullet", 

546 bulletFormat="%s." if ordered else None, 

547 start=int(t.attrs.get("start") or 1) if ordered else "•", 

548 leftIndent=14, 

549 bulletFontName=self.f.regular, 

550 bulletFontSize=9, 

551 ) 

552 ) 

553 elif t.type == "blockquote_open": 

554 inner, i = self._blocks(tokens, i + 1, "blockquote_close", "quote") 

555 flow.extend(inner) 

556 elif t.type == "fence" and (kind := kind_of(t.info)) is not None: 

557 flow.extend(self._visual(kind, t.content)) 

558 i += 1 

559 elif t.type in ("fence", "code_block"): 

560 flow.append( 

561 XPreformatted(escape(t.content.rstrip("\n")), self.s["code"]) 

562 ) 

563 flow.append(Spacer(1, 4)) 

564 i += 1 

565 elif t.type == "table_open": 

566 table, i = self._table(tokens, i + 1) 

567 if table is not None: 

568 flow += [table, Spacer(1, 8)] 

569 elif t.type == "hr": 

570 flow.append( 

571 HRFlowable(width="100%", color=_RULE, spaceBefore=4, spaceAfter=8) 

572 ) 

573 i += 1 

574 else: 

575 i += 1 

576 return flow, i 

577 

578 def _list( 

579 self, tokens: list[Token], i: int, close: str 

580 ) -> tuple[list[ListItem], int]: 

581 items: list[ListItem] = [] 

582 while i < len(tokens) and tokens[i].type != close: 

583 if tokens[i].type == "list_item_open": 

584 inner, i = self._blocks(tokens, i + 1, "list_item_close") 

585 # Tight lists wrap their text in hidden paragraphs; either way 

586 # the item is its flowables. 

587 items.append(ListItem(inner or [Paragraph("", self.s["body"])])) 

588 else: 

589 i += 1 

590 return items, i + 1 

591 

592 def _cell(self, token: Token, style: str) -> Any: 

593 """A table cell: one paragraph, or — when it shows an embedded image — 

594 its paragraphs and figures, each figure fitted to the column.""" 

595 parts = _segments(token, self.f, self.images) 

596 if len(parts) == 1 and isinstance(parts[0], str): 

597 return Paragraph(parts[0], self.s[style]) 

598 flow: list[Any] = [] 

599 for part in parts: 

600 if isinstance(part, _Figure): 

601 flow += self._figure(part, max_height=_CELL_FIGURE_HEIGHT) 

602 else: 

603 flow.append(Paragraph(part, self.s[style])) 

604 return flow 

605 

606 def _table(self, tokens: list[Token], i: int) -> tuple[Table | None, int]: 

607 rows: list[list[Any]] = [] 

608 header_rows = 0 

609 in_head = False 

610 row: list[Any] = [] 

611 while i < len(tokens) and tokens[i].type != "table_close": 

612 t = tokens[i] 

613 if t.type == "thead_open": 

614 in_head = True 

615 elif t.type == "thead_close": 

616 in_head = False 

617 elif t.type == "tr_open": 

618 row = [] 

619 elif t.type == "tr_close": 

620 rows.append(row) 

621 header_rows += 1 if in_head else 0 

622 elif t.type in ("th_open", "td_open"): 

623 style = "cell_head" if t.type == "th_open" else "cell" 

624 row.append(self._cell(tokens[i + 1], style)) 

625 i += 2 

626 i += 1 

627 if not rows: 

628 return None, i + 1 

629 cols = max(len(r) for r in rows) 

630 rows = [r + [Paragraph("", self.s["cell"])] * (cols - len(r)) for r in rows] 

631 table = Table( 

632 rows, colWidths=[self.width / cols] * cols, repeatRows=header_rows 

633 ) 

634 commands: list[tuple[Any, ...]] = [ 

635 ("GRID", (0, 0), (-1, -1), 0.5, _RULE), 

636 ("VALIGN", (0, 0), (-1, -1), "TOP"), 

637 ("TOPPADDING", (0, 0), (-1, -1), 4), 

638 ("BOTTOMPADDING", (0, 0), (-1, -1), 4), 

639 ] 

640 if header_rows: 

641 commands.append(("BACKGROUND", (0, 0), (-1, header_rows - 1), _PANEL)) 

642 table.setStyle(TableStyle(commands)) 

643 return table, i + 1 

644 

645 

646#: The tallest a figure in a table cell may be. 

647_CELL_FIGURE_HEIGHT = 50 * mm 

648 

649 

650def _markdown(text: str, builder: _Builder) -> list[Any]: 

651 return builder.build(MD.parse(text or "")) 

652 

653 

654# --------------------------------------------------------------------------- 

655# The document 

656# --------------------------------------------------------------------------- 

657 

658#: One label per level of the document's confidence scale. 

659_CONFIDENCE_LABEL = {level: level.capitalize() for level in vocab.values(Confidence)} 

660 

661 

662def _section(label: str, s: dict[str, ParagraphStyle]) -> list[Any]: 

663 return [ 

664 Spacer(1, 6), 

665 Paragraph(escape(label.upper()), s["label"]), 

666 HRFlowable(width="100%", color=_RULE, spaceBefore=2, spaceAfter=6), 

667 ] 

668 

669 

670def _bullets(lines: list[str], s: dict[str, ParagraphStyle], f: _Fonts) -> ListFlowable: 

671 return ListFlowable( 

672 [ListItem(Paragraph(escape(line), s["body"])) for line in lines], 

673 bulletType="bullet", 

674 leftIndent=14, 

675 bulletFontName=f.regular, 

676 bulletFontSize=9, 

677 ) 

678 

679 

680#: Printed on every page. Article 50 of the EU AI Act requires content an AI 

681#: system generates to be marked as such; fe-core's chat exports carry the 

682#: same sentence (``src/util/aiDisclosure.ts``). 

683AI_DISCLOSURE = ( 

684 "Generated by an AI system on CHAIN-R. It can be wrong, so check the " 

685 "sources before relying on it." 

686) 

687#: The machine-readable mark, in the PDF's document information. 

688AI_KEYWORDS = ["AI-generated", "CHAIN-R"] 

689 

690 

691class _KeepTogether(KeepTogether): 

692 """reportlab's group for flowables kept with the next (a heading, a 

693 figure's title), counting a tall diagram by its first rows. 

694 

695 reportlab starts a new page for any group taller than the space left, 

696 so a heading kept with a diagram that splits across pages always began 

697 a page of its own. Counted by its first rows, the group starts where 

698 those fit, and the diagram splits on from there (``VisualFlowable``). 

699 """ 

700 

701 def wrap(self, aW: float, aH: float) -> tuple[float, float]: 

702 size = super().wrap(aW, aH) 

703 for flowable in self._content: 

704 if isinstance(flowable, visuals.VisualFlowable) and flowable.tall(aW): 

705 self._H -= flowable.height - flowable.lead_height(aW) 

706 return size 

707 

708 

709def render_pdf( 

710 spec: DocumentSpec, 

711 *, 

712 images: Mapping[str, EmbeddedImage] | None = None, 

713 footer: str | None = None, 

714 generated_at: datetime | None = None, 

715 drawn: list[DrawnVisual] | None = None, 

716) -> bytes: 

717 """The PDF for ``spec``. Every page closes with the AI disclosure, then 

718 ``footer``: a provenance line (what produced the document, and when). 

719 

720 ``images`` holds the stored copies of the images the body shows, keyed by 

721 each image's normalised link; any other image is drawn as its alt text. 

722 ``drawn``, when given, collects each visual fence of the body and whether 

723 it was drawn.""" 

724 f = _fonts() 

725 s = _styles(f) 

726 buffer = io.BytesIO() 

727 margin = 18 * mm 

728 doc = SimpleDocTemplate( 

729 buffer, 

730 pagesize=A4, 

731 leftMargin=margin, 

732 rightMargin=margin, 

733 topMargin=margin, 

734 bottomMargin=margin + 6 * mm, 

735 title=spec.title, 

736 subject=spec.subtitle or "", 

737 author="CHAIN-R", 

738 creator="CHAIN-R", 

739 keywords=AI_KEYWORDS, 

740 ) 

741 builder = _Builder(s, f, doc.width, doc.height, images) 

742 when = (generated_at or datetime.now(UTC)).strftime("%d %b %Y") 

743 footer_text = escape(AI_DISCLOSURE) + "<br/>" + escape((footer or "CHAIN-R")[:300]) 

744 

745 story: list[Any] = [Paragraph(escape(spec.title), s["title"])] 

746 if spec.subtitle: 

747 story.append(Paragraph(escape(spec.subtitle), s["subtitle"])) 

748 meta = [f"Generated {when}"] 

749 if spec.confidence: 

750 meta.append(f"Confidence: {_CONFIDENCE_LABEL[spec.confidence]}") 

751 story.append(Paragraph(" · ".join(meta), s["meta"])) 

752 

753 if spec.summary: 

754 panel = Table( 

755 [[Paragraph(escape(spec.summary), s["body"])]], 

756 colWidths=[doc.width], 

757 style=TableStyle( 

758 [ 

759 ("BACKGROUND", (0, 0), (-1, -1), _PANEL), 

760 ("LINEBEFORE", (0, 0), (0, -1), 2, _ACCENT), 

761 ("LEFTPADDING", (0, 0), (-1, -1), 10), 

762 ("RIGHTPADDING", (0, 0), (-1, -1), 10), 

763 ("TOPPADDING", (0, 0), (-1, -1), 8), 

764 ("BOTTOMPADDING", (0, 0), (-1, -1), 4), 

765 ] 

766 ), 

767 ) 

768 story += [*_section("Summary", s), panel] 

769 

770 if spec.key_findings: 

771 story += [*_section("Key findings", s), _bullets(spec.key_findings, s, f)] 

772 

773 if spec.body.strip(): 

774 story += [Spacer(1, 8), *_markdown(spec.body, builder)] 

775 

776 if spec.open_questions: 

777 story += [*_section("Open questions", s), _bullets(spec.open_questions, s, f)] 

778 

779 if spec.sources: 

780 rows = [ 

781 Paragraph(f"[{n}] {escape(src)}", s["source"]) 

782 for n, src in enumerate(spec.sources, start=1) 

783 ] 

784 story += [KeepTogether(_section("Sources", s) + rows[:1]), *rows[1:]] 

785 

786 def _decorate(canvas: Any, document: Any) -> None: 

787 canvas.saveState() 

788 canvas.setFont(f.regular, 7.5) 

789 canvas.setFillColor(_MUTED) 

790 y = margin - 2 * mm 

791 p = Paragraph(footer_text, s["footer"]) 

792 _, height = p.wrap(document.width - 20 * mm, 20 * mm) 

793 p.drawOn(canvas, margin, y - height + 6) 

794 canvas.drawRightString(A4[0] - margin, y, f"Page {document.page}") 

795 canvas.restoreState() 

796 

797 doc.keepTogetherClass = _KeepTogether 

798 doc.build(story, onFirstPage=_decorate, onLaterPages=_decorate) 

799 if drawn is not None: 

800 drawn.extend(builder.drawn) 

801 return buffer.getvalue()