Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 41 additions & 5 deletions packages/django/basicbar-pdf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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 |
|---|---|
Expand All @@ -51,15 +52,50 @@ 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 |
| `add(*flowables)` | eigene reportlab-Flowables |
| `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

Expand Down
7 changes: 5 additions & 2 deletions packages/django/basicbar-pdf/basicbar_pdf/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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"]
87 changes: 55 additions & 32 deletions packages/django/basicbar-pdf/basicbar_pdf/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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()

Expand All @@ -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
Expand All @@ -73,14 +82,24 @@ 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
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)

Expand All @@ -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 []
Expand Down Expand Up @@ -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))
Expand All @@ -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()
Loading