"""Font download, sanitization, and FPDF writing.""" from __future__ import annotations import hashlib import re import urllib.request from pathlib import Path from fpdf import FPDF from fpdf.enums import Align, WrapMode FONT_DIR = Path(__file__).resolve().parent / "_fonts" FONT_URLS = { "NotoSans-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf", "SourceHanSansSC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/SimplifiedChinese/SourceHanSansSC-Regular.otf", "SourceHanSansK-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/Korean/SourceHanSansK-Regular.otf", } EXTRA_FONT_URLS = { "SourceHanSansTC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/TraditionalChinese/SourceHanSansTC-Regular.otf", "NotoSansDevanagari-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansDevanagari/NotoSansDevanagari-Regular.ttf", "NotoSansArmenian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansArmenian/NotoSansArmenian-Regular.ttf", "NotoSansGeorgian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansGeorgian/NotoSansGeorgian-Regular.ttf", } def ensure_fonts() -> None: FONT_DIR.mkdir(parents=True, exist_ok=True) all_fonts = {**FONT_URLS, **EXTRA_FONT_URLS} for name, url in all_fonts.items(): dest = FONT_DIR / name if dest.exists() and dest.stat().st_size > 1000: continue print(f"Downloading font {name} …", flush=True) req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f: f.write(r.read()) def sanitize_pdf_text(s: str) -> str: s = str(s).replace("\t", " ").replace("\r\n", "\n").replace("\r", "\n") s = s.replace("\uf0b7", "•").replace("\uf0a7", "•").replace("\uf0d8", "•") s = s.replace("\uf02d", "–") return s def safe_slug(case_id: str | None, link: str | None, row_idx: int) -> str: raw = (case_id or "").strip() if not raw: h = hashlib.sha256(((link or "") + str(row_idx)).encode("utf-8")).hexdigest()[:12] raw = f"decision_{row_idx}_{h}" raw = raw.replace("\n", " ").strip() raw = re.sub(r'[\x00-\x1f<>:"/\\|?*]', "_", raw) raw = re.sub(r"\s+", "_", raw) raw = raw.strip("._") or f"row_{row_idx}" if len(raw) > 120: raw = raw[:120].rstrip("_") return raw class UnicodePDF(FPDF): pass def pdf_font_setup(pdf: FPDF, key: str) -> str: if key == "han_sc": pdf.add_font("HanSC", "", str(FONT_DIR / "SourceHanSansSC-Regular.otf")) return "HanSC" if key == "han_tc": pdf.add_font("HanTC", "", str(FONT_DIR / "SourceHanSansTC-Regular.otf")) return "HanTC" if key == "han_k": pdf.add_font("HanK", "", str(FONT_DIR / "SourceHanSansK-Regular.otf")) return "HanK" if key == "deva": pdf.add_font("Deva", "", str(FONT_DIR / "NotoSansDevanagari-Regular.ttf")) return "Deva" if key == "arm": pdf.add_font("Arm", "", str(FONT_DIR / "NotoSansArmenian-Regular.ttf")) return "Arm" if key == "geo": pdf.add_font("Geo", "", str(FONT_DIR / "NotoSansGeorgian-Regular.ttf")) return "Geo" pdf.add_font("NotoSans", "", str(FONT_DIR / "NotoSans-Regular.ttf")) return "NotoSans" def write_one_pdf( path: Path, case_id: str, link: str, body: str, font_key: str, *, text_source: str | None = None, ) -> None: path.parent.mkdir(parents=True, exist_ok=True) pdf = UnicodePDF() pdf.set_auto_page_break(auto=True, margin=14) pdf.set_left_margin(14) pdf.set_right_margin(14) pdf.add_page() # Use one font for meta + body when the script is non-Latin: case_id often # contains Hangul etc., and NotoSans would miss those glyphs in the header. if font_key == "default": text_family = pdf_font_setup(pdf, "default") else: text_family = pdf_font_setup(pdf, font_key) pdf.set_font(text_family, size=11) head = [f"case_id: {case_id}", f"link: {link}"] if text_source: head.append(f"Quelle Text: {text_source}") head.append("") meta = sanitize_pdf_text("\n".join(head)) # Latin header: WORD wrap; CJK header lines are short — WORD is fine with LEFT. pdf.multi_cell(0, 6, meta, align=Align.L, wrapmode=WrapMode.WORD) pdf.ln(2) pdf.set_font(text_family, size=10) text = body if (body and str(body).strip()) else "(kein Volltext in der Quelle)" body_txt = sanitize_pdf_text(text) if font_key == "default": pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.WORD) else: pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.CHAR) pdf.output(str(path))