diff --git a/NOTICE b/NOTICE index 81c96fc3..0119dd54 100644 --- a/NOTICE +++ b/NOTICE @@ -90,6 +90,8 @@ Schriften (public/fonts/*, je Ordner mit OFL.txt), SIL Open Font License 1.1, lo Public Sans, Rubik, Source Sans 3 und Source Serif 4 (Adobe), Space Grotesk, Work Sans. [226] Dieselben Dateien liest auch der GPU-Glyphen-Pass (render2d); die WOFF2-Container sind ohne Transformation neu gepackt (fontTools, Schriftdaten unverändert), die Breitentabellen im Kern (core/src/text_metrics.rs) stammen aus ihrer Tabelle hmtx. + [208] Auch die PDF-Exporte betten diese Schriften ein (Layout-/Plakat-PDF, Berichte; export/pdfFonts.ts): OFL 1.1 erlaubt + das Einbetten in Dokumente; die Schriftdaten bleiben unverändert (WOFF2 -> TTF nur umgepackt, core/src/woff2.rs). Website (website/static/fonts, Lizenztexte OFL-*.txt daneben), SIL Open Font License 1.1, Quelle google/fonts: Schibsted Grotesk (The Schibsted-Grotesk Project Authors), Schnitte 600 und 800, auf Latein beschnitten; diff --git a/TODO.md b/TODO.md index 728b3056..839968a9 100644 --- a/TODO.md +++ b/TODO.md @@ -339,7 +339,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. setzt nur Grundrisse, Ansichten, Schnitt; Situation und Tabelle müssten als Viewport/Tabelle mit ins Plakat ([207], [255]). b) Anordnung nutzt das Raster nicht: Inhalt klein und mittig geballt, grosse Leerflächen (A1 bei 1:200 ≈ 40 % belegt), Zeilen nicht an Spalten ausgerichtet; Schriftfeld des Masters (70 × 30 mm, Text ~2 mm) steht zusätzlich zur Plakat-Kopfzeile unten rechts und ist redundant. c) Schriften nicht eingebettet (jsPDF Standard-14: Helvetica/Times/ - Courier ohne Einbettung; Druckereien verlangen oft eingebettet); keine PDF-Ebenen-Prüfung am Plotter. d) Ansichten: keine Terrain-/Bodenlinie, Kotenmarken + Courier ohne Einbettung; Druckereien verlangen oft eingebettet; BEHOBEN 14.11., s. unten); keine PDF-Ebenen-Prüfung am Plotter. d) Ansichten: keine Terrain-/Bodenlinie, Kotenmarken winzig (< 1 mm Schrift), Fenster grau ohne Rahmenzeichnung; Massketten im Grundriss überlagern sich vereinzelt („12.39“/„4.80“ links, „1.20“ in der Wand E.09). e) Anonymitäts-Dialog zu Recht bei „Hofwiesenstrasse“ in der Kontext-Zeichnung des Beispiels (Adresse) — Beispiel enthält die Adresse im Klartext. f) Schwarzplan/Nachbarn grau nicht beurteilbar (Situation nicht auf dem Plakat). Dateigrösse 98 KB (ohne Bild), Rand/Satzspiegel (Raster 6 Spalten) in Ordnung, @@ -353,6 +353,14 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. Offen: Rahmen sind so breit wie der Inhalt samt Masskette/Kontext (Musterhaus komplex: 2 Spalten je Grundriss, viel Weissraum im Rahmen, 2 Blätter); Anordnung mischt Gruppen (Pläne neben Situation, Ansichten darunter) statt strenger Zeilen; Tabellen-Spaltenköpfe „Reserve/Erfüllt“ eng; Baurecht-Zeilen mit „—“ bei fehlenden Vorgaben; Lage der Tabellen/des Bildes nicht von Hand fixiert (Neuberechnung nur durch Neuerstellen); nicht in der Tauri-App geprüft. + **Schriften im PDF eingebettet (14.11., zu c)**: alle jsPDF-Ausgaben (Blatt-/Plakat-/Ordner-PDF `layoutPdf.ts`, Einzelplan `exportPdf.ts`, Berichte `areaReport.ts`, + Blatt-Tabellen) betten Inter und die im SVG gewählten Familien aus `public/fonts` ein (OFL, `NOTICE`): `export/pdfFonts.ts` lädt die WOFF2 (App: `fetch` auf App-Dateien, + CLI/Tests: `setPdfFontLoader`), der Kern wandelt sie in TTF (`woff2_to_sfnt`, `core/src/woff2.rs` — Datei von render2d mitbenutzt, nicht doppelt), jsPDF bettet nur die + benutzten Glyphen ein (`putOnlyUsedFonts`: auch die 14 Standardschriften entfallen); `font-family`-Listen im Druck-SVG werden auf die erste gebündelte Familie, sonst Inter, + abgebildet. `buildAreaReportPdf` ist jetzt `async`. `pdffonts`: Inter „emb yes“, Umlaute/ß/²/³/±/Ø/–/„“ per `pdftotext` geprüft (vitest `pdfFonts.test.ts`). Plakat + e2e: 59,6 KB (vorher ~48 KB, +11 KB für Inter normal+fett). Text steht im PDF nur noch als Glyphen-Nummern: e2e-/vitest-Prüfungen lesen ihn über `pdftotext` + (`e2e/pdf.ts`, `export/pdfText.testing.ts`). Offen: kein Schnitt-/Kursiv-Rückfall für Glyphen ausserhalb der Latin-Teilmenge (z. B. Σ ≈ − im Bericht werden ersetzt, im SVG-Text + fehlende Zeichen bleiben leer); PDF/X-Prüfung am Plotter nicht möglich; nur im Linux-Container/Chromium geprüft, nicht in der Tauri-App. - [61] Raumprogramm gegen Modell und Flächennachweis SIA 416 als Tabelle/Layout-Element ([70]); Kennzahlen (GF, GV, HNF/GF, Fassadenanteil). - 3D-Bilder für die Abgabe: hochaufgelöster PNG-Export (Perspektive, Axonometrie, Schatten), Sonnenstand; [205] Pausfolie. - [199]/[204] Plan- und App-Review-Reste im Darstellungsbereich 1:500/1:200 schliessen. diff --git a/e2e/competition.spec.ts b/e2e/competition.spec.ts index 518c0037..4dfea84e 100644 --- a/e2e/competition.spec.ts +++ b/e2e/competition.spec.ts @@ -153,8 +153,8 @@ test("Plakat A1 quer aus Vorlage, Bild einsetzen, anonym als WBW-Abgabe exportie expect(text).not.toContain("Demo-Haus"); expect(text).toContain("/Subtype /Image"); const content = pdfStreams(bytes); - expect(content).toContain("(FALKE 7)"); - expect(content).toContain("(Kennwort)"); + expect(content).toContain("FALKE 7"); + expect(content).toContain("Kennwort"); expect(content).not.toContain("Demo-Haus"); if (process.env.DOSSIER_SHOTS) { diff --git a/e2e/pdf.ts b/e2e/pdf.ts index d85b4d8c..f19f5767 100644 --- a/e2e/pdf.ts +++ b/e2e/pdf.ts @@ -1,4 +1,8 @@ // Gemeinsame PDF-/PNG-Helfer der e2e-Specs (Wettbewerb [208], Referenz-Ablauf [206]). +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { deflateSync, inflateSync } from "node:zlib"; /** PNG (Verlauf, Standard 160 × 90 px), im Test erzeugt: kein Fixture, nur die Pflicht-Chunks. */ @@ -37,7 +41,23 @@ export function testPng(w = 160, h = 90): Buffer { return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]); } -/** Text aller Inhaltsströme eines PDFs (Flate entpackt). */ +/** + * Sichtbarer Text des PDFs (`pdftotext`, Poppler). Die eingebetteten Schriften ([208]) kodieren Text als Glyphen- + * Nummern (Identity-H), er steht nicht mehr als `(Text)` im Inhaltsstrom; ohne Poppler leer. + */ +export function pdfText(buf: Buffer): string { + const dir = mkdtempSync(join(tmpdir(), "dossier-e2e-pdf-")); + try { + const file = join(dir, "t.pdf"); + writeFileSync(file, buf); + const r = spawnSync("pdftotext", ["-layout", file, "-"], { encoding: "utf8" }); + return r.status === 0 ? r.stdout : ""; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +/** Text aller Inhaltsströme eines PDFs (Flate entpackt) plus der sichtbare Text (`pdfText`, ohne Klammern). */ export function pdfStreams(buf: Buffer): string { const src = buf.toString("latin1"); let out = src; @@ -51,6 +71,6 @@ export function pdfStreams(buf: Buffer): string { /* kein Flate-Strom */ } } - return out; + return out + "\n" + pdfText(buf); } diff --git a/e2e/release10.spec.ts b/e2e/release10.spec.ts index f2271ae3..4a2e478d 100644 --- a/e2e/release10.spec.ts +++ b/e2e/release10.spec.ts @@ -684,7 +684,7 @@ test("[208] Wettbewerbs-Plakat A1 mit Kennwort, anonymes PDF ohne Projektnamen", expect(raw.slice(0, 5)).toBe("%PDF-"); expect(raw).toMatch(/\/MediaBox \[0 0 2383\.93\d* 1683\.7\d*/); // A1 quer expect(raw).toContain("/Title (FALKE 7)"); - expect(all).toContain("(FALKE 7)"); + expect(all).toContain("FALKE 7"); expect(all).not.toContain(projectName); expect(anon.name).not.toContain(projectName); }); diff --git a/e2e/sheetTable.spec.ts b/e2e/sheetTable.spec.ts index 89650aa0..5bb5947b 100644 --- a/e2e/sheetTable.spec.ts +++ b/e2e/sheetTable.spec.ts @@ -2,9 +2,9 @@ // (Fenster löschen → Zeile weg, Rückgängig → Zeile wieder da) und steht als Vektortext im Ordner-PDF. // Mit DOSSIER_SHOTS= entsteht zusätzlich ein Screenshot des Blatts für die Abnahme. import { readFile, writeFile } from "node:fs/promises"; -import { inflateSync } from "node:zlib"; import type { Page } from "@playwright/test"; import { blurFocus, elementRows, expect, openSample, openTab, startNewProject, test } from "./app"; +import { pdfStreams } from "./pdf"; /** Layout in einem neuen Ordner anlegen und öffnen. */ async function openNewLayoutInFolder(page: Page) { @@ -26,23 +26,6 @@ async function tableMarks(page: Page): Promise { return texts.filter((s) => /^F\d\.\d\d$/.test(s)); } -/** Text aller Inhaltsströme eines PDFs (Flate entpackt). */ -function pdfStreams(buf: Buffer): string { - const src = buf.toString("latin1"); - let out = src; - for (const m of src.matchAll(/stream\r?\n/g)) { - const start = m.index! + m[0].length; - const end = src.indexOf("endstream", start); - if (end < 0) continue; - try { - out += inflateSync(buf.subarray(start, end)).toString("latin1"); - } catch { - /* kein Flate-Strom */ - } - } - return out; -} - test("Tabelle auf dem Blatt: lebendig, mit Spaltenwahl, im PDF als Vektortext", async ({ page }) => { await startNewProject(page); await openSample(page); @@ -95,6 +78,6 @@ test("Tabelle auf dem Blatt: lebendig, mit Spaltenwahl, im PDF als Vektortext", const bytes = await readFile((await dl.path())!); if (shots) await writeFile(`${shots}/blatt-tabelle.pdf`, bytes); const text = pdfStreams(bytes); - expect(text).toContain("(F1.01)"); - expect(text).toContain("(Räume)"); + expect(text).toContain("F1.01"); + expect(text).toContain("Räume"); }); diff --git a/src-tauri/core/Cargo.lock b/src-tauri/core/Cargo.lock index 493fccdf..edc3e8a4 100644 --- a/src-tauri/core/Cargo.lock +++ b/src-tauri/core/Cargo.lock @@ -2,12 +2,37 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -75,6 +100,7 @@ dependencies = [ name = "dossier-core" version = "0.1.0" dependencies = [ + "brotli-decompressor", "console_error_panic_hook", "dossier-hatch", "i_overlay", diff --git a/src-tauri/core/Cargo.toml b/src-tauri/core/Cargo.toml index 9cf9566d..afd35c8b 100644 --- a/src-tauri/core/Cargo.toml +++ b/src-tauri/core/Cargo.toml @@ -32,6 +32,8 @@ wasm-bindgen = { version = "0.2", optional = true } console_error_panic_hook = { version = "0.1", optional = true } # TS-Typen aus dem Rust-Modell ([K4] S4): `src/model/types.generated.ts`, s. `model/ts_export.rs`. # Körper-Booleans ([107] Schritt 2, `solid_bool.rs`): Manifold-Port, exakter Modus; Version gepinnt (junges Crate). +# WOFF2 -> TTF fuer die PDF-Schriften (`woff2.rs`, [208]); reiner Rust-Dekoder, auch wasm. +brotli-decompressor = "5" manifold-rust = "=0.19.1" ts-rs = { version = "12", default-features = false, features = ["serde-compat"] } diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index b12baa1a..fe2e7e13 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -35,6 +35,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `standards.rs` | Standard-Bibliothek: Baustoffe mit SIA-400-Schraffur und Kennwerten, Linientypen, Standard-Aufbauten | | `furniture_lib.rs` | Objektbibliothek 2D ([253]): Katalog der Standard-Symbole mit Parametern (Definition) und Zeichenfunktionen nach Detailgrad (Erzeugung), Register, Platzhalter für unbekannte Ids; s. `doc/ARCHITEKTUR.md` 3.7 | | `text_layout.rs`, `rich_text.rs` | Text-Layout (Zeilen, Umbruch) und Bearbeiten von Rich-Text | +| `woff2.rs` | WOFF2 → TTF/SFNT (nur untransformierte Pakete), `woff2_to_sfnt` für die PDF-Schriften ([208], `src/export/pdfFonts.ts`); render2d bindet dieselbe Datei per `#[path]` ein (Glyphen-Pass [226]) | ## 3D diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index fc07c308..69407c91 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -153,5 +153,6 @@ pub mod presentation_poster; pub mod presentation_sheet; pub mod drawing_recognize; pub mod kosten; +pub mod woff2; #[cfg(test)] mod wall_join3d_tests; diff --git a/src-tauri/core/src/web/fonts.rs b/src-tauri/core/src/web/fonts.rs new file mode 100644 index 00000000..a1b80a8a --- /dev/null +++ b/src-tauri/core/src/web/fonts.rs @@ -0,0 +1,10 @@ +//! Bindung `woff2_to_sfnt` für den PDF-Export ([208]): jsPDF bettet nur TTF ein, die gebündelten Schriften +//! (`public/fonts`) liegen als WOFF2 vor. Kaputte Eingaben ergeben einen leeren Puffer, nie einen Panic. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// WOFF2 (oder rohes SFNT) -> SFNT/TTF-Bytes; leer bei Fehlern. +#[wasm_bindgen] +pub fn woff2_to_sfnt(bytes: &[u8]) -> Vec { + crate::woff2::to_sfnt(bytes).unwrap_or_default() +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 8b0d7166..694f2fa1 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -51,6 +51,7 @@ pub mod opening_presets; pub mod furniture_lib; pub mod solid_bool; pub mod line_pattern; +pub mod fonts; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/render2d/src/woff2.rs b/src-tauri/core/src/woff2.rs similarity index 98% rename from src-tauri/render2d/src/woff2.rs rename to src-tauri/core/src/woff2.rs index c4a5cd43..4b3a81f7 100644 --- a/src-tauri/render2d/src/woff2.rs +++ b/src-tauri/core/src/woff2.rs @@ -193,8 +193,8 @@ mod tests { #[test] fn rohes_sfnt_geht_durch_und_muell_wird_abgelehnt() { - let ttf = include_bytes!("../assets/Inter.ttf"); - assert_eq!(to_sfnt(ttf).unwrap(), ttf); + let ttf = to_sfnt(&std::fs::read(fonts_dir().join("inter/inter-400-normal.woff2")).unwrap()).unwrap(); + assert_eq!(to_sfnt(&ttf).unwrap(), ttf); assert!(to_sfnt(b"").is_err()); assert!(to_sfnt(b"wOF2").is_err()); assert!(to_sfnt(b"wOF2\0\0\0\0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").is_err()); diff --git a/src-tauri/render2d/src/lib.rs b/src-tauri/render2d/src/lib.rs index 7aebc12b..02206974 100644 --- a/src-tauri/render2d/src/lib.rs +++ b/src-tauri/render2d/src/lib.rs @@ -19,6 +19,8 @@ pub mod shaders; pub mod tessellate; pub mod text_lines; pub mod types; +// Eine Datei fuer beide Crates: der PDF-Export ([208]) braucht denselben Entpacker im Kern. +#[path = "../../core/src/woff2.rs"] pub mod woff2; #[cfg(feature = "render")] diff --git a/src/cli/main.ts b/src/cli/main.ts index c71910d2..05fbefdf 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -100,6 +100,7 @@ import { areaReportToCsv, areaReportToSvg, buildAreaReportPdf, + setPdfFontLoader, exportProjectName, isAnonymous, anonymityFindings, @@ -211,6 +212,12 @@ function wasmDir(): string { return resolve(dirname(fileURLToPath(import.meta.url)), "..", "src", "engine"); } +// Schriften fürs PDF ([208]): `public/fonts` neben dem Quellbaum (dist-cli/ → ../public); fehlen sie, bleibt es bei Helvetica. +setPdfFontLoader(async (url) => { + const f = process.env.DOSSIER_FONT_DIR ? join(process.env.DOSSIER_FONT_DIR, url.replace(/^\/fonts\//, "")) : join(dirname(wasmDir()), "..", "public", url); + return existsSync(f) ? new Uint8Array(readFileSync(f)) : null; +}); + const WASM_FILES: Record = { core: "pkgCore/core_bg.wasm", fileio: "pkgFileIo/fileio_bg.wasm", @@ -1138,7 +1145,7 @@ async function execute(project: Project, file: string, command: string, rest: st const report = buildAreaReport(project, { areas: wantAreas, ivhb: wantIvhb, siteProof: wantProof, ivhbOptions }); if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`); else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`); - else if (format === "pdf") out(args, new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")), `${stem}.pdf`); + else if (format === "pdf") out(args, new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")), `${stem}.pdf`); else throw new Error("--format: json, csv, svg oder pdf"); return 0; } @@ -1194,7 +1201,7 @@ async function execute(project: Project, file: string, command: string, rest: st const report = buildProgramReport(next); if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`); else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`); - else if (format === "pdf") out(args, new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")), `${stem}.pdf`); + else if (format === "pdf") out(args, new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")), `${stem}.pdf`); else throw new Error("--format: json, csv, svg oder pdf"); } return 0; @@ -1218,7 +1225,7 @@ async function execute(project: Project, file: string, command: string, rest: st const report = buildOpeningReport(project); if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`); else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`); - else if (format === "pdf") out(args, new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")), `${stem}.pdf`); + else if (format === "pdf") out(args, new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")), `${stem}.pdf`); else throw new Error("--format: json, csv, svg oder pdf"); } return 0; @@ -1232,7 +1239,7 @@ async function execute(project: Project, file: string, command: string, rest: st const report = buildRoomBookReport(project); if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`); else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`); - else if (format === "pdf") out(args, new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")), `${stem}.pdf`); + else if (format === "pdf") out(args, new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")), `${stem}.pdf`); else throw new Error("--format: json, csv, svg oder pdf"); } return 0; @@ -1246,7 +1253,7 @@ async function execute(project: Project, file: string, command: string, rest: st const report = buildElementReport(project); if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`); else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`); - else if (format === "pdf") out(args, new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")), `${stem}.pdf`); + else if (format === "pdf") out(args, new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")), `${stem}.pdf`); else throw new Error("--format: json, csv, svg oder pdf"); } return 0; diff --git a/src/core/extra.ts b/src/core/extra.ts index 7d7422d4..8042cab7 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -50,6 +50,7 @@ export type { CompetitionIdentity } from "../export/competitionIdentity"; export { anonymityFindings } from "../export/competitionCheck"; export type { AnonymityFinding, AnonymityKind } from "../export/competitionCheck"; export { buildAreaReport, areaReportToCsv, parseAreaReportCsv, areaReportToSvg, buildAreaReportPdf } from "../export/areaReport"; +export { setPdfFontLoader } from "../export/pdfFonts"; export type { AreaReport, AreaReportOptions } from "../export/areaReport"; export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun"; export type { SunPosition } from "../analysis/sun"; diff --git a/src/export/areaReport.test.ts b/src/export/areaReport.test.ts index 56a62d1f..95d83170 100644 --- a/src/export/areaReport.test.ts +++ b/src/export/areaReport.test.ts @@ -95,13 +95,13 @@ describe("Bericht", () => { expect(parseAreaReportCsv(areaReportToCsv(r)).projectName).toBe('Haus "A"; Süd'); }); - it("SVG und PDF entstehen aus derselben Seitenaufteilung", () => { + it("SVG und PDF entstehen aus derselben Seitenaufteilung", async () => { const svg = areaReportToSvg(report); expect(svg.startsWith(" { const lay = layoutAreaReport(report, o); - const doc = new jsPDF({ unit: "mm", format: [lay.width, lay.height], orientation: lay.width > lay.height ? "landscape" : "portrait", compress: true }); + const doc = new jsPDF({ unit: "mm", format: [lay.width, lay.height], orientation: lay.width > lay.height ? "landscape" : "portrait", compress: true, putOnlyUsedFonts: true }); + await ensurePdfFonts(doc, [PDF_DEFAULT_FONT]); + const embedded = hasPdfFont(doc); lay.pages.forEach((prims, i) => { if (i > 0) doc.addPage([lay.width, lay.height], lay.width > lay.height ? "landscape" : "portrait"); doc.setTextColor(17, 17, 17); @@ -210,9 +214,9 @@ export function buildAreaReportPdf(report: AreaReport, o: ReportLayoutOptions = doc.setLineWidth(p.w); doc.line(p.x1, p.y1, p.x2, p.y2); } else { - doc.setFont("helvetica", p.bold ? "bold" : "normal"); + setPdfFont(doc, PDF_DEFAULT_FONT, !!p.bold); doc.setFontSize(p.size); - doc.text(pdfSafe(p.s), p.x, p.y, { align: p.align ?? "left" }); + doc.text(pdfSafe(p.s, embedded), p.x, p.y, { align: p.align ?? "left" }); } } }); diff --git a/src/export/competitionAnonymous.test.ts b/src/export/competitionAnonymous.test.ts index 3b7e0b52..afadb0c9 100644 --- a/src/export/competitionAnonymous.test.ts +++ b/src/export/competitionAnonymous.test.ts @@ -18,6 +18,7 @@ import { exportIfcSpf } from "./exportIfc"; import { exportGlb, exportGltf, exportMtl, exportObj, exportStl } from "./exportMesh"; import { exportScheduleCsv } from "./exportSchedule"; import { exportProjectStep } from "./exportStep"; +import { pdfVisibleText } from "./pdfText.testing"; import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf"; import { planToSvgString } from "./planToSvgString"; import { areaReportToCsv, buildAreaReport, buildAreaReportPdf } from "./areaReport"; @@ -68,7 +69,7 @@ function streamsText(bytes: Uint8Array): string { // kein Flate-Stream } } - return out; + return out + "\n" + pdfVisibleText(bytes); } /** Alle Ausgaben, die ohne Browser/GPU entstehen: Name → Text (Binärformate als latin1). */ @@ -84,7 +85,7 @@ async function allOutputs(p: Project): Promise> { const reports = { Flaechen: buildAreaReport(p, { ivhb: true }), Programm: buildProgramReport(p), Raumbuch: buildRoomBookReport(p), Oeffnungen: buildOpeningReport(p), Bauteile: buildElementReport(p), Kosten: buildCostReport(p) }; for (const [name, report] of Object.entries(reports)) { out[`CSV-${name}`] = areaReportToCsv(report); - const bytes = new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")); + const bytes = new Uint8Array((await buildAreaReportPdf(report)).output("arraybuffer")); out[`PDF-${name}`] = latin1(bytes); out[`PDF-${name}-Text`] = streamsText(bytes); out[`PDF-${name}-Info`] = pdfInfoText(bytes); @@ -124,7 +125,8 @@ describe("anonyme Wettbewerbs-Abgabe in allen Ausgaben", () => { ["IFC4", NAME], ["CSV-Flaechen", NAME], ["PDF-Flaechen-Text", NAME], - ["PDF-Blatt-Text", AUTHOR], + ["PDF-Blatt-Text", NAME], + ["PDF-Blatt-Info", AUTHOR], ["Blender-scene.json", NAME], ] as const) { expect(o[where], where).toContain(what); @@ -144,7 +146,7 @@ describe("anonyme Wettbewerbs-Abgabe in allen Ausgaben", () => { it("anonym: das Kennwort steht, wo es stehen soll", async () => { const o = await allOutputs(project(true)); - expect(o["PDF-Blatt-Text"]).toContain(`(${KEYWORD})`); + expect(o["PDF-Blatt-Text"]).toContain(KEYWORD); expect(o["PDF-Blatt-Info"]).toContain(`/Title (${KEYWORD})`); expect(o["PDF-Flaechen-Info"]).toContain(`/Title (${KEYWORD})`); expect(o["PDF-Flaechen-Text"]).toContain(KEYWORD); diff --git a/src/export/exportPdf.ts b/src/export/exportPdf.ts index b8d931d4..889e115c 100644 --- a/src/export/exportPdf.ts +++ b/src/export/exportPdf.ts @@ -13,6 +13,7 @@ import { jsPDF } from "jspdf"; import "svg2pdf.js"; +import { ensurePdfFonts, PDF_DEFAULT_FONT, prepareSvgFonts, setPdfFont } from "./pdfFonts"; import type { Plan } from "../plan/generatePlan"; import { planToRenderScene } from "../plan/toRenderScene"; import { sceneToPrintSvg } from "./sceneToPrintSvg"; @@ -88,11 +89,14 @@ export async function buildPlanPdf( format: [pageW, pageH], orientation: opts.orientation, compress: true, + putOnlyUsedFonts: true, }); // SVG → PDF (Vektor). Die viewBox des SVG ist in mm (Papier-Benutzereinheiten) // und deckungsgleich mit der Blattgröße; svg2pdf bildet sie 1:1 auf das mm-Ziel // (Blattbreite/-höhe) ab. + await ensurePdfFonts(doc, [PDF_DEFAULT_FONT]); + await prepareSvgFonts(doc, print.svg); await doc.svg(print.svg, { x: 0, y: 0, width: pageW, height: pageH }); // Info-Wörterbuch ([208]): anonym nur das Kennwort. doc.setProperties(pdfInfoFields({ name: opts.subtitle ?? opts.title, competition: opts.competition })); @@ -124,17 +128,17 @@ function drawTitleBlock( doc.line(x, y + boxH - 7, x + boxW, y + boxH - 7); doc.setTextColor(17, 17, 17); - doc.setFont("helvetica", "bold"); + setPdfFont(doc, PDF_DEFAULT_FONT, true); doc.setFontSize(10); doc.text(clip(opts.title, 30), x + 3, y + 6); if (opts.subtitle) { - doc.setFont("helvetica", "normal"); + setPdfFont(doc, PDF_DEFAULT_FONT); doc.setFontSize(7); doc.text(clip(opts.subtitle, 40), x + 3, y + 11); } - doc.setFont("helvetica", "normal"); + setPdfFont(doc, PDF_DEFAULT_FONT); doc.setFontSize(9); doc.text(`1:${opts.scaleDenominator}`, x + 3, y + boxH - 2.2); const fmt = `${opts.paper.toUpperCase()} ${ diff --git a/src/export/layoutPdf.images.test.ts b/src/export/layoutPdf.images.test.ts index 3a13fe50..af9d9ec7 100644 --- a/src/export/layoutPdf.images.test.ts +++ b/src/export/layoutPdf.images.test.ts @@ -6,6 +6,7 @@ import type { Layout, Project } from "../model/types"; import { createPosterMaster, posterTemplate } from "../model/posterTemplates"; import { addImage, createLayoutImage } from "../model/layoutImages"; import { JPEG_64X48, PNG_40X30, PNG_40X30_ALPHA } from "../model/layoutImages.testing"; +import { pdfVisibleText } from "./pdfText.testing"; import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf"; import { pdfInfoText } from "./pdfInfo"; @@ -29,7 +30,7 @@ function streamsText(bytes: Uint8Array): string { // kein Flate-Stream (z. B. JPEG) } } - return out; + return out + "\n" + pdfVisibleText(bytes); } function indexOfBytes(hay: Uint8Array, needle: Uint8Array): number { @@ -73,9 +74,9 @@ describe("Blatt-PDF mit Bild", () => { const bytes = pdfBytes(p, doc!); expect(latin1(bytes)).toMatch(/\/MediaBox \[0 0 2383\.93\d* 1683\.7\d*/); // 841 × 594 mm in pt const content = streamsText(bytes); - expect(content).toContain("(Kennwort)"); - expect(content).toContain("(FALKE 7)"); - expect(content).toContain("(Plan 1/1)"); + expect(content).toContain("Kennwort"); + expect(content).toContain("FALKE 7"); + expect(content).toContain("Plan 1/1"); }); it("anonyme Abgabe: keine Büro-/Autor-Angaben, Info nur mit Kennwort, kein jsPDF-Producer", async () => { @@ -92,7 +93,7 @@ describe("Blatt-PDF mit Bild", () => { expect(all).not.toContain("Büro Muster"); expect(all).not.toContain("Maria Muster"); expect(all).not.toContain("Haus Muster"); - expect(all).toContain("(FALKE 7)"); + expect(all).toContain("FALKE 7"); }); it("nicht anonym: Projektname im Titel, Bearbeiter im Info-Wörterbuch", async () => { diff --git a/src/export/layoutPdf.ts b/src/export/layoutPdf.ts index 96eeaa0d..dd2a2bfb 100644 --- a/src/export/layoutPdf.ts +++ b/src/export/layoutPdf.ts @@ -19,8 +19,9 @@ import { categoryLayerGroups, enablePdfLayers, type PdfLayers } from "./pdfLayer import { generatePlan, type Plan } from "../plan/generatePlan"; import { snapshotMono, snapshotOverrideRuleIds, snapshotTemplate, viewportLevelPlan } from "../plan/viewportPlan"; import { planToPrintSvg } from "./planToPrintSvg"; -import { drawTablesPdf, sheetTables } from "./sheetTable"; +import { drawTablesPdf, PDF_TABLE_FONT, sheetTables } from "./sheetTable"; import { applyPdfInfo, finishPdfBytes } from "./pdfInfo"; +import { ensurePdfFonts, PDF_DEFAULT_FONT, prepareSvgFonts, setPdfFont } from "./pdfFonts"; import { imageGeometry } from "../model/layoutImages"; import { posterHeaderItems, viewportScaleLabel } from "../model/posterTemplates"; import { collectVisibleCodes } from "../model/types"; @@ -68,12 +69,12 @@ function drawTitleBlock( doc.line(x, y + boxH - 7, x + boxW, y + boxH - 7); doc.setTextColor(17, 17, 17); - doc.setFont("helvetica", "bold"); + setPdfFont(doc, PDF_DEFAULT_FONT, true); doc.setFontSize(9); doc.text(clip(tb.projectName, 28), x + 3, y + 5.6); doc.text(tb.planNumber, x + boxW - 3, y + 5.6, { align: "right" }); - doc.setFont("helvetica", "normal"); + setPdfFont(doc, PDF_DEFAULT_FONT); doc.setFontSize(8); doc.text(clip(tb.sheetName, 36), x + 3, y + 13); if (showRevision && tb.revision) { @@ -129,6 +130,7 @@ async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout, bounds: { minX: a.x, minY: a.y, maxX: b.x, maxY: b.y }, transparent: true, }); + await prepareSvgFonts(doc, print.svg); await doc.svg(print.svg, { x: 0, y: 0, width: widthMm, height: heightMm }); } @@ -179,7 +181,7 @@ function drawImagesPdf(doc: jsPDF, layout: Layout): void { /** Massstabsangabe unter jedem Viewport ([208], Master `viewportScaleLabels`). */ function drawScaleLabelsPdf(doc: jsPDF, project: Project, layout: Layout, sheet: { w: number; h: number }, scaleOverride?: number): void { doc.setTextColor(17, 17, 17); - doc.setFont("helvetica", "normal"); + setPdfFont(doc, PDF_DEFAULT_FONT); for (const vp of layout.viewports) { const l = viewportScaleLabel(project, vp, sheet, scaleOverride); if (!l) continue; @@ -197,7 +199,7 @@ function drawPosterHeaderPdf(doc: jsPDF, project: Project, layout: Layout, maste doc.setLineWidth(it.stroke); doc.rect(it.x, it.y, it.w, it.h); } else { - doc.setFont("helvetica", it.bold ? "bold" : "normal"); + setPdfFont(doc, PDF_DEFAULT_FONT, it.bold); doc.setFontSize(it.sizeMm * MM_TO_PT); doc.text(it.text, it.x, it.y, { align: it.align }); } @@ -230,6 +232,7 @@ async function renderPage( const planOf = (visible: Set) => viewportLevelPlan(project, snap.activeLevelId, visible, snap.detail, scaleN, true, snapshotMono(project, snap), ruleIds, template, snap.modelViewOptionId); const draw = async (plan: Plan, transparent: boolean, bounds?: Plan["bounds"]) => { const print = planToPrintSvg(plan, { scaleDenominator: scaleN, pageWidthMm: vp.widthMm, pageHeightMm: vp.heightMm, transparent, bounds }); + await prepareSvgFonts(doc, print.svg); await doc.svg(print.svg, { x: vp.xMm, y: vp.yMm, width: vp.widthMm, height: vp.heightMm }); }; const full = await planOf(codes); @@ -269,7 +272,9 @@ async function renderPage( const lp = legendPlan(project, layout, lg); if (!lp) continue; await inLayer(ctx, t("pdfLayers.legend"), async () => { - await doc.svg(legendPrintSvg(lp), { x: lp.xMm, y: lp.yMm, width: lp.widthMm, height: lp.heightMm }); + const legendSvg = legendPrintSvg(lp); + await prepareSvgFonts(doc, legendSvg); + await doc.svg(legendSvg, { x: lp.xMm, y: lp.yMm, width: lp.widthMm, height: lp.heightMm }); }); } catch { // Eine Legende, die nicht rendert, darf die Seite nicht killen. @@ -292,7 +297,9 @@ async function renderPage( // Lebendige Tabellen ([111]): Vektortext + Linien wie in der Blattansicht. try { - await inLayer(ctx, t("pdfLayers.tables"), () => drawTablesPdf(doc, sheetTables(project, layout.id))); + const tables = sheetTables(project, layout.id); + await ensurePdfFonts(doc, tables.flatMap((tb) => tb.prims.flatMap((p) => (p.k === "text" ? [PDF_TABLE_FONT[p.font]] : [])))); + await inLayer(ctx, t("pdfLayers.tables"), () => drawTablesPdf(doc, tables)); } catch { // Eine Tabelle, die nicht rechnet, darf die Seite nicht killen. } @@ -326,7 +333,8 @@ export async function buildPagesPdf(project: Project, pages: FolderPdfPage[], op const orientOf = (s: { w: number; h: number }) => (s.w > s.h ? "landscape" : "portrait"); const first = sizeOf(pages[0]); - const doc = new jsPDF({ unit: "mm", format: [first.w, first.h], orientation: orientOf(first), compress: true }); + const doc = new jsPDF({ unit: "mm", format: [first.w, first.h], orientation: orientOf(first), compress: true, putOnlyUsedFonts: true }); + await ensurePdfFonts(doc, [PDF_DEFAULT_FONT]); // Info-Wörterbuch: anonym nur das Kennwort ([208]); sonst Projektname und Bearbeiter des ersten Blatts. const firstMaster = findMaster(project, pages[0].layout); applyPdfInfo(doc, project, firstMaster ? resolveTitleBlock(project, pages[0].layout, firstMaster).author : undefined); diff --git a/src/export/pdfFonts.setup.ts b/src/export/pdfFonts.setup.ts new file mode 100644 index 00000000..3612eccb --- /dev/null +++ b/src/export/pdfFonts.setup.ts @@ -0,0 +1,5 @@ +// Vitest-Setup: PDF-Schriften aus `public/fonts` lesen (in der App holt `fetch` sie, [208]). +import { existsSync, readFileSync } from "node:fs"; +import { setPdfFontLoader } from "./pdfFonts"; + +setPdfFontLoader(async (url) => (existsSync(`public${url}`) ? new Uint8Array(readFileSync(`public${url}`)) : null)); diff --git a/src/export/pdfFonts.test.ts b/src/export/pdfFonts.test.ts new file mode 100644 index 00000000..b1b09781 --- /dev/null +++ b/src/export/pdfFonts.test.ts @@ -0,0 +1,94 @@ +// [208] PDF-Schriften: Inter und die gewählten Familien sind eingebettet (`pdffonts`: emb yes), Umlaute und +// Sonderzeichen kommen im Text an (`pdftotext`). Ohne Poppler-Werkzeuge laufen nur die Prüfungen ohne sie. +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { jsPDF } from "jspdf"; +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import type { Layout, Project } from "../model/types"; +import { createPosterMaster, posterTemplate } from "../model/posterTemplates"; +import { buildAreaReport, buildAreaReportPdf } from "./areaReport"; +import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf"; +import { ensurePdfFonts, prepareSvgFonts, resolvePdfFamily, setPdfFont, setPdfFontLoader } from "./pdfFonts"; +import { HAVE_POPPLER, pdfVisibleText, withPdfFile } from "./pdfText.testing"; + +const SPECIAL = "Größe Ø 12 ± 3 m² m³ – „Bürgenstock“ ß Äöü"; +const EMB = /\byes\s+(yes|no)\s+(yes|no)\s+\d+\s+\d+\s*$/; // Spalte „emb“ = yes + +const fonts = (bytes: Uint8Array) => withPdfFile(bytes, (f) => spawnSync("pdffonts", [f], { encoding: "utf8" }).stdout.split("\n").slice(2).filter(Boolean)); +const fromDisk = async (url: string) => (existsSync(`public${url}`) ? new Uint8Array(readFileSync(`public${url}`)) : null); + +describe("resolvePdfFamily", () => { + it("erste gebündelte Familie der CSS-Liste, sonst Inter", () => { + expect(resolvePdfFamily("Helvetica, Arial, sans-serif")).toBe("Inter"); + expect(resolvePdfFamily('"IBM Plex Mono", monospace')).toBe("IBM Plex Mono"); + expect(resolvePdfFamily("arial, work sans")).toBe("Work Sans"); + expect(resolvePdfFamily("serif")).toBe("Source Serif 4"); + expect(resolvePdfFamily(null)).toBe("Inter"); + }); +}); + +describe("PDF-Schriften", () => { + it("jsPDF kennt die eingebetteten Schnitte; ohne Lader bleibt Helvetica", async () => { + const doc = new jsPDF(); + await ensurePdfFonts(doc, ["Inter", "Source Serif 4"]); + const list = doc.getFontList(); + expect(list["Inter"]).toEqual(expect.arrayContaining(["normal", "bold", "italic", "bolditalic"])); + expect(list["Source Serif 4"]).toBeDefined(); + setPdfFontLoader(async () => null); + try { + const bare = new jsPDF(); + await ensurePdfFonts(bare, ["Inter"]); + setPdfFont(bare, "Inter", true); + expect(bare.getFont().fontName).toBe("helvetica"); + } finally { + setPdfFontLoader(fromDisk); + } + }); + + it("prepareSvgFonts ersetzt die font-family-Listen durch die gebündelte Familie", async () => { + const doc = new jsPDF(); + const fake = (family: string | null) => { + const attrs = new Map(family === null ? [] : [["font-family", family]]); + return { + getAttribute: (n: string) => attrs.get(n) ?? null, + setAttribute: (n: string, v: string) => void attrs.set(n, v), + hasAttribute: (n: string) => attrs.has(n), + querySelectorAll: () => kids, + }; + }; + const kids = [fake("Helvetica, Arial, sans-serif"), fake("Work Sans, sans-serif")]; + const root = fake(null); + await prepareSvgFonts(doc, root as unknown as Element); + expect(kids.map((k) => k.getAttribute("font-family"))).toEqual(["Inter", "Work Sans"]); + expect(root.getAttribute("font-family")).toBe("Inter"); + }); + + it.runIf(HAVE_POPPLER)("Bericht-PDF: Schrift eingebettet, Sonderzeichen im Text", async () => { + const report = buildAreaReport(sampleProject, { areas: true }); + report.title = SPECIAL; + const doc = await buildAreaReportPdf(report); + const bytes = new Uint8Array(doc.output("arraybuffer")); + const rows = fonts(bytes); + expect(rows.length).toBeGreaterThan(0); + for (const r of rows) expect(r).toMatch(EMB); + expect(rows.join("\n")).toMatch(/Inter/); + expect(rows.join("\n")).not.toMatch(/Helvetica|Times|Courier/); + expect(pdfVisibleText(bytes).replace(/\s+/g, " ")).toContain(SPECIAL); + }); + + it.runIf(HAVE_POPPLER)("Blatt-PDF: Plakat-Kopfzeile in Inter, Sonderzeichen im Text", async () => { + const master = createPosterMaster("m1", posterTemplate("poster-a1-landscape")!); + master.titleBlock = { projectName: SPECIAL, author: "Zoë Müller" }; + const lay: Layout = { id: "l1", name: "Grundriss", paper: "a1", orientation: "landscape", masterId: "m1", viewports: [] }; + const p: Project = { ...sampleProject, name: "Haus", masterLayouts: [master], layouts: [lay] }; + const doc = await buildPagesPdf(p, layoutPages(p, ["l1"])); + const bytes = pdfBytes(p, doc!); + const rows = fonts(bytes); + expect(rows.length).toBeGreaterThan(0); + for (const r of rows) expect(r).toMatch(EMB); + expect(rows.join("\n")).not.toMatch(/Helvetica|Times|Courier/); + // Ø, ², ³, ±, –, „“, ß und Umlaute müssen unversehrt ankommen. + expect(pdfVisibleText(bytes).replace(/\s+/g, " ")).toContain(SPECIAL); + }); +}); diff --git a/src/export/pdfFonts.ts b/src/export/pdfFonts.ts new file mode 100644 index 00000000..d6494592 --- /dev/null +++ b/src/export/pdfFonts.ts @@ -0,0 +1,154 @@ +// Schriften im PDF ([208], Abgabe-Review 14.11.): Inter und die im Projekt gewählten Familien aus `public/fonts` +// (SIL OFL, `TEXT_FONTS`) werden eingebettet — dieselben wie Bildschirm und SVG, nicht mehr die Standard-14 +// von jsPDF (Helvetica/Times/Courier, nicht eingebettet, nur WinAnsi). jsPDF bettet nur TTF ein: die WOFF2-Dateien +// (untransformiert, `core/woff2.rs`) wandelt der Kern in SFNT um. Eingebettet wird je Dokument nur, was +// tatsächlich vorkommt (Familie × Schnitt); die gebündelten Dateien sind bereits Latin-Teilmengen (< 100 KB je +// Schnitt), jsPDF komprimiert sie im Strom. Kein Netzabruf: `fetch` auf App-eigene Dateien, in Node (CLI, Tests) +// über `setPdfFontLoader`. + +import type { jsPDF } from "jspdf"; +import { core } from "../engine/coreWasm"; +import { TEXT_FONTS } from "../text/fontList"; + +/** Bytes einer gebündelten Schriftdatei (`/fonts//-400-normal.woff2`); `null` = nicht verfügbar. */ +export type PdfFontLoader = (url: string) => Promise; + +const fetchLoader: PdfFontLoader = async (url) => { + try { + const r = await globalThis.fetch(url); // App-eigene Datei, kein Netzabruf (daher nicht `netFetch`) + return r.ok ? new Uint8Array(await r.arrayBuffer()) : null; + } catch { + return null; + } +}; + +let loader: PdfFontLoader = fetchLoader; +const fileCache = new Map>(); + +/** Lader austauschen (CLI/Tests lesen aus `public/fonts`); ohne Argument zurück auf `fetch`. */ +export function setPdfFontLoader(f?: PdfFontLoader): void { + loader = f ?? fetchLoader; + fileCache.clear(); +} + +export const PDF_DEFAULT_FONT = "Inter"; +/** Familie für CSS-Allgemeinnamen im SVG (`serif`, `monospace`). */ +const GENERIC: Record = { serif: "Source Serif 4", monospace: "IBM Plex Mono" }; + +const STYLES = [ + { style: "normal", weight: 400, slant: "normal" }, + { style: "bold", weight: 700, slant: "normal" }, + { style: "italic", weight: 400, slant: "italic" }, + { style: "bolditalic", weight: 700, slant: "italic" }, +] as const; + +const slugOf = (family: string) => family.toLowerCase().replace(/\s+/g, "-"); + +/** Gebündelte Familie zu einem Namen (Gross-/Kleinschreibung egal, Anführungszeichen entfernt). */ +export function bundledFamily(name: string): string | undefined { + const n = name.trim().replace(/^["']|["']$/g, "").toLowerCase(); + return TEXT_FONTS.find((f) => f.toLowerCase() === n) ?? GENERIC[n]; +} + +/** Erste gebündelte Familie einer CSS-`font-family`-Liste, sonst Inter (Standard von Bildschirm und SVG). */ +export function resolvePdfFamily(cssList: string | null | undefined): string { + for (const part of (cssList ?? "").split(",")) { + const f = bundledFamily(part); + if (f) return f; + } + return PDF_DEFAULT_FONT; +} + +/** TTF als Base64 (so erwartet es `addFileToVFS`); `null` bei fehlender Datei oder Umwandlungsfehler. */ +function loadTtfBase64(url: string): Promise { + let p = fileCache.get(url); + if (!p) { + p = (async () => { + const woff = await loader(url); + if (!woff || woff.length === 0) return null; + const sfnt = core().woff2_to_sfnt(woff); + if (sfnt.length === 0) return null; + let bin = ""; + for (let i = 0; i < sfnt.length; i += 0x8000) bin += String.fromCharCode(...sfnt.subarray(i, i + 0x8000)); + return btoa(bin); + })(); + fileCache.set(url, p); + } + return p; +} + +const registered = new WeakMap>>(); +const ready = new WeakMap>(); + +/** + * Familie im Dokument registrieren (je Dokument einmal): alle vier Schnitte, fehlende (Kursiv bei Manrope, + * Outfit, Space Grotesk) ersatzweise mit dem Normalschnitt gleicher Stärke. `false` = Familie nicht ladbar + * (dann bleibt der Aufrufer bei Helvetica). + */ +function ensurePdfFont(doc: jsPDF, family: string): Promise { + let m = registered.get(doc); + if (!m) registered.set(doc, (m = new Map())); + let p = m.get(family); + if (!p) { + p = (async () => { + const slug = slugOf(family); + const url = (weight: number, slant: string) => `/fonts/${slug}/${slug}-${weight}-${slant}.woff2`; + let any = false; + for (const s of STYLES) { + const data = (await loadTtfBase64(url(s.weight, s.slant))) ?? (await loadTtfBase64(url(s.weight, "normal"))); + if (!data) continue; + const file = `${slug}-${s.weight}-${s.slant}.ttf`; + doc.addFileToVFS(file, data); + doc.addFont(file, family, s.style); + any = true; + } + return any; + })(); + m.set(family, p); + } + return p; +} + +/** Familien im Dokument registrieren und als verwendbar vormerken. */ +export async function ensurePdfFonts(doc: jsPDF, families: Iterable): Promise { + let ok = ready.get(doc); + if (!ok) ready.set(doc, (ok = new Set())); + for (const f of new Set(families)) if (await ensurePdfFont(doc, f)) ok.add(f); +} + +/** Schrift für `doc.text`: die eingebettete Familie, sonst (Lader fehlt) die jsPDF-Helvetica. */ +export function setPdfFont(doc: jsPDF, family: string, bold = false, italic = false): void { + const style = bold && italic ? "bolditalic" : bold ? "bold" : italic ? "italic" : "normal"; + doc.setFont(ready.get(doc)?.has(family) ? family : "helvetica", style); +} + +/** Hat das Dokument die Schrift eingebettet (sonst Helvetica, die nur WinAnsi kann)? */ +export function hasPdfFont(doc: jsPDF, family: string = PDF_DEFAULT_FONT): boolean { + return ready.get(doc)?.has(family) ?? false; +} + +/** + * Vor `doc.svg(...)`: setzt an jedem Text die aufgelöste gebündelte Familie (`font-family`-Liste → erste bekannte, + * sonst Inter) und registriert diese im Dokument. svg2pdf wählt die Schrift sonst aus der Liste der + * jsPDF-Schriften (Helvetica/Arial → Standard-Helvetica, nicht eingebettet). + */ +export async function prepareSvgFonts(doc: jsPDF, root: Element): Promise { + const used = new Set([PDF_DEFAULT_FONT]); + const nodes: Element[] = [root, ...Array.from(root.querySelectorAll("[font-family]"))]; + for (const el of nodes) { + const css = el.getAttribute("font-family"); + if (css === null) continue; + const f = resolvePdfFamily(css); + el.setAttribute("font-family", f); + used.add(f); + } + await ensurePdfFonts(doc, used); + const ok = ready.get(doc); + // Nicht ladbare Familien (kein Lader): zurück auf die Standardschrift, svg2pdf sucht sonst Unbekanntes. + for (const el of nodes) { + const f = el.getAttribute("font-family"); + if (f !== null && !ok?.has(f)) el.setAttribute("font-family", "Helvetica"); + } + // Text ohne eigenes `font-family` (Wurzel hat keines): Inter als Vorgabe setzen. + if (!root.hasAttribute("font-family")) root.setAttribute("font-family", ok?.has(PDF_DEFAULT_FONT) ? PDF_DEFAULT_FONT : "Helvetica"); +} diff --git a/src/export/pdfText.testing.ts b/src/export/pdfText.testing.ts new file mode 100644 index 00000000..a8bcde86 --- /dev/null +++ b/src/export/pdfText.testing.ts @@ -0,0 +1,25 @@ +// Test-Helfer ([208]): sichtbarer Text eines PDFs über `pdftotext` (Poppler). Mit den eingebetteten Schriften steht +// Text nicht mehr als `(Text)` im Inhaltsstrom, sondern als Glyphen-Nummern (Identity-H). +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +export const HAVE_POPPLER = spawnSync("pdftotext", ["-v"]).error === undefined && spawnSync("pdffonts", ["-v"]).error === undefined; + +export function withPdfFile(bytes: Uint8Array, fn: (file: string) => T): T { + const dir = mkdtempSync(join(tmpdir(), "dossier-pdf-")); + try { + const file = join(dir, "t.pdf"); + writeFileSync(file, bytes); + return fn(file); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +/** Sichtbarer Text (Zeilen so, wie sie auf dem Blatt stehen); leer ohne Poppler. */ +export function pdfVisibleText(bytes: Uint8Array): string { + if (!HAVE_POPPLER) return ""; + return withPdfFile(bytes, (f) => spawnSync("pdftotext", ["-layout", f, "-"], { encoding: "utf8" }).stdout); +} diff --git a/src/export/sheetTable.ts b/src/export/sheetTable.ts index 68521880..48ca21c1 100644 --- a/src/export/sheetTable.ts +++ b/src/export/sheetTable.ts @@ -3,6 +3,7 @@ // (`src-tauri/core/src/sheet_table.rs`, Abfrage `sheetTables`); hier nur die Beschriftung mit `t()`, die Kern- // Fassade und das Zeichnen ins jsPDF (Vektortext) — dieselben Primitive wie Blattansicht und DXF. +import { setPdfFont } from "./pdfFonts"; import type { jsPDF } from "jspdf"; import type { Layout, LayoutTable, LayoutTableSource, Project } from "../model/types"; import { t } from "../i18n/translate"; @@ -74,7 +75,8 @@ export function createTable(id: string, source: LayoutTableSource, sheetW: numbe return { id, source, xMm: 10, yMm: y, widthMm: width }; } -const PDF_FONT = { sans: "helvetica", serif: "times", mono: "courier" } as const; +/** Gebündelte Familien der drei Tabellenschriften ([208]: eingebettet statt Helvetica/Times/Courier). */ +export const PDF_TABLE_FONT = { sans: "Inter", serif: "Source Serif 4", mono: "IBM Plex Mono" } as const; const PT_PER_MM = 72 / 25.4; /** Zeichnet die Tabellen eines Blatts als Vektor (Text + Linien) auf die aktuelle jsPDF-Seite. */ @@ -87,7 +89,7 @@ export function drawTablesPdf(doc: jsPDF, tables: readonly TableOut[]): void { doc.setLineWidth(p.w); doc.line(p.x1, p.y1, p.x2, p.y2); } else { - doc.setFont(PDF_FONT[p.font], p.bold && p.italic ? "bolditalic" : p.bold ? "bold" : p.italic ? "italic" : "normal"); + setPdfFont(doc, PDF_TABLE_FONT[p.font], p.bold, p.italic); doc.setFontSize(p.size * PT_PER_MM); doc.text(p.s, p.x, p.y, { align: p.align === "r" ? "right" : "left" }); } diff --git a/src/panels/AreaTableSection.tsx b/src/panels/AreaTableSection.tsx index e73a84ca..28e4075f 100644 --- a/src/panels/AreaTableSection.tsx +++ b/src/panels/AreaTableSection.tsx @@ -30,9 +30,9 @@ export function AreaTableSection() { const stem = `${exportProjectName(project) || "projekt"}-flaechen`; const exportPdf = () => { - runWithAnonymityGate(project, [`${stem}.pdf`], () => { + runWithAnonymityGate(project, [`${stem}.pdf`], async () => { try { - buildAreaReportPdf(report).save(`${stem}.pdf`); + (await buildAreaReportPdf(report)).save(`${stem}.pdf`); } catch { notify(t("areas.exportPdf.fail")); } diff --git a/src/panels/CostEstimateSection.tsx b/src/panels/CostEstimateSection.tsx index 0d24fed3..69c45949 100644 --- a/src/panels/CostEstimateSection.tsx +++ b/src/panels/CostEstimateSection.tsx @@ -76,9 +76,9 @@ export function CostEstimateSection() { const exportCsv = () => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, areaReportToCsv(buildCostReport(project, res)))); const exportPdf = () => { - runWithAnonymityGate(project, [`${stem}.pdf`], () => { + runWithAnonymityGate(project, [`${stem}.pdf`], async () => { try { - buildAreaReportPdf(buildCostReport(project, res)).save(`${stem}.pdf`); + (await buildAreaReportPdf(buildCostReport(project, res))).save(`${stem}.pdf`); } catch { notify(t("costs.export.fail")); } diff --git a/src/panels/ElementScheduleSection.tsx b/src/panels/ElementScheduleSection.tsx index 7ed41b13..a169d428 100644 --- a/src/panels/ElementScheduleSection.tsx +++ b/src/panels/ElementScheduleSection.tsx @@ -15,9 +15,9 @@ export function ElementScheduleSection() { const rows = useMemo(() => elementSchedule(project), [project]); const stem = `${exportProjectName(project) || "projekt"}-bauteile`; const exportPdf = () => { - runWithAnonymityGate(project, [`${stem}.pdf`], () => { + runWithAnonymityGate(project, [`${stem}.pdf`], async () => { try { - buildAreaReportPdf(buildElementReport(project)).save(`${stem}.pdf`); + (await buildAreaReportPdf(buildElementReport(project))).save(`${stem}.pdf`); } catch { notify(t("openings.exportPdf.fail")); } diff --git a/src/panels/OpeningScheduleSection.tsx b/src/panels/OpeningScheduleSection.tsx index 250800db..c812ec5a 100644 --- a/src/panels/OpeningScheduleSection.tsx +++ b/src/panels/OpeningScheduleSection.tsx @@ -39,9 +39,9 @@ export function OpeningScheduleSection() { const setExternal = (id: string, value: string) => patch(id, { isExternal: value === "" ? undefined : value === "ext" }, "isExternal"); const exportPdf = () => { - runWithAnonymityGate(project, [`${stem}.pdf`], () => { + runWithAnonymityGate(project, [`${stem}.pdf`], async () => { try { - buildAreaReportPdf(buildOpeningReport(project)).save(`${stem}.pdf`); + (await buildAreaReportPdf(buildOpeningReport(project))).save(`${stem}.pdf`); } catch { notify(t("openings.exportPdf.fail")); } diff --git a/src/panels/ProgramCompareSection.tsx b/src/panels/ProgramCompareSection.tsx index d22617d4..837fb1a7 100644 --- a/src/panels/ProgramCompareSection.tsx +++ b/src/panels/ProgramCompareSection.tsx @@ -60,9 +60,9 @@ export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: C }; const exportPdf = () => { - runWithAnonymityGate(project, [`${stem}.pdf`], () => { + runWithAnonymityGate(project, [`${stem}.pdf`], async () => { try { - buildAreaReportPdf(buildProgramReport(project)).save(`${stem}.pdf`); + (await buildAreaReportPdf(buildProgramReport(project))).save(`${stem}.pdf`); } catch { notify(t("program.compare.exportPdf.fail")); } diff --git a/src/panels/RoomBookSection.tsx b/src/panels/RoomBookSection.tsx index 2f65d6fc..6eaf1172 100644 --- a/src/panels/RoomBookSection.tsx +++ b/src/panels/RoomBookSection.tsx @@ -21,9 +21,9 @@ export function RoomBookSection() { const stem = `${exportProjectName(project) || "projekt"}-raumbuch`; const exportPdf = () => { - runWithAnonymityGate(project, [`${stem}.pdf`], () => { + runWithAnonymityGate(project, [`${stem}.pdf`], async () => { try { - buildAreaReportPdf(buildRoomBookReport(project)).save(`${stem}.pdf`); + (await buildAreaReportPdf(buildRoomBookReport(project))).save(`${stem}.pdf`); } catch { notify(t("roomBook.exportPdf.fail")); } diff --git a/vitest.config.ts b/vitest.config.ts index d39cfac2..8c241f3b 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -5,7 +5,7 @@ export default defineConfig({ environment: "node", include: ["src/**/*.test.ts"], // Rust-Kern (pkgCore) vor jedem Testmodul synchron laden. - setupFiles: ["src/engine/coreWasm.setup.ts"], + setupFiles: ["src/engine/coreWasm.setup.ts", "src/export/pdfFonts.setup.ts"], // Grosszügig: andere Agents bauen/testen parallel, die Maschine ist oft überbucht. Die 5-s-Vorgabe // traf dann Tests mit grossen Eingaben (Plan-Chunks, Kern-Chargen), die allein < 1 s laufen. // Fehlschläge bleiben Fehlschläge; nur die Wartezeit bis zum Abbruch ist länger.