[208] PDF: Inter und gewählte Familien eingebettet statt jsPDF-Standardschriften (Layout-/Plakat-/Einzelplan-PDF, Berichte, Blatt-Tabellen); WOFF2→TTF im Kern
This commit is contained in:
34 files changed
+440
-77
No files matched your search
@@ -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("<svg")).toBe(true);
|
||||
expect(svg).toContain("NGF");
|
||||
const lay = layoutAreaReport(report);
|
||||
expect(lay.pages.length).toBeGreaterThanOrEqual(1);
|
||||
const pdf = buildAreaReportPdf(report);
|
||||
const pdf = await buildAreaReportPdf(report);
|
||||
expect(pdf.getNumberOfPages()).toBe(lay.pages.length);
|
||||
expect(pdf.output("arraybuffer").byteLength).toBeGreaterThan(1000);
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import { jsPDF } from "jspdf";
|
||||
import type { Project } from "../model/types";
|
||||
import { t } from "../i18n/translate";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { ensurePdfFonts, hasPdfFont, PDF_DEFAULT_FONT, setPdfFont } from "./pdfFonts";
|
||||
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
import type { AreaRow, IvhbOptions } from "../analysis/areaTable";
|
||||
import { computeSiteProof } from "../analysis/siteProof";
|
||||
@@ -192,15 +193,18 @@ export function areaReportToSvg(report: AreaReport, page = 0, o: ReportLayoutOpt
|
||||
return core().area_report_svg(JSON.stringify(report), Math.max(0, page), JSON.stringify(o));
|
||||
}
|
||||
|
||||
/** Die eingebaute Helvetica kennt nur WinAnsi: Zeichen ausserhalb ersetzen. */
|
||||
function pdfSafe(s: string): string {
|
||||
return s.replace(/Σ/g, "Sum").replace(/≈/g, "~").replace(/[–−]/g, "-");
|
||||
/** Zeichen ausserhalb der eingebetteten Latin-Teilmenge ersetzen; die Rückfall-Helvetica kennt nur WinAnsi (auch –). */
|
||||
function pdfSafe(s: string, embedded: boolean): string {
|
||||
const r = s.replace(/Σ/g, "Sum").replace(/≈/g, "~").replace(/−/g, "-");
|
||||
return embedded ? r : r.replace(/–/g, "-");
|
||||
}
|
||||
|
||||
/** Vektor-PDF des Berichts (A4 quer, eine oder mehrere Seiten). */
|
||||
export function buildAreaReportPdf(report: AreaReport, o: ReportLayoutOptions = {}): jsPDF {
|
||||
export async function buildAreaReportPdf(report: AreaReport, o: ReportLayoutOptions = {}): Promise<jsPDF> {
|
||||
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" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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<Record<string, string>> {
|
||||
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);
|
||||
|
||||
@@ -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()} ${
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
+16
-8
@@ -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<string>) => 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);
|
||||
|
||||
@@ -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));
|
||||
@@ -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<string, string>(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);
|
||||
});
|
||||
});
|
||||
@@ -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/<slug>/<slug>-400-normal.woff2`); `null` = nicht verfügbar. */
|
||||
export type PdfFontLoader = (url: string) => Promise<Uint8Array | null>;
|
||||
|
||||
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<string, Promise<string | null>>();
|
||||
|
||||
/** 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<string, string> = { 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<string | null> {
|
||||
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<jsPDF, Map<string, Promise<boolean>>>();
|
||||
const ready = new WeakMap<jsPDF, Set<string>>();
|
||||
|
||||
/**
|
||||
* 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<boolean> {
|
||||
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<string>): Promise<void> {
|
||||
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<void> {
|
||||
const used = new Set<string>([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");
|
||||
}
|
||||
@@ -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<T>(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);
|
||||
}
|
||||
@@ -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" });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user