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