From d504f52de1a539ab11d0e403fc8d979d15cb26ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Thu, 26 Nov 2026 19:07:39 +0100 Subject: [PATCH] feat(pdf): Theme mit eigener Schrift und Farben, Ersatzschrift je Absatz (pdf 0.2.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PdfTheme / FontFamily / register_font_family: Schrift und Farben des Tools (Text, gedämpft, Überschriften, Zitate, Tabellen, Kasten, Fußzeile); ohne Theme bleibt das Aussehen wie bisher. - Absätze mit Zeichen, die der Theme-Schrift fehlen, setzt der Rahmen in der mitgelieferten Schrift (gleicher Schnitt); nur was keine der beiden hat, wird zu "?". Gilt für heading, paragraph, rich, bullets, table, Fußzeile. - PdfDocument.usable_height: Satzspiegel abzüglich Innenabstand des Rahmens. - Fix: box() maß ohne den eigenen Innenabstand gegen eine zu großzügige Grenze; ein Kasten knapp unter Seitenhöhe brach mit LayoutError ab. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 29 ++++ packages/django/basicbar-pdf/README.md | 46 ++++- .../basicbar-pdf/basicbar_pdf/__init__.py | 7 +- .../basicbar-pdf/basicbar_pdf/document.py | 87 ++++++---- .../django/basicbar-pdf/basicbar_pdf/html.py | 62 +++---- .../basicbar_pdf/tests/test_theme.py | 157 ++++++++++++++++++ .../django/basicbar-pdf/basicbar_pdf/theme.py | 140 ++++++++++++++++ packages/django/basicbar-pdf/pyproject.toml | 4 +- 8 files changed, 463 insertions(+), 69 deletions(-) create mode 100644 packages/django/basicbar-pdf/basicbar_pdf/tests/test_theme.py create mode 100644 packages/django/basicbar-pdf/basicbar_pdf/theme.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4612d4a..31b5bdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,35 @@ Changelog ist die Upgrade-Anleitung für die Tools. ## [Unreleased] +### basicbar-pdf (→ wird `pdf/v0.2.0`) + +- Theme: `PdfDocument(..., theme=PdfTheme(...))` setzt Schrift und Farben + des Tools. `PdfTheme` hat eine Schriftfamilie (`FontFamily`, zu + registrieren mit `register_font_family(name, regular=…, bold=…, + italic=…, bold_italic=…)`; fehlende Schnitte nehmen den nächsten) sowie die + Farben für Text, gedämpften Text, Überschriften, Zitate, Tabellenlinien, + Tabellenkopf, Kasten (Fläche, Rand) und Fußzeile. Ohne Theme bleibt alles + wie bisher. `make_styles(theme)` und `html_to_flowables(..., theme=…)` + nehmen das Theme ebenfalls an. +- Ersatzschrift je Absatz: Hat ein Absatz Zeichen, die der Theme-Schrift + fehlen, die mitgelieferte Plus Jakarta Sans aber hat (z. B. „Ş“, „Ł“, „→“ + bei einer Schrift mit Latin-Teilmenge), wird dieser Absatz in der + mitgelieferten Schrift gesetzt, im gleichen Schnitt. Nur was keine der + beiden Schriften hat, wird zu „?“. Gilt für `heading`, `paragraph`, `rich`, + `bullets`, `table` und die Fußzeile; `auto_widths` misst in der Schrift, + die die Zelle setzt. +- Die Fußzeile steht in der Theme-Schrift und -Farbe. +- Neu `PdfDocument.usable_height`: die Höhe, die ein Flowable auf einer Seite + haben darf (Satzspiegel abzüglich des Innenabstands des Rahmens). Eigene + Bausteine über `add()` müssen damit nicht mehr selbst rechnen. +- Fix: `box()` maß die Höhe ohne seinen eigenen Innenabstand und gegen eine zu + großzügige Grenze. Ein Kasten knapp unter einer Seitenhöhe wurde gerahmt + und brach das Rendern mit `LayoutError` ab; jetzt fällt er wie dokumentiert + ungerahmt aus. +- Migration: keine. Ein Tool mit eigener Schrift kann eigene Unterklassen + oder eigene Höhenrechnung durch `theme=` und `usable_height` ersetzen + (erprobt für orientierBAR: Signika, Uni-Farben). + ### @basicbar/ui (→ wird `ui/v0.12.0`) - `RichTextEditor` bekommt die Prop `tools` (Typ `RichTextTool[]`, Standard diff --git a/packages/django/basicbar-pdf/README.md b/packages/django/basicbar-pdf/README.md index 2f24028..02f9d11 100644 --- a/packages/django/basicbar-pdf/README.md +++ b/packages/django/basicbar-pdf/README.md @@ -3,7 +3,8 @@ Gemeinsamer PDF-Rahmen der „-bar“-Tools für herunterladbare Dokumente (Protokolle, Berichte): [reportlab](https://www.reportlab.com/) mit der mitgelieferten Schrift **Plus Jakarta Sans** (SIL OFL 1.1, `basicbar_pdf/fonts/OFL.txt`), -A4 hoch oder quer, Fußzeile „Seite x von y“ auf jeder Seite. +A4 hoch oder quer, Fußzeile „Seite x von y“ auf jeder Seite. Ein Tool kann +eigene Schrift und Farben setzen (Theme, siehe unten). Kein Django nötig: die einzigen sichtbaren Texte des Rahmens (Seitenangabe, Bild-Platzhalter) sind Parameter; das Tool übergibt seine Übersetzungen @@ -13,7 +14,7 @@ Bild-Platzhalter) sind Parameter; das Tool übergibt seine Übersetzungen ```text # requirements.txt -basicbar-pdf @ https://github.com/virtUOS/basicbar/archive/refs/tags/pdf/v0.1.0.tar.gz#subdirectory=packages/django/basicbar-pdf +basicbar-pdf @ https://github.com/virtUOS/basicbar/archive/refs/tags/pdf/v0.2.0.tar.gz#subdirectory=packages/django/basicbar-pdf ``` ```python @@ -40,7 +41,7 @@ Die msgids `"Page %(page)s of %(pages)s"` und `"[Image]"` gehören in den ## API `PdfDocument(title, *, footer_left="", author="", landscape=False, margin_mm=20, -page_label="Page %(page)s of %(pages)s", image_placeholder="[Image]", compress=True)` +page_label="Page %(page)s of %(pages)s", image_placeholder="[Image]", compress=True, theme=None)` | Methode | Zweck | |---|---| @@ -51,6 +52,7 @@ page_label="Page %(page)s of %(pages)s", image_placeholder="[Image]", compress=T | `table(rows, *, header=True, col_widths=None, align_right_from=None, strong_rows=())` | Gitter-Tabelle, Kopfzeile wiederholt sich auf jeder Seite; `col_widths="auto"` misst die Spalten (kein Wort wird getrennt), `align_right_from` setzt Zahlenspalten rechtsbündig, `strong_rows` fettet Zeilen (Kopfzeile = 0) | | `auto_widths(rows, *, header=True)` | die Spaltenbreiten von `col_widths="auto"` | | `usable_width` | Breite zwischen den Rändern in Punkt | +| `usable_height` | Höhe, die ein Flowable auf einer Seite haben darf (Satzspiegel abzüglich Innenabstand des Rahmens), in Punkt; für eigene Bausteine über `add()` | | `rule()`, `spacer(mm=3)` | Trennlinie, Abstand | | `keep_together(builder)` | Block bleibt auf einer Seite, wenn er passt | | `box(builder)` | hellgrau gerahmter Block; höher als eine Seite → ungerahmt | @@ -58,8 +60,42 @@ page_label="Page %(page)s of %(pages)s", image_placeholder="[Image]", compress=T | `render() -> bytes` | das PDF | Außerdem: `safe_text(text)` (Zeichen, die die Schrift nicht hat — Griechisch, -Kyrillisch, CJK, Emoji — werden zu „?“), `html_to_flowables(html, styles)`, -`make_styles()`, `FONT`, `FONT_BOLD`. +Kyrillisch, CJK, Emoji — werden zu „?“), `html_to_flowables(html, styles, theme=None)`, +`make_styles(theme=None)`, `FONT`, `FONT_BOLD`. + +## Theme: eigene Schrift und Farben + +```python +from pathlib import Path +from basicbar_pdf import PdfDocument, PdfTheme, register_font_family + +FONTS = Path(__file__).parent / "fonts" +signika = register_font_family( + "Signika", regular=FONTS / "Signika-Regular.ttf", bold=FONTS / "Signika-Bold.ttf", +) # ohne Kursive: kursiv fällt auf normal, fett-kursiv auf fett +THEME = PdfTheme(fonts=signika, text="#3e3e3f", heading="#ad1034", box_fill="#f3f3f3") + +doc = PdfDocument(_("Recommendations"), theme=THEME) +``` + +`PdfTheme` (unveränderlich; die Standardwerte sind das bisherige Aussehen): + +| Feld | Standard | Wirkung | +|---|---|---| +| `fonts` | Plus Jakarta Sans | Schriftfamilie (`FontFamily`, von `register_font_family`) | +| `text` | `#000000` | Fließtext | +| `muted` | `#666666` | Stil `muted` | +| `heading` | wie `text` | h1–h3 | +| `quote` | `#444444` | Zitate | +| `grid`, `table_head` | `#c8c8c8`, `#eeeeee` | Tabellenlinien und `rule()`, Tabellenkopf | +| `box_fill`, `box_border` | `#f3f3f3`, `#aaaaaa` | `box()` | +| `footer` | `#555555` | Fußzeile (in der Theme-Schrift) | + +**Ersatzschrift je Absatz:** Hat ein Absatz Zeichen, die der Theme-Schrift +fehlen, die mitgelieferte Plus Jakarta Sans aber hat, wird er in der +mitgelieferten Schrift gesetzt (gleicher Schnitt). Nur was keine der beiden +Schriften hat, wird zu „?“. Eigene Flowables über `add()` können dasselbe mit +`theme.paragraph(markup, style)` und `theme.safe(text)` tun. ## Tests diff --git a/packages/django/basicbar-pdf/basicbar_pdf/__init__.py b/packages/django/basicbar-pdf/basicbar_pdf/__init__.py index b6ac7f8..5213360 100644 --- a/packages/django/basicbar-pdf/basicbar_pdf/__init__.py +++ b/packages/django/basicbar-pdf/basicbar_pdf/__init__.py @@ -1,7 +1,8 @@ # SPDX-License-Identifier: Apache-2.0 # Copyright 2026 Universität Osnabrück (virtUOS) -"""PDF frame for downloadable documents of the -bar tools (reportlab, bundled Plus Jakarta Sans). +"""PDF frame for downloadable documents of the -bar tools (reportlab, bundled Plus Jakarta Sans, +optional theme with the tool's own font and colours). No Django dependency: user-visible labels (page footer, image placeholder) are parameters, so a tool passes its own (lazy) gettext strings. @@ -10,5 +11,7 @@ from .document import PdfDocument from .fonts import FONT, FONT_BOLD, safe_text from .html import html_to_flowables, make_styles +from .theme import BUNDLED_FAMILY, DEFAULT_THEME, FontFamily, PdfTheme, register_font_family -__all__ = ["FONT", "FONT_BOLD", "PdfDocument", "html_to_flowables", "make_styles", "safe_text"] +__all__ = ["BUNDLED_FAMILY", "DEFAULT_THEME", "FONT", "FONT_BOLD", "FontFamily", "PdfDocument", "PdfTheme", + "html_to_flowables", "make_styles", "register_font_family", "safe_text"] diff --git a/packages/django/basicbar-pdf/basicbar_pdf/document.py b/packages/django/basicbar-pdf/basicbar_pdf/document.py index b81b5c7..4f55f05 100644 --- a/packages/django/basicbar-pdf/basicbar_pdf/document.py +++ b/packages/django/basicbar-pdf/basicbar_pdf/document.py @@ -13,17 +13,24 @@ from reportlab.lib.units import mm as MM from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.pdfgen import canvas -from reportlab.platypus import HRFlowable, KeepTogether, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle +from reportlab.platypus import HRFlowable, KeepTogether, SimpleDocTemplate, Spacer, Table, TableStyle +from reportlab.platypus.frames import Frame -from .fonts import FONT, FONT_BOLD, safe_text from .html import _markup, html_to_flowables, make_styles +from .theme import DEFAULT_THEME, PdfTheme PAGE_LABEL = "Page %(page)s of %(pages)s" -GRID = colors.HexColor("#c8c8c8") +GRID = colors.HexColor(DEFAULT_THEME.grid) # kept for tools that imported it; the theme decides +# SimpleDocTemplate's frame keeps reportlab's default padding inside the margins (top and bottom). +_FRAME_PADDING = Frame(0, 0, 100, 100).topPadding + Frame(0, 0, 100, 100).bottomPadding -def _numbered_canvas(footer_left: str, page_label: str, margin: float): - left = safe_text(footer_left) +def _numbered_canvas(footer_left: str, page_label: str, margin: float, theme: PdfTheme): + left = theme.safe(footer_left) + + def draw(c, x, text, right=False): + c.setFont(theme.font_for(theme.fonts.normal, text), 8) + (c.drawRightString if right else c.drawString)(x, 10 * MM, text) class NumberedCanvas(canvas.Canvas): """Two passes: the page count is known only after the last page.""" @@ -41,11 +48,10 @@ def save(self): for state in self._pages: self.__dict__.update(state) width, _height = self._pagesize - self.setFont(FONT, 8) - self.setFillColor(colors.HexColor("#555555")) - self.drawString(margin, 10 * MM, left) - self.drawRightString(width - margin, 10 * MM, - safe_text(page_label % {"page": self._pageNumber, "pages": count})) + self.setFillColor(colors.HexColor(theme.footer)) + draw(self, margin, left) + draw(self, width - margin, theme.safe(page_label % {"page": self._pageNumber, "pages": count}), + right=True) super().showPage() super().save() @@ -59,11 +65,14 @@ class PdfDocument: ``page_label`` and ``image_placeholder`` are the only user-visible strings of the frame; pass the tool's translations (``gettext_lazy`` works — they are resolved when used). All text is escaped; characters the bundled font lacks become "?" (:func:`safe_text`). + + ``theme`` (:class:`PdfTheme`) sets the tool's own font and colours; a paragraph the theme font + cannot set falls back to the bundled font, and only characters neither font has become "?". """ def __init__(self, title: str, *, footer_left: str = "", author: str = "", landscape: bool = False, margin_mm: float = 20, page_label=PAGE_LABEL, image_placeholder="[Image]", - compress: bool = True): + compress: bool = True, theme: PdfTheme | None = None): self.title = title self.author = author self.footer_left = footer_left @@ -73,7 +82,8 @@ def __init__(self, title: str, *, footer_left: str = "", author: str = "", lands self.page_label = page_label self.image_placeholder = image_placeholder self.compress = compress - self.styles = make_styles() + self.theme = theme or DEFAULT_THEME + self.styles = make_styles(self.theme) self._story: list = [] @property @@ -81,6 +91,15 @@ def usable_width(self) -> float: """Width between the side margins in points (for ``col_widths``).""" return self.pagesize[0] - 2 * self.margin + @property + def usable_height(self) -> float: + """Height a flowable may take on one page in points: between the margins, less the frame's + own padding. Anything taller (a table row, a one-cell box) cannot be placed.""" + return self.pagesize[1] - self.margin - self.bottom - _FRAME_PADDING + + def _para(self, text: str, style: ParagraphStyle, **kwargs): + return self.theme.paragraph(_markup(text, self.theme), style, **kwargs) + def _add(self, *flowables): self._story.extend(flowables) @@ -89,36 +108,39 @@ def add(self, *flowables): self._add(*flowables) def heading(self, text: str, level: int = 1): - self._add(Paragraph(_markup(text), self.styles[f"h{min(max(level, 1), 3)}"])) + self._add(self._para(text, self.styles[f"h{min(max(level, 1), 3)}"])) def paragraph(self, text: str, *, style: str = "normal"): - self._add(Paragraph(_markup(text), self.styles[style])) + self._add(self._para(text, self.styles[style])) def rich(self, html: str): """Editor HTML (paragraphs, inline formatting, lists, headings, quotes, links).""" - self._add(*html_to_flowables(html, self.styles, image_placeholder=self.image_placeholder)) + self._add(*html_to_flowables(html, self.styles, image_placeholder=self.image_placeholder, + theme=self.theme)) def bullets(self, items: list[str]): style = ParagraphStyle("bl", parent=self.styles["normal"], leftIndent=16, bulletIndent=4) for item in items: - self._add(Paragraph(_markup(item), style, bulletText="•")) + self._add(self._para(item, style, bulletText="•")) def auto_widths(self, rows: Sequence[Sequence[str]], *, header: bool = True) -> list[float]: """Column widths for ``rows``: each column at least as wide as its longest header word and its longest value (no value is broken mid-word); the remaining width is shared evenly, or everything shrinks proportionally when the page is too narrow.""" font_size = self.styles["cell"].fontSize + bold = self.styles["cell_head"].fontName need = [] for col in range(max((len(row) for row in rows), default=0)): widths = [0.0] for i, row in enumerate(rows): if col >= len(row): continue - cell = safe_text(row[col]) + cell = self.theme.safe(row[col]) + font = self.theme.font_for(bold, cell) if header and i == 0: - widths += [stringWidth(word, FONT_BOLD, font_size) for word in cell.split()] + widths += [stringWidth(word, font, font_size) for word in cell.split()] else: - widths += [stringWidth(line, FONT_BOLD, font_size) for line in cell.split("\n")] + widths += [stringWidth(line, font, font_size) for line in cell.split("\n")] need.append(max(widths) + 8) # cell padding left + right if not need: return [] @@ -154,20 +176,21 @@ def cell_style(i: int, j: int) -> ParagraphStyle: alignment=TA_RIGHT) if right else base return styles[key] - data = [[Paragraph(_markup(cell), cell_style(i, j)) for j, cell in enumerate(row)] + data = [[self._para(cell, cell_style(i, j)) for j, cell in enumerate(row)] for i, row in enumerate(rows)] table = Table(data, colWidths=col_widths, repeatRows=1 if header else 0) style = [("VALIGN", (0, 0), (-1, -1), "TOP"), - ("GRID", (0, 0), (-1, -1), 0.25, GRID), + ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor(self.theme.grid)), ("TOPPADDING", (0, 0), (-1, -1), 3), ("BOTTOMPADDING", (0, 0), (-1, -1), 3)] if header: - style.append(("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#eeeeee"))) + style.append(("BACKGROUND", (0, 0), (-1, 0), colors.HexColor(self.theme.table_head))) table.setStyle(TableStyle(style)) self._add(table, Spacer(1, 2 * MM)) def rule(self): """Thin horizontal separator line.""" - self._add(HRFlowable(width="100%", thickness=0.5, color=GRID, spaceBefore=2 * MM, spaceAfter=2 * MM)) + self._add(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor(self.theme.grid), + spaceBefore=2 * MM, spaceAfter=2 * MM)) def spacer(self, mm: float = 3): self._add(Spacer(1, mm * MM)) @@ -188,22 +211,22 @@ def box(self, builder: Callable[["PdfDocument"], None]): """Light grey framed block. Rendered as a one-cell table, so it cannot split across pages; a block taller than a page is added unframed instead.""" inner = self._collect(builder) - width, height = self.pagesize box = Table([[inner]], colWidths=[self.usable_width]) - if box.wrap(self.usable_width, height)[1] > height - self.margin - self.bottom - 4 * MM: - self._add(*inner, Spacer(1, 2 * MM)) - return - box.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#f3f3f3")), - ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#aaaaaa")), + box.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), colors.HexColor(self.theme.box_fill)), + ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor(self.theme.box_border)), ("LEFTPADDING", (0, 0), (-1, -1), 8), ("RIGHTPADDING", (0, 0), (-1, -1), 8), ("TOPPADDING", (0, 0), (-1, -1), 6), ("BOTTOMPADDING", (0, 0), (-1, -1), 4)])) + # measured with its own padding: a one-cell table cannot split across pages + if box.wrap(self.usable_width, self.pagesize[1])[1] > self.usable_height: + self._add(*inner, Spacer(1, 2 * MM)) + return self._add(box, Spacer(1, 2 * MM)) def render(self) -> bytes: buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=self.pagesize, leftMargin=self.margin, rightMargin=self.margin, - topMargin=self.margin, bottomMargin=self.bottom, title=safe_text(self.title), - author=safe_text(self.author), pageCompression=1 if self.compress else 0) + topMargin=self.margin, bottomMargin=self.bottom, title=self.theme.safe(self.title), + author=self.theme.safe(self.author), pageCompression=1 if self.compress else 0) doc.build(list(self._story), - canvasmaker=_numbered_canvas(self.footer_left, str(self.page_label), self.margin)) + canvasmaker=_numbered_canvas(self.footer_left, str(self.page_label), self.margin, self.theme)) return buffer.getvalue() diff --git a/packages/django/basicbar-pdf/basicbar_pdf/html.py b/packages/django/basicbar-pdf/basicbar_pdf/html.py index 068501a..e778aff 100644 --- a/packages/django/basicbar-pdf/basicbar_pdf/html.py +++ b/packages/django/basicbar-pdf/basicbar_pdf/html.py @@ -9,9 +9,8 @@ from reportlab.lib import colors from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet -from reportlab.platypus import Paragraph -from .fonts import FONT, FONT_BOLD, safe_text +from .theme import DEFAULT_THEME, PdfTheme INLINE_TAGS = {"strong": "b", "b": "b", "em": "i", "i": "i", "u": "u", "s": "strike", "del": "strike", "strike": "strike"} @@ -20,28 +19,33 @@ TABLE_TAGS = {"table", "thead", "tbody", "tfoot", "tr"} -def _markup(text: str) -> str: - return escape(safe_text(text)).replace("\n", "
") +def _markup(text: str, theme: PdfTheme = DEFAULT_THEME) -> str: + return escape(theme.safe(text)).replace("\n", "
") -def make_styles() -> dict: - """Paragraph styles in the bundled font: normal, small, bold, muted, h1-h3, quote, cell, cell_head.""" +def make_styles(theme: PdfTheme | None = None) -> dict: + """Paragraph styles in the theme's font and colours (default: the bundled font): normal, small, + bold, muted, h1-h3, quote, cell, cell_head.""" + theme = theme or DEFAULT_THEME + regular, bold = theme.fonts.normal, theme.fonts.bold + heading = colors.HexColor(theme.heading or theme.text) base = getSampleStyleSheet()["Normal"] - normal = ParagraphStyle("n", parent=base, fontName=FONT, fontSize=10, leading=13.5, spaceAfter=3) + normal = ParagraphStyle("n", parent=base, fontName=regular, fontSize=10, leading=13.5, spaceAfter=3, + textColor=colors.HexColor(theme.text)) styles = { "normal": normal, "small": ParagraphStyle("s", parent=normal, fontSize=8.5, leading=11), - "bold": ParagraphStyle("b", parent=normal, fontName=FONT_BOLD), - "muted": ParagraphStyle("m", parent=normal, fontSize=8.5, leading=11, textColor=colors.HexColor("#666666")), - "h1": ParagraphStyle("h1", parent=normal, fontName=FONT_BOLD, fontSize=18, leading=22, - spaceBefore=4, spaceAfter=6), - "h2": ParagraphStyle("h2", parent=normal, fontName=FONT_BOLD, fontSize=15, leading=18, - spaceBefore=14, spaceAfter=5), - "h3": ParagraphStyle("h3", parent=normal, fontName=FONT_BOLD, fontSize=12, leading=15, - spaceBefore=8, spaceAfter=2), - "quote": ParagraphStyle("q", parent=normal, leftIndent=10, textColor=colors.HexColor("#444444")), + "bold": ParagraphStyle("b", parent=normal, fontName=bold), + "muted": ParagraphStyle("m", parent=normal, fontSize=8.5, leading=11, textColor=colors.HexColor(theme.muted)), + "h1": ParagraphStyle("h1", parent=normal, fontName=bold, fontSize=18, leading=22, + spaceBefore=4, spaceAfter=6, textColor=heading), + "h2": ParagraphStyle("h2", parent=normal, fontName=bold, fontSize=15, leading=18, + spaceBefore=14, spaceAfter=5, textColor=heading), + "h3": ParagraphStyle("h3", parent=normal, fontName=bold, fontSize=12, leading=15, + spaceBefore=8, spaceAfter=2, textColor=heading), + "quote": ParagraphStyle("q", parent=normal, leftIndent=10, textColor=colors.HexColor(theme.quote)), "cell": ParagraphStyle("c", parent=normal, fontSize=9, leading=11.5, spaceAfter=0), - "cell_head": ParagraphStyle("ch", parent=normal, fontName=FONT_BOLD, fontSize=9, leading=11.5, + "cell_head": ParagraphStyle("ch", parent=normal, fontName=bold, fontSize=9, leading=11.5, spaceAfter=0), } return styles @@ -59,10 +63,11 @@ class _HtmlToFlowables(HTMLParser): """Editor HTML (p, br, inline formatting, lists, headings, blockquote) to Paragraphs. Unknown tags are dropped, their text kept; the markup passed to reportlab is always balanced.""" - def __init__(self, styles, image_placeholder): + def __init__(self, styles, image_placeholder, theme: PdfTheme): super().__init__(convert_charrefs=True) self.image_placeholder = image_placeholder - own = make_styles() + self.theme = theme + own = make_styles(theme) # accept any mapping/stylesheet; keys it lacks fall back to the built-in styles self.styles = {key: (styles[key] if _has(styles, key) else own[key]) for key in own} self.out = [] @@ -93,10 +98,10 @@ def _paragraph(self, markup): if self.bullet is not None: style = ParagraphStyle("li", parent=style, leftIndent=12 * depth + 4, bulletIndent=12 * (depth - 1)) try: - return Paragraph(markup, style, bulletText=self.bullet) + return self.theme.paragraph(markup, style, bulletText=self.bullet) except Exception: # never let one broken fragment kill the document plain = re.sub(r"<[^>]*>", "", markup.replace("
", " ")) # already escaped - return Paragraph(plain, style, bulletText=self.bullet) + return self.theme.paragraph(plain, style, bulletText=self.bullet) def handle_starttag(self, tag, attrs): if tag in SKIP_CONTENT: @@ -112,7 +117,7 @@ def handle_starttag(self, tag, attrs): elif tag == "br": self.buf += "
" elif tag == "img": - self.buf += escape(safe_text(self.image_placeholder)) + self.buf += escape(self.theme.safe(self.image_placeholder)) self.has_text = True elif tag in ("td", "th"): if self.cells: @@ -162,7 +167,7 @@ def handle_endtag(self, tag): if self.hrefs: href = self.hrefs.pop() if href: - self.buf += escape(safe_text(f" ({href})")) + self.buf += escape(self.theme.safe(f" ({href})")) elif tag in ("ul", "ol"): self._flush() self.bullet = None @@ -182,13 +187,13 @@ def handle_data(self, data): if self.skip: return if self.pre: - self.buf += _markup(data) + self.buf += _markup(data, self.theme) if data.strip(): self.has_text = True return if not self.open and not self.buf.strip() and not data.strip(): return - self.buf += escape(safe_text(data)) + self.buf += escape(self.theme.safe(data)) if data.strip(): self.has_text = True @@ -198,9 +203,10 @@ def result(self): return self.out -def html_to_flowables(html: str, styles, *, image_placeholder="[Image]") -> list: +def html_to_flowables(html: str, styles, *, image_placeholder="[Image]", theme: PdfTheme | None = None) -> list: """Editor HTML to flowables. ``styles`` is any mapping/stylesheet; keys it lacks fall back to - :func:`make_styles`. ``image_placeholder`` (str or lazy translation) stands in for ````.""" - parser = _HtmlToFlowables(styles, str(image_placeholder)) + :func:`make_styles` (of ``theme``). ``image_placeholder`` (str or lazy translation) stands in + for ````. With a ``theme``, a paragraph the theme font cannot set uses the bundled font.""" + parser = _HtmlToFlowables(styles, str(image_placeholder), theme or DEFAULT_THEME) parser.feed(html or "") return parser.result() diff --git a/packages/django/basicbar-pdf/basicbar_pdf/tests/test_theme.py b/packages/django/basicbar-pdf/basicbar_pdf/tests/test_theme.py new file mode 100644 index 0000000..95e475b --- /dev/null +++ b/packages/django/basicbar-pdf/basicbar_pdf/tests/test_theme.py @@ -0,0 +1,157 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""PdfTheme: own font and colours, per-paragraph fallback to the bundled font, usable_height.""" + +import unittest +from io import BytesIO + +from basicbar_pdf import theme as theme_module + +ASCII = frozenset(range(32, 127)) + + +def ascii_family(): + """A stand-in theme font: the bundled bold and bold italic files registered as "TestSans" + (regular) and "TestSans-Bold", treated as ASCII-only (coverage patched). In a rendered PDF the + theme font shows up as PlusJakartaSans-Bold, the fallback as PlusJakartaSans-Regular.""" + from basicbar_pdf import register_font_family + from basicbar_pdf.fonts import FONT_DIR + family = register_font_family("TestSans", regular=FONT_DIR / "PlusJakartaSans-Bold.ttf", + bold=FONT_DIR / "PlusJakartaSans-BoldItalic.ttf") + for name in family.names(): + theme_module._coverage[name] = ASCII + return family + + +def fonts_in(data: bytes) -> set[str]: + from pypdf import PdfReader + names = set() + for page in PdfReader(BytesIO(data)).pages: + for font in page["/Resources"]["/Font"].values(): + names.add(str(font.get_object()["/BaseFont"]).split("+")[-1]) + return names + + +def texts(data: bytes) -> str: + from pypdf import PdfReader + return "\n".join(page.extract_text() for page in PdfReader(BytesIO(data)).pages) + + +class FontFamilyTests(unittest.TestCase): + + def test_missing_cuts_fall_back_to_the_nearest(self): + family = ascii_family() + self.assertEqual(family.bold, "TestSans-Bold") + self.assertEqual(family.italic, "TestSans") + self.assertEqual(family.bold_italic, "TestSans-Bold") + + def test_registering_again_is_harmless(self): + self.assertEqual(ascii_family(), ascii_family()) + + +class ThemeStyleTests(unittest.TestCase): + + def test_default_theme_keeps_the_frame_look(self): + from reportlab.lib import colors + + from basicbar_pdf import FONT, FONT_BOLD, make_styles + styles = make_styles() + self.assertEqual(styles["normal"].fontName, FONT) + self.assertEqual(styles["h1"].fontName, FONT_BOLD) + self.assertEqual(styles["normal"].textColor.hexval(), colors.black.hexval()) + self.assertEqual(styles["muted"].textColor.hexval(), "0x666666") + + def test_theme_sets_font_and_colours(self): + from basicbar_pdf import PdfDocument, PdfTheme + family = ascii_family() + theme = PdfTheme(fonts=family, text="#3e3e3f", heading="#ad1034", muted="#707070") + doc = PdfDocument("t", theme=theme) + self.assertEqual(doc.styles["normal"].fontName, "TestSans") + self.assertEqual(doc.styles["cell_head"].fontName, "TestSans-Bold") + self.assertEqual(doc.styles["normal"].textColor.hexval(), "0x3e3e3f") + self.assertEqual(doc.styles["h2"].textColor.hexval(), "0xad1034") + self.assertEqual(doc.styles["muted"].textColor.hexval(), "0x707070") + + def test_heading_colour_defaults_to_text(self): + from basicbar_pdf import make_styles, PdfTheme + styles = make_styles(PdfTheme(text="#123456")) + self.assertEqual(styles["h3"].textColor.hexval(), "0x123456") + + +class ThemeFallbackTests(unittest.TestCase): + + def setUp(self): + from basicbar_pdf import PdfTheme + self.theme = PdfTheme(fonts=ascii_family()) + + def test_safe_keeps_what_either_font_has(self): + self.assertEqual(self.theme.safe("Grüße αβ 😀"), "Grüße ?? ?") + + def test_paragraph_switches_to_the_bundled_cut_of_the_same_weight(self): + from basicbar_pdf import FONT, FONT_BOLD, PdfDocument + doc = PdfDocument("t", theme=self.theme) + doc.paragraph("Hallo") + doc.paragraph("Grüße") + doc.heading("Überschrift", 2) + doc.paragraph("& tags do not count", style="bold") + fonts = [p.style.fontName for p in doc._story] + self.assertEqual(fonts, ["TestSans", FONT, FONT_BOLD, "TestSans-Bold"]) + + def test_rich_bullets_and_table_cells_fall_back_per_paragraph(self): + from reportlab.platypus import Paragraph, Table + + from basicbar_pdf import FONT, PdfDocument + doc = PdfDocument("t", theme=self.theme) + doc.rich("

plain

Şahin

") + doc.bullets(["eins", "zwei → drei"]) + doc.table([["Kopf"], ["Wert ü"]]) + paras = [f for f in doc._story if isinstance(f, Paragraph)] + self.assertEqual([p.style.fontName for p in paras], + ["TestSans", FONT, "TestSans", FONT, "TestSans", FONT]) + table = next(f for f in doc._story if isinstance(f, Table)) + self.assertEqual(table._cellvalues[0][0].style.fontName, "TestSans-Bold") + self.assertEqual(table._cellvalues[1][0].style.fontName, FONT) + + def test_render_embeds_theme_font_and_fallback_only_where_needed(self): + from basicbar_pdf import PdfDocument + doc = PdfDocument("t", theme=self.theme, footer_left="Fusszeile") + doc.paragraph("Nur ASCII") + data = doc.render() + self.assertIn("PlusJakartaSans-Bold", fonts_in(data)) + self.assertNotIn("PlusJakartaSans-Regular", fonts_in(data)) # the footer is in the theme font too + + doc = PdfDocument("t", theme=self.theme, footer_left="Fußzeile") + doc.paragraph("Şahin → Łódź") + data = doc.render() + self.assertIn("PlusJakartaSans-Regular", fonts_in(data)) + self.assertIn("Şahin → Łódź", texts(data)) + self.assertIn("Fußzeile", texts(data)) + + def test_auto_widths_measure_in_the_font_that_sets_the_cell(self): + from reportlab.pdfbase.pdfmetrics import stringWidth + + from basicbar_pdf import FONT_BOLD, PdfDocument + doc = PdfDocument("t", theme=self.theme) + widths = doc.auto_widths([["Größe", "x"]]) + self.assertGreaterEqual(widths[0], stringWidth("Größe", FONT_BOLD, 9)) + + +class UsableHeightTests(unittest.TestCase): + + def test_usable_height_is_the_frame_less_its_padding(self): + from reportlab.lib.pagesizes import A4 + + from basicbar_pdf import PdfDocument + doc = PdfDocument("t") + self.assertAlmostEqual(doc.usable_height, A4[1] - doc.margin - doc.bottom - 12, places=3) + + def test_box_just_taller_than_the_frame_still_renders(self): + from reportlab.platypus import Spacer + + from basicbar_pdf import PdfDocument + doc = PdfDocument("t") + # the box table adds 10 pt of padding: inner + 10 lands 0.3 pt above the usable height, + # where the old check (measured without that padding) still framed it and the render failed + doc.box(lambda d: d.add(Spacer(1, doc.usable_height - 9.7))) + self.assertTrue(doc.render().startswith(b"%PDF")) diff --git a/packages/django/basicbar-pdf/basicbar_pdf/theme.py b/packages/django/basicbar-pdf/basicbar_pdf/theme.py new file mode 100644 index 0000000..341adc2 --- /dev/null +++ b/packages/django/basicbar-pdf/basicbar_pdf/theme.py @@ -0,0 +1,140 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""``PdfTheme``: a tool's own font and colours for the frame, with the bundled font as fallback. + +A paragraph whose text has characters the theme font lacks (but the bundled Plus Jakarta Sans has) +is set in the bundled font, in the same weight; only what neither font has becomes "?". +""" + +import re +from dataclasses import dataclass, field +from html import unescape +from pathlib import Path + +from reportlab.lib.styles import ParagraphStyle +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.ttfonts import TTFont +from reportlab.platypus import Paragraph + +from .fonts import FONT, FONT_BOLD + +_TAG = re.compile(r"<[^>]*>") +_coverage: dict[str, frozenset[int]] = {} + + +def covered(font_name: str) -> frozenset[int]: + """Code points a registered TrueType font has (cached per font name).""" + if font_name not in _coverage: + _coverage[font_name] = frozenset(pdfmetrics.getFont(font_name).face.charToGlyph) + return _coverage[font_name] + + +@dataclass(frozen=True) +class FontFamily: + """The four registered reportlab font names of one family.""" + + normal: str + bold: str + italic: str + bold_italic: str + + def names(self) -> tuple[str, str, str, str]: + return (self.normal, self.bold, self.italic, self.bold_italic) + + +BUNDLED_FAMILY = FontFamily(FONT, FONT_BOLD, FONT + "-Italic", FONT + "-BoldItalic") + + +def register_font_family(name: str, *, regular: str | Path, bold: str | Path | None = None, + italic: str | Path | None = None, + bold_italic: str | Path | None = None) -> FontFamily: + """Register TrueType files as one family (````/```` in markup pick the right cut) and + return its names for :class:`PdfTheme`. A missing cut falls back to the nearest one: italic to + regular, bold italic to bold (or italic). Calling it again with the same name is a no-op.""" + files = {name: regular, f"{name}-Bold": bold, f"{name}-Italic": italic, f"{name}-BoldItalic": bold_italic} + known = set(pdfmetrics.getRegisteredFontNames()) + for font_name, path in files.items(): + if path is not None and font_name not in known: + pdfmetrics.registerFont(TTFont(font_name, str(path))) + normal = name + bold_name = f"{name}-Bold" if bold is not None else normal + italic_name = f"{name}-Italic" if italic is not None else normal + bold_italic_name = (f"{name}-BoldItalic" if bold_italic is not None + else bold_name if bold is not None else italic_name) + pdfmetrics.registerFontFamily(name, normal=normal, bold=bold_name, italic=italic_name, + boldItalic=bold_italic_name) + return FontFamily(normal, bold_name, italic_name, bold_italic_name) + + +@dataclass(frozen=True) +class PdfTheme: + """Font and colours of a :class:`~basicbar_pdf.PdfDocument`. The defaults are the frame's + own look; colours are hex strings. ``heading`` None means the text colour.""" + + fonts: FontFamily = BUNDLED_FAMILY + text: str = "#000000" + muted: str = "#666666" + heading: str | None = None + quote: str = "#444444" + grid: str = "#c8c8c8" + table_head: str = "#eeeeee" + box_fill: str = "#f3f3f3" + box_border: str = "#aaaaaa" + footer: str = "#555555" + _fallback_styles: dict = field(default_factory=dict, init=False, repr=False, compare=False, hash=False) + + @property + def own_font(self) -> bool: + """Whether the theme sets a font other than the bundled one.""" + return self.fonts != BUNDLED_FAMILY + + def safe(self, text) -> str: + """Characters neither the theme font nor the bundled font has become "?".""" + known = covered(self.fonts.normal) | covered(FONT) if self.own_font else covered(FONT) + return "".join(c if c.isspace() or ord(c) in known else "?" for c in str(text)) + + def lacks(self, markup: str) -> bool: + """Whether the visible text of ``markup`` has characters the theme font lacks.""" + if not self.own_font: + return False + own = covered(self.fonts.normal) + return any(not c.isspace() and ord(c) not in own for c in unescape(_TAG.sub("", markup))) + + def font_for(self, font_name: str, text: str) -> str: + """``font_name`` (a cut of the theme family), or the bundled cut of the same weight when + ``text`` (plain) has characters the theme font lacks.""" + if not self.own_font or not any(not c.isspace() and ord(c) not in covered(self.fonts.normal) + for c in text): + return font_name + return _BUNDLED_BY_CUT.get(self._cut(font_name), FONT) + + def _cut(self, font_name: str) -> str: + fonts = self.fonts + # upright first: a family without italics maps italic to the upright name + for cut, name in (("normal", fonts.normal), ("bold", fonts.bold), + ("italic", fonts.italic), ("bold_italic", fonts.bold_italic)): + if font_name == name: + return cut + return "normal" + + def fallback_style(self, style: ParagraphStyle) -> ParagraphStyle: + """``style`` set in the bundled font of the same weight (cached per style).""" + key = id(style) + cached = self._fallback_styles.get(key) + if cached is not None and cached[0] is style: + return cached[1] + derived = ParagraphStyle(f"{style.name}-fallback", parent=style, + fontName=_BUNDLED_BY_CUT.get(self._cut(style.fontName), FONT)) + self._fallback_styles[key] = (style, derived) + return derived + + def paragraph(self, markup: str, style: ParagraphStyle, **kwargs) -> Paragraph: + """A Paragraph of (already escaped) ``markup``, in the bundled font when the theme font + lacks a character of it.""" + return Paragraph(markup, self.fallback_style(style) if self.lacks(markup) else style, **kwargs) + + +_BUNDLED_BY_CUT = dict(zip(("normal", "bold", "italic", "bold_italic"), BUNDLED_FAMILY.names())) + +DEFAULT_THEME = PdfTheme() diff --git a/packages/django/basicbar-pdf/pyproject.toml b/packages/django/basicbar-pdf/pyproject.toml index ff0848c..89a4f95 100644 --- a/packages/django/basicbar-pdf/pyproject.toml +++ b/packages/django/basicbar-pdf/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "basicbar-pdf" -version = "0.1.0" -description = "PDF-Rahmen der virtUOS -bar-Tools: reportlab-Dokument mit mitgelieferter Schrift, Fußzeile, Editor-HTML" +version = "0.2.0" +description = "PDF-Rahmen der virtUOS -bar-Tools: reportlab-Dokument mit mitgelieferter Schrift, Theme, Fußzeile, Editor-HTML" readme = "README.md" requires-python = ">=3.12" license = { text = "Apache-2.0" }