Files
surveybox/surveybox/forms/participant_pdf.py
T
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

249 lines
9.3 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Teilnehmerlisten als PDF zum Ausdrucken (reportlab).
A4 hoch, Ränder wie beim XLSX-Export (oben 2 cm, unten 1,2 cm, links und rechts 1 cm).
Jede Seite trägt oben Logo und Titel, unten "Seite X von Y". Je Eintrag eines
Teilnahme-Feldes eine Tabelle mit Nummer und Name, auf Wunsch mit Spalte für
Unterschriften; freie Plätze erscheinen als leere Zeilen, die Warteliste darunter.
Schrift ist Bitstream Vera aus dem reportlab-Paket (eingebettet, als Teilmenge).
Zeichen, die sie nicht kennt, werden auf den Grundbuchstaben zurückgeführt (ř → r),
statt als Kästchen zu erscheinen. Texte der Benutzer werden für den Absatz-Parser von
reportlab maskiert; Markup aus Antworten wird nie ausgewertet.
"""
from __future__ import annotations
import io
import unicodedata
from collections.abc import Sequence
from dataclasses import dataclass, field
from functools import cache
from pathlib import Path
from typing import Any
from xml.sax.saxutils import escape
from surveybox.i18n import gettext
DASH = "\N{EN DASH}"
MAX_FREE_ROWS = 100 # mehr leere Zeilen für freie Plätze druckt niemand aus
@dataclass
class Entry:
title: str
capacity: int | None
confirmed: list[str] = field(default_factory=list)
waiting: list[str] = field(default_factory=list)
@dataclass
class Section:
title: str
entries: list[Entry]
@dataclass
class Options:
signature: bool = False
page_per_entry: bool = False
FONT = "SurveyboxSans"
FONT_BOLD = "SurveyboxSans-Bold"
def available() -> bool:
"""reportlab installiert? (Nach dem Update einmal scripts/lock.sh ausführen.)"""
import importlib.util
return importlib.util.find_spec("reportlab") is not None
@cache
def _fonts() -> frozenset[int]:
"""Schrift einmal registrieren; liefert die Zeichen, die sie darstellen kann."""
import reportlab
from reportlab.lib.fonts import addMapping
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
folder = Path(reportlab.__file__).parent / "fonts"
regular = TTFont(FONT, str(folder / "Vera.ttf"))
pdfmetrics.registerFont(regular)
pdfmetrics.registerFont(TTFont(FONT_BOLD, str(folder / "VeraBd.ttf")))
addMapping(FONT, 0, 0, FONT)
addMapping(FONT, 1, 0, FONT_BOLD)
return frozenset(regular.face.charToGlyph)
def printable(text: str) -> str:
"""Text so, dass die Schrift jedes Zeichen kennt (sonst Grundbuchstabe oder '?')."""
known = _fonts()
out = []
for ch in text:
if ch in "\r\n\t":
out.append(" ")
elif ord(ch) in known:
out.append(ch)
elif unicodedata.category(ch).startswith("C"):
continue
else:
base = "".join(c for c in unicodedata.normalize("NFKD", ch)
if ord(c) in known and not unicodedata.combining(c))
out.append(base or "?")
return "".join(out)
def _para(text: str, style: Any) -> Any:
from reportlab.platypus import Paragraph
return Paragraph(escape(printable(text)), style)
def build(form_title: str, sections: Sequence[Section], info: Sequence[tuple[str, str]],
logo: bytes | None, options: Options) -> bytes:
_fonts()
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import cm
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas as pdfcanvas
from reportlab.platypus import (
CondPageBreak,
PageBreak,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
base = ParagraphStyle("base", fontName=FONT, fontSize=10, leading=13)
small = ParagraphStyle("small", parent=base, fontSize=8.5, leading=11,
textColor=colors.HexColor("#555555"))
h1 = ParagraphStyle("h1", parent=base, fontName=FONT_BOLD, fontSize=15, leading=19,
spaceAfter=4)
h2 = ParagraphStyle("h2", parent=base, fontName=FONT_BOLD, fontSize=12.5, leading=16,
spaceBefore=10, spaceAfter=4, keepWithNext=1)
h3 = ParagraphStyle("h3", parent=base, fontName=FONT_BOLD, fontSize=11, leading=14,
spaceBefore=8, spaceAfter=3)
head = ParagraphStyle("head", parent=base, fontName=FONT_BOLD)
width, height = A4
left = right = 1 * cm
top, bottom = 2 * cm, 1.2 * cm
usable = width - left - right
logo_reader = ImageReader(io.BytesIO(logo)) if logo else None
title = printable(form_title)
def decorate(canvas: Any, page: int, pages: int) -> None:
canvas.saveState()
x = left
if logo_reader is not None:
iw, ih = logo_reader.getSize()
h = 1.0 * cm
w = iw * h / ih if ih else h
canvas.drawImage(logo_reader, x, height - top + 0.5 * cm, w, h, mask="auto")
x += w + 0.3 * cm
canvas.setFont(FONT, 9)
canvas.setFillColor(colors.HexColor("#555555"))
canvas.drawString(x, height - top + 0.85 * cm, title[:110])
canvas.drawCentredString(width / 2, bottom / 2,
gettext("Page %(page)s of %(pages)s")
% {"page": page, "pages": pages})
canvas.restoreState()
class NumberedCanvas(pdfcanvas.Canvas): # type: ignore[misc]
"""Merkt sich die Seiten, um am Ende "Seite X von Y" zu schreiben."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._pages: list[dict[str, Any]] = []
def showPage(self) -> None:
self._pages.append(dict(self.__dict__))
self._startPage()
def save(self) -> None:
total = len(self._pages)
for number, state in enumerate(self._pages, 1):
self.__dict__.update(state)
decorate(self, number, total)
super().showPage()
super().save()
number_w = 1.2 * cm
if options.signature:
name_w = (usable - number_w) * 0.55
widths = [number_w, name_w, usable - number_w - name_w]
header = [gettext("No."), gettext("Name"), gettext("Signature")]
else:
widths = [number_w, usable - number_w]
header = [gettext("No."), gettext("Name")]
style = TableStyle([
("FONT", (0, 0), (-1, -1), FONT, 10),
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#CCCCCC")),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#888888")),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ALIGN", (0, 0), (0, -1), "RIGHT"),
("TOPPADDING", (0, 1), (-1, -1), 5 if options.signature else 3),
("BOTTOMPADDING", (0, 1), (-1, -1), 5 if options.signature else 3),
])
def table(names: Sequence[str], free: int) -> Any:
rows: list[list[Any]] = [[_para(h, head) for h in header]]
for number, name in enumerate(names, 1):
rows.append([str(number), _para(name, base)] + ([""] if options.signature else []))
for number in range(len(names) + 1, len(names) + free + 1):
rows.append([str(number), ""] + ([""] if options.signature else []))
result = Table(rows, colWidths=widths, repeatRows=1)
result.setStyle(style)
return result
story: list[Any] = [_para(form_title, h1)]
story += [_para(f"{label}: {value}", small) for label, value in info]
first = True
for section in sections:
if section.title:
story.append(_para(section.title, h2))
for entry in section.entries:
if options.page_per_entry and not first:
story.append(PageBreak())
if section.title:
story.append(_para(section.title, small))
first = False
story.append(CondPageBreak(3.5 * cm)) # Überschrift nicht allein am Seitenende
if entry.title:
count = len(entry.confirmed)
taken = (gettext("%(taken)s of %(places)s places taken")
% {"taken": count, "places": entry.capacity}
if entry.capacity else
gettext("%(taken)s signed up") % {"taken": count})
story.append(_para(f"{entry.title} {DASH} {taken}", h3))
else:
story.append(Spacer(1, 6))
free = 0
if entry.capacity:
free = min(max(entry.capacity - len(entry.confirmed), 0), MAX_FREE_ROWS)
if entry.confirmed or free:
story.append(table(entry.confirmed, free))
else:
story.append(_para(gettext("Nobody has signed up yet."), small))
if entry.waiting:
story.append(CondPageBreak(3 * cm))
story.append(Spacer(1, 6))
story.append(_para(gettext("Waiting list"), head))
story.append(Spacer(1, 2))
story.append(table(entry.waiting, 0))
story.append(Spacer(1, 8))
buffer = io.BytesIO()
doc = SimpleDocTemplate(
buffer, pagesize=A4, leftMargin=left, rightMargin=right, topMargin=top,
bottomMargin=bottom, title=title, author="Surveybox", creator="Surveybox",
subject=gettext("Participant lists"),
)
doc.build(story, canvasmaker=NumberedCanvas)
return buffer.getvalue()