346 lines
13 KiB
Python
346 lines
13 KiB
Python
|
|
#!/usr/bin/env python3
|
|||
|
|
"""
|
|||
|
|
Baut den verdeckten SL-Schirm (A5 quer) aus einer Markdown-Datenquelle.
|
|||
|
|
|
|||
|
|
Trennung von Inhalt und Layout: Der Inhalt steht in einer editierbaren
|
|||
|
|
Markdown-Datei (Standard: RPG/7-Prep/<prep>/SL Schirm/SL-Schirm Inhalt.md),
|
|||
|
|
dieses Skript rendert daraus ein druckfertiges PDF. Für die nächste Prep-Session
|
|||
|
|
wird nur die Markdown-Datei kopiert/aktualisiert und neu gebaut.
|
|||
|
|
|
|||
|
|
Quellformat
|
|||
|
|
-----------
|
|||
|
|
---
|
|||
|
|
titel: SL-Schirm
|
|||
|
|
untertitel: … (optional, erscheint klein unter dem Titel)
|
|||
|
|
ingame: 1. Dezember (optional, steht im Kopf jeder Seite)
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## Karte 1 · Fraktionen & Absichten
|
|||
|
|
farbe: rot (optional: rot | blau | gruen | schwarz | grau)
|
|||
|
|
### Unterabschnitt (optional, Zwischenüberschrift)
|
|||
|
|
| Kopf | Kopf | (Pipe-Tabelle, erste Zeile = Kopfzeile)
|
|||
|
|
| --- | --- |
|
|||
|
|
| … | … |
|
|||
|
|
- Stichpunkt
|
|||
|
|
> Hinweis (klein, grau)
|
|||
|
|
Fließtext
|
|||
|
|
|
|||
|
|
Jede `##`-Karte beginnt auf einer neuen Seite.
|
|||
|
|
|
|||
|
|
Aufruf:
|
|||
|
|
.venv/bin/python tools/build_sl_schirm.py # Standardquelle + Standardziel
|
|||
|
|
.venv/bin/python tools/build_sl_schirm.py -s quelle.md -o ziel.pdf
|
|||
|
|
"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import argparse
|
|||
|
|
import re
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from reportlab.lib import colors
|
|||
|
|
from reportlab.lib.pagesizes import A5, landscape
|
|||
|
|
from reportlab.lib.styles import ParagraphStyle
|
|||
|
|
from reportlab.lib.units import mm
|
|||
|
|
from reportlab.pdfbase import pdfmetrics
|
|||
|
|
from reportlab.pdfbase.ttfonts import TTFont
|
|||
|
|
from reportlab.platypus import (BaseDocTemplate, Frame, PageBreak, PageTemplate,
|
|||
|
|
Paragraph, Spacer, Table, TableStyle)
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|||
|
|
VAULT = ROOT / "RPG"
|
|||
|
|
# Prep-Material liegt pro Prep-Session in einem eigenen Unterordner
|
|||
|
|
PREP = VAULT / "7-Prep" / "prep_2026-11-20"
|
|||
|
|
QUELLE = PREP / "SL Schirm" / "SL-Schirm Inhalt.md"
|
|||
|
|
ZIEL = PREP / "SL Schirm" / "SL-Schirm (A5 quer).pdf"
|
|||
|
|
|
|||
|
|
FONT_DIR = Path("/usr/share/fonts/truetype/dejavu")
|
|||
|
|
pdfmetrics.registerFont(TTFont("Serif", str(FONT_DIR / "DejaVuSerif.ttf")))
|
|||
|
|
pdfmetrics.registerFont(TTFont("Serif-Bold", str(FONT_DIR / "DejaVuSerif-Bold.ttf")))
|
|||
|
|
pdfmetrics.registerFont(TTFont("Sans", str(FONT_DIR / "DejaVuSans.ttf")))
|
|||
|
|
pdfmetrics.registerFont(TTFont("Sans-Bold", str(FONT_DIR / "DejaVuSans-Bold.ttf")))
|
|||
|
|
pdfmetrics.registerFontFamily("Serif", normal="Serif", bold="Serif-Bold",
|
|||
|
|
italic="Serif", boldItalic="Serif-Bold")
|
|||
|
|
pdfmetrics.registerFontFamily("Sans", normal="Sans", bold="Sans-Bold",
|
|||
|
|
italic="Sans", boldItalic="Sans-Bold")
|
|||
|
|
|
|||
|
|
INK = colors.HexColor("#2b2118")
|
|||
|
|
GREY = colors.HexColor("#6b6259")
|
|||
|
|
RULE = colors.HexColor("#b9a893")
|
|||
|
|
ACCENT = colors.HexColor("#7a2e1e")
|
|||
|
|
|
|||
|
|
# Farbcode je Karte – am Tisch soll ein Griff genügen
|
|||
|
|
FARBEN = {
|
|||
|
|
"rot": colors.HexColor("#7a2e1e"),
|
|||
|
|
"blau": colors.HexColor("#1f4e6b"),
|
|||
|
|
"gruen": colors.HexColor("#3d5a2e"),
|
|||
|
|
"schwarz": colors.HexColor("#2b2118"),
|
|||
|
|
"grau": colors.HexColor("#5c5349"),
|
|||
|
|
"gold": colors.HexColor("#8a6a1f"),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
PAGE_W, PAGE_H = landscape(A5) # 210 × 148 mm
|
|||
|
|
MARGIN_X = 9 * mm
|
|||
|
|
MARGIN_TOP = 9 * mm
|
|||
|
|
MARGIN_BOT = 8 * mm
|
|||
|
|
|
|||
|
|
S = {
|
|||
|
|
"karte": ParagraphStyle("karte", fontName="Serif-Bold", fontSize=13.5, leading=16.5,
|
|||
|
|
textColor=colors.white),
|
|||
|
|
"karte_sub": ParagraphStyle("karte_sub", fontName="Sans", fontSize=7.4, leading=9.4,
|
|||
|
|
textColor=colors.white),
|
|||
|
|
"h2": ParagraphStyle("h2", fontName="Serif-Bold", fontSize=9.6, leading=12.4,
|
|||
|
|
textColor=ACCENT, spaceBefore=4, spaceAfter=2, keepWithNext=1),
|
|||
|
|
"body": ParagraphStyle("body", fontName="Serif", fontSize=8.2, leading=10.9,
|
|||
|
|
textColor=INK, spaceAfter=2),
|
|||
|
|
"bullet": ParagraphStyle("bullet", fontName="Serif", fontSize=8.2, leading=10.9,
|
|||
|
|
textColor=INK, leftIndent=8, bulletIndent=1, spaceAfter=1.4),
|
|||
|
|
"note": ParagraphStyle("note", fontName="Sans", fontSize=7.2, leading=9.6,
|
|||
|
|
textColor=GREY, spaceAfter=2),
|
|||
|
|
"cell": ParagraphStyle("cell", fontName="Serif", fontSize=7.4, leading=9.0, textColor=INK),
|
|||
|
|
"cell_b": ParagraphStyle("cell_b", fontName="Serif-Bold", fontSize=7.4, leading=9.0,
|
|||
|
|
textColor=INK),
|
|||
|
|
"cell_h": ParagraphStyle("cell_h", fontName="Sans-Bold", fontSize=7.4, leading=9.0,
|
|||
|
|
textColor=colors.white),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ------------------------------------------------------------------ Markdown
|
|||
|
|
def clean(text: str) -> str:
|
|||
|
|
t = text.strip()
|
|||
|
|
t = t.replace("&", "&").replace("<", "<").replace(">", ">")
|
|||
|
|
t = re.sub(r"\[\[([^\]|]+)\|([^\]]+)\]\]", r"\2", t)
|
|||
|
|
t = re.sub(r"\[\[([^\]]+)\]\]", r"\1", t)
|
|||
|
|
t = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", t)
|
|||
|
|
t = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<i>\1</i>", t)
|
|||
|
|
t = t.replace("--", "–")
|
|||
|
|
return t
|
|||
|
|
|
|||
|
|
|
|||
|
|
def parse_frontmatter(text: str) -> tuple[dict[str, str], str]:
|
|||
|
|
if not text.startswith("---"):
|
|||
|
|
return {}, text
|
|||
|
|
parts = text.split("---", 2)
|
|||
|
|
if len(parts) < 3:
|
|||
|
|
return {}, text
|
|||
|
|
meta: dict[str, str] = {}
|
|||
|
|
for line in parts[1].splitlines():
|
|||
|
|
if ":" in line:
|
|||
|
|
k, v = line.split(":", 1)
|
|||
|
|
meta[k.strip()] = v.strip()
|
|||
|
|
return meta, parts[2]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def parse_cards(text: str) -> list[dict]:
|
|||
|
|
cards: list[dict] = []
|
|||
|
|
akt: dict | None = None
|
|||
|
|
for raw in text.splitlines():
|
|||
|
|
line = raw.rstrip()
|
|||
|
|
if line.startswith("## "):
|
|||
|
|
akt = {"titel": line[3:].strip(), "farbe": "rot", "zeilen": []}
|
|||
|
|
cards.append(akt)
|
|||
|
|
continue
|
|||
|
|
if akt is None:
|
|||
|
|
continue
|
|||
|
|
m = re.match(r"farbe:\s*(\w+)", line.strip(), re.I)
|
|||
|
|
if m and not akt["zeilen"]:
|
|||
|
|
akt["farbe"] = m.group(1).lower()
|
|||
|
|
continue
|
|||
|
|
akt["zeilen"].append(line)
|
|||
|
|
return cards
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ------------------------------------------------------------------ Flowables
|
|||
|
|
def is_table_row(line: str) -> bool:
|
|||
|
|
return line.strip().startswith("|")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def split_row(line: str) -> list[str]:
|
|||
|
|
return [c.strip() for c in line.strip().strip("|").split("|")]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def nice_weights(rows: list[list[str]]) -> list[float]:
|
|||
|
|
"""Spaltenbreiten grob nach Inhalt (Kopfzeile + mittlere Zelllänge)."""
|
|||
|
|
cols = max(len(r) for r in rows)
|
|||
|
|
raw: list[float] = []
|
|||
|
|
for c in range(cols):
|
|||
|
|
lens = [len(r[c]) for r in rows[1:] if c < len(r) and r[c]]
|
|||
|
|
kopf = len(rows[0][c]) if c < len(rows[0]) else 6
|
|||
|
|
mittel = sum(lens) / len(lens) if lens else kopf
|
|||
|
|
raw.append(max(kopf * 1.1, mittel) ** 0.72)
|
|||
|
|
lo = min(raw)
|
|||
|
|
return [max(w / lo, 1.0) for w in raw]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def make_table(rows: list[list[str]], farbe) -> Table:
|
|||
|
|
cols = max(len(r) for r in rows)
|
|||
|
|
rows = [r + [""] * (cols - len(r)) for r in rows]
|
|||
|
|
breite = PAGE_W - 2 * MARGIN_X
|
|||
|
|
weights = nice_weights(rows)
|
|||
|
|
total = sum(weights)
|
|||
|
|
data = [[Paragraph(clean(c),
|
|||
|
|
S["cell_h"] if i == 0 else S["cell_b" if j == 0 else "cell"])
|
|||
|
|
for j, c in enumerate(row)] for i, row in enumerate(rows)]
|
|||
|
|
t = Table(data, colWidths=[breite * w / total for w in weights],
|
|||
|
|
repeatRows=1, hAlign="LEFT")
|
|||
|
|
t.setStyle(TableStyle([
|
|||
|
|
("BACKGROUND", (0, 0), (-1, 0), farbe),
|
|||
|
|
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
|||
|
|
("GRID", (0, 0), (-1, -1), 0.4, RULE),
|
|||
|
|
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f6f1ea")]),
|
|||
|
|
("LEFTPADDING", (0, 0), (-1, -1), 3),
|
|||
|
|
("RIGHTPADDING", (0, 0), (-1, -1), 3),
|
|||
|
|
("TOPPADDING", (0, 0), (-1, -1), 1.6),
|
|||
|
|
("BOTTOMPADDING", (0, 0), (-1, -1), 1.6),
|
|||
|
|
]))
|
|||
|
|
return t
|
|||
|
|
|
|||
|
|
|
|||
|
|
def karte_kopf(titel: str, untertitel: str, farbe) -> Table:
|
|||
|
|
breite = PAGE_W - 2 * MARGIN_X
|
|||
|
|
text = [Paragraph(clean(titel), S["karte"])]
|
|||
|
|
if untertitel:
|
|||
|
|
text.append(Paragraph(clean(untertitel), S["karte_sub"]))
|
|||
|
|
t = Table([[text, Paragraph("SL · vertraulich", S["karte_sub"])]],
|
|||
|
|
colWidths=[breite * 0.82, breite * 0.18], hAlign="LEFT")
|
|||
|
|
t.setStyle(TableStyle([
|
|||
|
|
("BACKGROUND", (0, 0), (-1, -1), farbe),
|
|||
|
|
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
|||
|
|
("ALIGN", (1, 0), (1, 0), "RIGHT"),
|
|||
|
|
("LEFTPADDING", (0, 0), (-1, -1), 5),
|
|||
|
|
("RIGHTPADDING", (0, 0), (-1, -1), 5),
|
|||
|
|
("TOPPADDING", (0, 0), (-1, -1), 3),
|
|||
|
|
("BOTTOMPADDING", (0, 0), (-1, -1), 3),
|
|||
|
|
]))
|
|||
|
|
return t
|
|||
|
|
|
|||
|
|
|
|||
|
|
def card_story(card: dict, untertitel: str) -> list:
|
|||
|
|
farbe = FARBEN.get(card["farbe"], ACCENT)
|
|||
|
|
story: list = [karte_kopf(card["titel"], untertitel, farbe), Spacer(1, 2.2 * mm)]
|
|||
|
|
|
|||
|
|
zeilen = card["zeilen"]
|
|||
|
|
i = 0
|
|||
|
|
while i < len(zeilen):
|
|||
|
|
line = zeilen[i]
|
|||
|
|
s = line.strip()
|
|||
|
|
|
|||
|
|
if not s:
|
|||
|
|
i += 1
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
if s.startswith("|"):
|
|||
|
|
block = []
|
|||
|
|
while i < len(zeilen) and is_table_row(zeilen[i]):
|
|||
|
|
cells = split_row(zeilen[i])
|
|||
|
|
if not all(re.fullmatch(r":?-{2,}:?", c) for c in cells if c):
|
|||
|
|
block.append(cells)
|
|||
|
|
i += 1
|
|||
|
|
if block:
|
|||
|
|
story += [make_table(block, farbe), Spacer(1, 2 * mm)]
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
if s.startswith("### "):
|
|||
|
|
story.append(Paragraph(clean(s[4:]), S["h2"]))
|
|||
|
|
i += 1
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
if s.startswith(">"):
|
|||
|
|
story.append(Paragraph(clean(s.lstrip("> ")), S["note"]))
|
|||
|
|
i += 1
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
if s.startswith(("- ", "* ")):
|
|||
|
|
gruppe = []
|
|||
|
|
while i < len(zeilen) and zeilen[i].strip().startswith(("- ", "* ")):
|
|||
|
|
gruppe.append(Paragraph(clean(zeilen[i].strip()[2:]),
|
|||
|
|
S["bullet"], bulletText="•"))
|
|||
|
|
i += 1
|
|||
|
|
story += gruppe + [Spacer(1, 1.2 * mm)]
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
# Fließtext: bis zur nächsten Sonderzeile sammeln
|
|||
|
|
gruppe = []
|
|||
|
|
while i < len(zeilen):
|
|||
|
|
t = zeilen[i].strip()
|
|||
|
|
if not t or t[0] in "|#>-" :
|
|||
|
|
break
|
|||
|
|
gruppe.append(t)
|
|||
|
|
i += 1
|
|||
|
|
story += [Paragraph(clean(" ".join(gruppe)), S["body"]), Spacer(1, 1.2 * mm)]
|
|||
|
|
|
|||
|
|
return story
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ------------------------------------------------------------------ Dokument
|
|||
|
|
def page_frame(canvas, doc):
|
|||
|
|
canvas.saveState()
|
|||
|
|
canvas.setStrokeColor(RULE)
|
|||
|
|
canvas.setLineWidth(0.4)
|
|||
|
|
canvas.line(MARGIN_X, PAGE_H - 6.5 * mm, PAGE_W - MARGIN_X, PAGE_H - 6.5 * mm)
|
|||
|
|
canvas.setFont("Sans", 6.8)
|
|||
|
|
canvas.setFillColor(GREY)
|
|||
|
|
canvas.drawString(MARGIN_X, PAGE_H - 5.4 * mm, doc.schirm_titel)
|
|||
|
|
if doc.ingame:
|
|||
|
|
canvas.setFont("Sans-Bold", 6.8)
|
|||
|
|
canvas.setFillColor(ACCENT)
|
|||
|
|
canvas.drawCentredString(PAGE_W / 2, PAGE_H - 5.4 * mm, f"In-Game: {doc.ingame}")
|
|||
|
|
canvas.setFont("Sans", 6.8)
|
|||
|
|
canvas.setFillColor(GREY)
|
|||
|
|
canvas.drawRightString(PAGE_W - MARGIN_X, PAGE_H - 5.4 * mm,
|
|||
|
|
f"Seite {doc.page}")
|
|||
|
|
canvas.restoreState()
|
|||
|
|
|
|||
|
|
|
|||
|
|
class SchirmDoc(BaseDocTemplate):
|
|||
|
|
def __init__(self, *args, schirm_titel: str = "SL-Schirm", ingame: str = "", **kw):
|
|||
|
|
self.schirm_titel = schirm_titel
|
|||
|
|
self.ingame = ingame
|
|||
|
|
super().__init__(*args, **kw)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def build(src: Path = QUELLE, dst: Path = ZIEL) -> tuple[Path, int]:
|
|||
|
|
if not src.exists():
|
|||
|
|
raise SystemExit(f"Quelle fehlt: {src}")
|
|||
|
|
meta, body = parse_frontmatter(src.read_text(encoding="utf-8"))
|
|||
|
|
cards = parse_cards(body)
|
|||
|
|
if not cards:
|
|||
|
|
raise SystemExit(f"Keine '## Karte …'-Abschnitte gefunden in {src}")
|
|||
|
|
|
|||
|
|
titel = meta.get("titel", "SL-Schirm")
|
|||
|
|
untertitel = meta.get("untertitel", "")
|
|||
|
|
ingame = meta.get("ingame", "")
|
|||
|
|
|
|||
|
|
doc = SchirmDoc(str(dst), pagesize=(PAGE_W, PAGE_H),
|
|||
|
|
leftMargin=MARGIN_X, rightMargin=MARGIN_X,
|
|||
|
|
topMargin=MARGIN_TOP, bottomMargin=MARGIN_BOT,
|
|||
|
|
title=f"{titel} – Westreiche", author="Westreiche",
|
|||
|
|
subject="Spielleiter-Schirm (vertraulich)", schirm_titel=titel,
|
|||
|
|
ingame=ingame)
|
|||
|
|
frame = Frame(MARGIN_X, MARGIN_BOT, PAGE_W - 2 * MARGIN_X,
|
|||
|
|
PAGE_H - MARGIN_TOP - MARGIN_BOT, id="body")
|
|||
|
|
doc.addPageTemplates([PageTemplate(id="body", frames=[frame], onPage=page_frame)])
|
|||
|
|
|
|||
|
|
story: list = []
|
|||
|
|
for n, card in enumerate(cards):
|
|||
|
|
if n:
|
|||
|
|
story.append(PageBreak())
|
|||
|
|
story += card_story(card, untertitel)
|
|||
|
|
|
|||
|
|
doc.build(story)
|
|||
|
|
return dst, doc.page
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main() -> None:
|
|||
|
|
ap = argparse.ArgumentParser(description="SL-Schirm (A5 quer) aus Markdown bauen")
|
|||
|
|
ap.add_argument("-s", "--src", default=str(QUELLE))
|
|||
|
|
ap.add_argument("-o", "--out", default=str(ZIEL))
|
|||
|
|
args = ap.parse_args()
|
|||
|
|
out = Path(args.out)
|
|||
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
dst, pages = build(Path(args.src), out)
|
|||
|
|
print(f"OK: {dst} ({pages} Seiten, A5 quer)")
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
main()
|