Import aus Monorepo (frischer Start)
All checks were successful
Build & Deploy / deploy (push) Successful in 10s
All checks were successful
Build & Deploy / deploy (push) Successful in 10s
This commit is contained in:
146
src/lib/page-layout.js
Normal file
146
src/lib/page-layout.js
Normal file
@@ -0,0 +1,146 @@
|
||||
const PX_PER_MM = 3.78; // 96dpi
|
||||
const FONT_SIZE_PX = 26;
|
||||
|
||||
// ── Formate: Defaults (Fallback) + datengetriebener Cache ───────────────────
|
||||
// Die Werte kommen zentral aus Directus (Collection render_formats) und werden
|
||||
// im Speicher gehalten (stündlich / manuell aufgefrischt via applyRenderFormats).
|
||||
// Ist Directus nicht erreichbar oder ein Format nicht hinterlegt, greifen die
|
||||
// eingebauten Defaults – die Generierung läuft also immer.
|
||||
const DEFAULT_LINE_LIMITS = { a4: 27, a6p: 14, a6l: 11 };
|
||||
const DEFAULT_FORMAT_LAYOUTS = {
|
||||
a4: { marginTopMm: 25, marginLeftMm: 20, lineHeightFactor: 1.35 },
|
||||
a6p: { marginTopMm: 8, marginLeftMm: 8, lineHeightFactor: 1.3 },
|
||||
a6l: { marginTopMm: 8, marginLeftMm: 8, marginRightMm: 14, lineHeightFactor: 1.2 },
|
||||
din_lang: { marginTopMm: 50, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
||||
c6: { marginTopMm: 60, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
||||
};
|
||||
const DEFAULT_PAGE_FORMATS = {
|
||||
a4: { widthMm: 210, heightMm: 297 },
|
||||
a6p: { widthMm: 105, heightMm: 148 },
|
||||
a6l: { widthMm: 148, heightMm: 105 },
|
||||
din_lang: { widthMm: 220, heightMm: 110 },
|
||||
c6: { widthMm: 162, heightMm: 114 },
|
||||
};
|
||||
|
||||
// Live-Cache (wird von applyRenderFormats ersetzt). Start = Defaults.
|
||||
let LINE_LIMITS = { ...DEFAULT_LINE_LIMITS };
|
||||
let FORMAT_LAYOUTS = { ...DEFAULT_FORMAT_LAYOUTS };
|
||||
let PAGE_FORMATS = { ...DEFAULT_PAGE_FORMATS };
|
||||
|
||||
/**
|
||||
* Übernimmt Format-Definitionen aus Directus (render_formats) in den Cache.
|
||||
* Baut immer auf den Defaults auf, damit Teilangaben nichts kaputt machen.
|
||||
* rows: [{ key, page_width_mm, page_height_mm, margin_top_mm, margin_left_mm,
|
||||
* margin_right_mm, line_height_factor, line_limit }]
|
||||
*/
|
||||
function applyRenderFormats(rows) {
|
||||
const pf = { ...DEFAULT_PAGE_FORMATS };
|
||||
const fl = { ...DEFAULT_FORMAT_LAYOUTS };
|
||||
const ll = { ...DEFAULT_LINE_LIMITS };
|
||||
for (const r of Array.isArray(rows) ? rows : []) {
|
||||
const k = String(r.key || '').toLowerCase();
|
||||
if (!k) continue;
|
||||
if (r.page_width_mm && r.page_height_mm) {
|
||||
pf[k] = { widthMm: Number(r.page_width_mm), heightMm: Number(r.page_height_mm) };
|
||||
}
|
||||
const alt = fl[k] || {};
|
||||
const layout = {
|
||||
marginTopMm: Number(r.margin_top_mm ?? alt.marginTopMm ?? 25),
|
||||
marginLeftMm: Number(r.margin_left_mm ?? alt.marginLeftMm ?? 20),
|
||||
lineHeightFactor: Number(r.line_height_factor ?? alt.lineHeightFactor ?? 1.35),
|
||||
};
|
||||
const mr = r.margin_right_mm ?? alt.marginRightMm;
|
||||
if (mr != null && mr !== '') layout.marginRightMm = Number(mr);
|
||||
fl[k] = layout;
|
||||
if (r.line_limit != null && r.line_limit !== '') ll[k] = Number(r.line_limit);
|
||||
}
|
||||
PAGE_FORMATS = pf;
|
||||
FORMAT_LAYOUTS = fl;
|
||||
LINE_LIMITS = ll;
|
||||
signaledMisses.clear();
|
||||
}
|
||||
|
||||
// mm in Pixel umrechnen
|
||||
function mmToPx(mm) {
|
||||
return mm * PX_PER_MM;
|
||||
}
|
||||
|
||||
// ── Refresh bei unbekanntem Format ──────────────────────────────────────────
|
||||
// Wird ein Format angefragt, das (noch) nicht im Cache liegt, meldet page-layout
|
||||
// das einmalig an einen Handler (den der Server auf refreshRenderFormats setzt).
|
||||
// So werden neu in Directus angelegte Formate sofort nachgeladen, ohne die
|
||||
// stündliche Aktualisierung abzuwarten. Für DIESEN Aufruf greift noch der
|
||||
// Default – der nächste Aufruf hat das Format.
|
||||
let missHandler = null;
|
||||
const signaledMisses = new Set();
|
||||
function setFormatMissHandler(fn) { missHandler = fn; }
|
||||
function signalMiss(key) {
|
||||
const k = String(key || '').toLowerCase();
|
||||
if (!missHandler || !k || signaledMisses.has(k)) return;
|
||||
signaledMisses.add(k);
|
||||
try { missHandler(k); } catch { /* egal */ }
|
||||
}
|
||||
|
||||
// Layout für Format holen
|
||||
function getLayoutForFormat(format) {
|
||||
const normalizedFormat = String(format).toLowerCase();
|
||||
const layoutConfig = FORMAT_LAYOUTS[normalizedFormat];
|
||||
if (!layoutConfig) signalMiss(normalizedFormat);
|
||||
|
||||
if (!layoutConfig) {
|
||||
// Fallback auf a4
|
||||
return {
|
||||
marginTopPx: mmToPx(FORMAT_LAYOUTS.a4.marginTopMm),
|
||||
marginLeftPx: mmToPx(FORMAT_LAYOUTS.a4.marginLeftMm),
|
||||
lineHeightPx: FONT_SIZE_PX * FORMAT_LAYOUTS.a4.lineHeightFactor,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
marginTopPx: mmToPx(layoutConfig.marginTopMm),
|
||||
marginLeftPx: mmToPx(layoutConfig.marginLeftMm),
|
||||
marginRightPx: layoutConfig.marginRightMm ? mmToPx(layoutConfig.marginRightMm) : null,
|
||||
lineHeightPx: FONT_SIZE_PX * layoutConfig.lineHeightFactor,
|
||||
};
|
||||
}
|
||||
|
||||
// Seiten-Dimensionen holen
|
||||
function getPageDimensions(format) {
|
||||
const normalizedFormat = String(format).toLowerCase();
|
||||
if (!PAGE_FORMATS[normalizedFormat]) signalMiss(normalizedFormat);
|
||||
const dimensions = PAGE_FORMATS[normalizedFormat] || PAGE_FORMATS.a4;
|
||||
|
||||
return {
|
||||
widthMm: dimensions.widthMm,
|
||||
heightMm: dimensions.heightMm,
|
||||
widthPx: mmToPx(dimensions.widthMm),
|
||||
heightPx: mmToPx(dimensions.heightMm),
|
||||
};
|
||||
}
|
||||
|
||||
// XML Escaping
|
||||
function escapeXml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// Zeilenlimit für Format holen
|
||||
function getLineLimit(format) {
|
||||
const normalizedFormat = String(format).toLowerCase();
|
||||
if (!LINE_LIMITS[normalizedFormat]) signalMiss(normalizedFormat);
|
||||
return LINE_LIMITS[normalizedFormat] || LINE_LIMITS.a4;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PX_PER_MM,
|
||||
FONT_SIZE_PX,
|
||||
mmToPx,
|
||||
getLayoutForFormat,
|
||||
getPageDimensions,
|
||||
getLineLimit,
|
||||
escapeXml,
|
||||
applyRenderFormats,
|
||||
setFormatMissHandler,
|
||||
};
|
||||
318
src/lib/svg-font-engine.js
Normal file
318
src/lib/svg-font-engine.js
Normal file
@@ -0,0 +1,318 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const config = require('../config');
|
||||
|
||||
// Cache je Fontdatei
|
||||
const FONT_CACHE = {};
|
||||
|
||||
// Attribut aus einem Tag lesen (mit Wortgrenze, um z.B. 'd' vs 'id' zu unterscheiden)
|
||||
function getAttr(tag, name) {
|
||||
const re = new RegExp(`\\b${name}="([^"]*)"`);
|
||||
const m = tag.match(re);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
// XML-Entities im unicode-Attribut dekodieren (z.B. < → <, & → &, " → ")
|
||||
function decodeXmlEntities(str) {
|
||||
return str
|
||||
.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
|
||||
.replace(/&#([0-9]+);/g, (_, dec) => String.fromCodePoint(parseInt(dec, 10)))
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
// SVG-Font parsen und Metriken plus Glyphen extrahieren
|
||||
function parseSvgFont(fontFileName) {
|
||||
if (FONT_CACHE[fontFileName]) return FONT_CACHE[fontFileName];
|
||||
|
||||
const fontPath = path.join(config.paths.fonts, fontFileName);
|
||||
const svg = fs.readFileSync(fontPath, 'utf8');
|
||||
|
||||
const fontFaceMatch = svg.match(/<font-face[\s\S]*?>/);
|
||||
if (!fontFaceMatch) {
|
||||
throw new Error(`Kein <font-face> in ${fontFileName} gefunden`);
|
||||
}
|
||||
|
||||
const fontFaceTag = fontFaceMatch[0];
|
||||
const unitsPerEm = parseFloat(getAttr(fontFaceTag, 'units-per-em') || '1000');
|
||||
const ascent = parseFloat(getAttr(fontFaceTag, 'ascent') || '0');
|
||||
const descent = parseFloat(getAttr(fontFaceTag, 'descent') || '0');
|
||||
|
||||
const glyphRegex = /<glyph[\s\S]*?\/>/g;
|
||||
const glyphs = {};
|
||||
let m;
|
||||
|
||||
while ((m = glyphRegex.exec(svg)) !== null) {
|
||||
const tag = m[0];
|
||||
const unicode = decodeXmlEntities(getAttr(tag, 'unicode') || '');
|
||||
const d = getAttr(tag, 'd');
|
||||
const adv = parseFloat(getAttr(tag, 'horiz-adv-x') || '0');
|
||||
|
||||
if (!unicode || !d) continue;
|
||||
|
||||
glyphs[unicode] = {
|
||||
d,
|
||||
adv,
|
||||
};
|
||||
}
|
||||
|
||||
const fontData = {
|
||||
unitsPerEm,
|
||||
ascent,
|
||||
descent,
|
||||
glyphs,
|
||||
};
|
||||
|
||||
FONT_CACHE[fontFileName] = fontData;
|
||||
return fontData;
|
||||
}
|
||||
|
||||
// Zeichen, das nach der Scriptalisierung als Tabulator-Marker eingebettet wird (Unicode PUA)
|
||||
const TAB_MARKER = '';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Breite einer Textzeile in Pixeln messen.
|
||||
* Unterstützt TAB_MARKER: springt zur nächsten Tabstop-Position (6 × fontSizePx).
|
||||
* maxWidthPx (optional) begrenzt den Tab-Sprung auf den rechten Rand, damit viele
|
||||
* Tabs nicht über die Seite hinauslaufen. Ohne Angabe (Infinity) unverändert.
|
||||
*/
|
||||
function measureTextWidthPx({ text, fontFileName, fontSizePx, maxWidthPx = Infinity }) {
|
||||
const { unitsPerEm, glyphs } = parseSvgFont(fontFileName);
|
||||
const scale = fontSizePx / unitsPerEm;
|
||||
const tabStopPx = fontSizePx * 6;
|
||||
|
||||
let x = 0;
|
||||
|
||||
for (const ch of String(text || '')) {
|
||||
if (ch === TAB_MARKER) {
|
||||
x = Math.min(Math.ceil((x + 1) / tabStopPx) * tabStopPx, maxWidthPx);
|
||||
continue;
|
||||
}
|
||||
|
||||
const glyph = glyphs[ch];
|
||||
|
||||
if (!glyph) {
|
||||
// Fallback für Leerzeichen / unbekannte Zeichen
|
||||
const spacePx = fontSizePx * 0.4;
|
||||
x += spacePx;
|
||||
continue;
|
||||
}
|
||||
|
||||
const advPx = (glyph.adv || unitsPerEm * 0.5) * scale;
|
||||
x += advPx;
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Text nach verfügbarer Breite umbrechen.
|
||||
* Garantiert: keine Zeile wird breiter als maxWidthPx.
|
||||
* Unterstützt TAB_MARKER als Tabulator-Sprung innerhalb einer Zeile.
|
||||
*/
|
||||
function wrapTextToLinesByWidth({
|
||||
text,
|
||||
maxWidthPx,
|
||||
fontFileName,
|
||||
fontSizePx,
|
||||
}) {
|
||||
const paragraphs = String(text || '').split(/\r?\n/);
|
||||
const allLines = [];
|
||||
|
||||
const measure = (t) =>
|
||||
measureTextWidthPx({ text: t, fontFileName, fontSizePx });
|
||||
|
||||
for (const para of paragraphs) {
|
||||
// Führende Tabs = bewusste Positionierung der Zeile (z.B. Datum nach rechts).
|
||||
// Solche Zeilen NICHT nach Wortbreite umbrechen, sonst würde der Text als
|
||||
// "zu breit" gewertet und die Wörter fielen nach links auf eine neue Zeile.
|
||||
// Der eigentliche Versatz (bzw. Rechtsbündigkeit bei Überlauf) passiert im Layout.
|
||||
const lead = para.match(new RegExp(`^${TAB_MARKER}+`));
|
||||
if (lead) {
|
||||
const rest = para.slice(lead[0].length);
|
||||
if (!rest.includes(TAB_MARKER) && measure(rest) <= maxWidthPx) {
|
||||
allLines.push(para);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Tokens: Wörter und TAB_MARKER getrennt ermitteln.
|
||||
// TAB_MARKER durch einen Platzhalter ersetzen, mit \s+ splitten, dann zurücktauschen.
|
||||
const TAB_PLACEHOLDER = '';
|
||||
const normalizedPara = para.split(TAB_MARKER).join(` ${TAB_PLACEHOLDER} `);
|
||||
const rawWords = normalizedPara.split(/\s+/).filter(Boolean);
|
||||
const tokens = rawWords.map(w => (w === TAB_PLACEHOLDER ? TAB_MARKER : w));
|
||||
|
||||
if (tokens.length === 0) {
|
||||
allLines.push('');
|
||||
continue;
|
||||
}
|
||||
|
||||
let currentLine = '';
|
||||
let afterTab = false;
|
||||
|
||||
for (const token of tokens) {
|
||||
if (token === TAB_MARKER) {
|
||||
currentLine += TAB_MARKER;
|
||||
afterTab = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Wort alleine zu breit → Zeichenweise brechen
|
||||
if (measure(token) > maxWidthPx) {
|
||||
if (currentLine) {
|
||||
allLines.push(currentLine);
|
||||
currentLine = '';
|
||||
afterTab = false;
|
||||
}
|
||||
|
||||
let buf = '';
|
||||
for (const ch of token) {
|
||||
const candidate = buf + ch;
|
||||
if (measure(candidate) > maxWidthPx && buf) {
|
||||
allLines.push(buf);
|
||||
buf = ch;
|
||||
} else {
|
||||
buf = candidate;
|
||||
}
|
||||
}
|
||||
if (buf) { currentLine = buf; afterTab = false; }
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!currentLine) {
|
||||
currentLine = token;
|
||||
afterTab = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Nach einem Tab kein Leerzeichen als Trenner einfügen
|
||||
const sep = afterTab ? '' : ' ';
|
||||
const candidate = `${currentLine}${sep}${token}`;
|
||||
if (measure(candidate) <= maxWidthPx) {
|
||||
currentLine = candidate;
|
||||
afterTab = false;
|
||||
} else {
|
||||
allLines.push(currentLine);
|
||||
currentLine = token;
|
||||
afterTab = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLine) {
|
||||
allLines.push(currentLine);
|
||||
}
|
||||
}
|
||||
|
||||
return allLines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Textzeilen in Pfade mit Transform-Matrix umwandeln.
|
||||
*/
|
||||
function layoutTextToPaths({
|
||||
lines,
|
||||
fontFileName,
|
||||
fontSizePx,
|
||||
startX,
|
||||
startY,
|
||||
lineHeightPx,
|
||||
realisticHandwriting = false,
|
||||
maxWidthPx = Infinity,
|
||||
}) {
|
||||
const { unitsPerEm, glyphs } = parseSvgFont(fontFileName);
|
||||
|
||||
const scale = fontSizePx / unitsPerEm;
|
||||
|
||||
const resultPaths = [];
|
||||
let baselineY = startY;
|
||||
|
||||
for (const line of lines) {
|
||||
let x = startX;
|
||||
let drift = 0;
|
||||
const lineSlope = realisticHandwriting ? (Math.random() - 0.5) * 0.01 : 0;
|
||||
|
||||
const tabStopPx = fontSizePx * 6;
|
||||
|
||||
// Führende Tabs vorab auflösen: normalerweise an die Tab-Position rücken;
|
||||
// würde der restliche Zeileninhalt dort über den rechten Rand laufen, die
|
||||
// Zeile stattdessen rechtsbündig an den Rand setzen (z.B. Datum ganz rechts,
|
||||
// ohne dass etwas daneben steht). Nur aktiv, wenn maxWidthPx bekannt ist.
|
||||
let startIdx = 0;
|
||||
if (line[0] === TAB_MARKER) {
|
||||
let leadCount = 0;
|
||||
while (line[leadCount] === TAB_MARKER) leadCount++;
|
||||
let tx = 0;
|
||||
for (let t = 0; t < leadCount; t++) {
|
||||
tx = Math.min(Math.ceil((tx + 1) / tabStopPx) * tabStopPx, maxWidthPx);
|
||||
}
|
||||
const rest = line.slice(leadCount);
|
||||
const restW = measureTextWidthPx({ text: rest, fontFileName, fontSizePx, maxWidthPx });
|
||||
if (tx + restW > maxWidthPx) tx = Math.max(0, maxWidthPx - restW);
|
||||
x = startX + tx;
|
||||
startIdx = leadCount;
|
||||
}
|
||||
|
||||
for (let i = startIdx; i < line.length; i++) {
|
||||
const ch = line[i];
|
||||
|
||||
// Tabulator-Marker → zur nächsten Tabstop-Position springen (an den Rand geclampt)
|
||||
if (ch === TAB_MARKER) {
|
||||
const relX = x - startX;
|
||||
const nextTab = Math.min(Math.ceil((relX + 1) / tabStopPx) * tabStopPx, maxWidthPx);
|
||||
x = startX + nextTab;
|
||||
continue;
|
||||
}
|
||||
|
||||
const glyph = glyphs[ch];
|
||||
|
||||
if (!glyph) {
|
||||
// Leerzeichen mit leicht variierender Breite
|
||||
const spacePx = fontSizePx * 0.4 * (realisticHandwriting ? (1 + (Math.random() - 0.5) * 0.08) : 1);
|
||||
x += spacePx;
|
||||
if (realisticHandwriting) {
|
||||
drift += (Math.random() - 0.5) * 0.3;
|
||||
drift = Math.max(-3, Math.min(3, drift));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const d = glyph.d;
|
||||
const advPx = (glyph.adv || unitsPerEm * 0.5) * scale;
|
||||
|
||||
const yJitter = realisticHandwriting ? (Math.random() - 0.5) * 2.5 : 0;
|
||||
if (realisticHandwriting) {
|
||||
drift += (Math.random() - 0.5) * 0.4;
|
||||
drift = Math.max(-3, Math.min(3, drift));
|
||||
}
|
||||
|
||||
const charY = baselineY + yJitter + drift + lineSlope * (x - startX);
|
||||
|
||||
const angleDeg = realisticHandwriting ? 5 + (Math.random() - 0.5) * 2 : 0;
|
||||
const pivotX = x + advPx / 2;
|
||||
const pivotY = charY - fontSizePx * 0.3;
|
||||
|
||||
const transform = `rotate(${angleDeg.toFixed(3)},${pivotX.toFixed(1)},${pivotY.toFixed(1)}) matrix(${scale},0,0,${-scale},${x},${charY})`;
|
||||
|
||||
resultPaths.push({ d, transform });
|
||||
|
||||
x += advPx;
|
||||
}
|
||||
|
||||
baselineY += lineHeightPx;
|
||||
}
|
||||
|
||||
return resultPaths;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TAB_MARKER,
|
||||
measureTextWidthPx,
|
||||
wrapTextToLinesByWidth,
|
||||
layoutTextToPaths
|
||||
};
|
||||
461
src/lib/svg-generator.js
Normal file
461
src/lib/svg-generator.js
Normal file
@@ -0,0 +1,461 @@
|
||||
const {
|
||||
FONT_SIZE_PX,
|
||||
getLayoutForFormat,
|
||||
getPageDimensions,
|
||||
getLineLimit,
|
||||
escapeXml,
|
||||
mmToPx
|
||||
} = require('./page-layout');
|
||||
|
||||
const {
|
||||
layoutTextToPaths,
|
||||
wrapTextToLinesByWidth,
|
||||
measureTextWidthPx,
|
||||
TAB_MARKER
|
||||
} = require('./svg-font-engine');
|
||||
|
||||
// Höhe einer Signatur in Seiten-Pixeln (Signatur-Canvas war 600×160; wir reservieren 160px * scale)
|
||||
const SIG_CANVAS_W = 600;
|
||||
const SIG_CANVAS_H = 160;
|
||||
|
||||
/**
|
||||
* Extrahiert Path- und Polyline-Elemente aus einem SVG-String und gibt sie als
|
||||
* umgeformte <g>-Gruppe zurück, die an Position (x, y) mit Skalierung scale eingebettet ist.
|
||||
*/
|
||||
function buildSignatureElement(svgString, x, y, scale) {
|
||||
if (!svgString || typeof svgString !== 'string') return '';
|
||||
|
||||
// Nur <path>-Elemente extrahieren (unsere Signatur-SVGs enthalten ausschließlich Paths)
|
||||
const pathRegex = /<path\b([^/]*)\/>/gi;
|
||||
const elements = [];
|
||||
let m;
|
||||
while ((m = pathRegex.exec(svgString)) !== null) {
|
||||
// Stroke-Farbe auf Druckfarbe setzen, stroke-width relativ zur Skalierung anpassen
|
||||
const attrs = m[1]
|
||||
.replace(/stroke="[^"]*"/i, 'stroke="#000000"')
|
||||
.replace(/stroke-width="[^"]*"/i, `stroke-width="${(2.5 / scale).toFixed(2)}"`);
|
||||
elements.push(`<path${attrs}/>`);
|
||||
}
|
||||
if (!elements.length) return '';
|
||||
|
||||
return `<g transform="translate(${x.toFixed(1)}, ${y.toFixed(1)}) scale(${scale.toFixed(4)})">
|
||||
${elements.join('\n ')}
|
||||
</g>`;
|
||||
}
|
||||
|
||||
// Mapping der Handschriften auf SVG-Font-Dateien
|
||||
const SVG_FONT_CONFIG = {
|
||||
tilda: { file: 'tilda.svg' },
|
||||
alva: { file: 'alva.svg' },
|
||||
ellie: { file: 'ellie.svg' },
|
||||
};
|
||||
|
||||
function normalizeFontKey(font) {
|
||||
if (!font) return 'tilda';
|
||||
const f = String(font).toLowerCase();
|
||||
if (['tilda', 'alva', 'ellie'].includes(f)) return f;
|
||||
return 'tilda';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generiert ein Schriftstück (Brief/Postkarte) als SVG
|
||||
* @param {string} text - Der scriptalisierte Text
|
||||
* @param {string} format - Format: a4, a6p, a6l
|
||||
* @param {object} options - { font: 'tilda', alignment: 'left' }
|
||||
*/
|
||||
function generateLetterSVG(text, format, options = {}) {
|
||||
const fontKey = normalizeFontKey(options.font);
|
||||
const fontConfig = SVG_FONT_CONFIG[fontKey];
|
||||
const signatures = options.signatures || {};
|
||||
// Feinjustierung je Signatur: { signatur1: { x: mm, y: mm, scale: Faktor } }.
|
||||
const signatureOffsets = options.signatureOffsets || {};
|
||||
// Einseitig: Seitenumbruch-Marker gibt es hier nicht – als Zeilenumbruch behandeln,
|
||||
// damit er nie wörtlich gedruckt wird (falls „Mehrseitig" nicht aktiv ist).
|
||||
text = String(text || '').replace(/\[\[seitenumbruch\]\]/gi, '\n');
|
||||
|
||||
const { widthPx, heightPx, widthMm, heightMm } = getPageDimensions(format);
|
||||
const { marginTopPx, marginLeftPx, marginRightPx, lineHeightPx: baseLineHeightPx } = getLayoutForFormat(format);
|
||||
const maxWidthPx = widthPx - marginLeftPx - (marginRightPx ?? marginLeftPx);
|
||||
|
||||
// Relative Schriftgröße (nur manuelle Aufträge setzen ≠ 1). Schrift UND Zeilenhöhe
|
||||
// skalieren mit, damit sich Zeilen nicht überlappen. Default 1 = unverändert.
|
||||
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
||||
const fontSizePx = FONT_SIZE_PX * fontScale;
|
||||
const lineHeightPx = baseLineHeightPx * fontScale;
|
||||
|
||||
// ── Signatur-Marker aus Text extrahieren ──────────────────────────────────
|
||||
const sigMarkerRe = /\[\[(signatur\d+)\]\]/gi;
|
||||
const hasSigMarkers = sigMarkerRe.test(String(text || ''));
|
||||
|
||||
if (!hasSigMarkers) {
|
||||
// ── Standard-Pfad (ohne Signaturen) ──────────────────────────────────────
|
||||
const lines = wrapTextToLinesByWidth({
|
||||
text: String(text || ''),
|
||||
maxWidthPx,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
});
|
||||
|
||||
const firstBaselineY = marginTopPx + fontSizePx;
|
||||
const paths = layoutTextToPaths({
|
||||
lines,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
startX: marginLeftPx,
|
||||
startY: firstBaselineY,
|
||||
lineHeightPx,
|
||||
realisticHandwriting: options.realisticHandwriting ?? false,
|
||||
maxWidthPx,
|
||||
});
|
||||
|
||||
const pathElements = paths
|
||||
.map(p => `<path d="${escapeXml(p.d)}"
|
||||
transform="${p.transform}"
|
||||
stroke="#000000" stroke-width="0.6" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"
|
||||
vector-effect="non-scaling-stroke"/>`)
|
||||
.join('\n ');
|
||||
|
||||
// Größere Schrift → weniger Zeilen passen aufs Blatt (Limit gegenläufig skalieren).
|
||||
const lineLimit = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
||||
return {
|
||||
svg: `<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="${widthMm}mm" height="${heightMm}mm"
|
||||
viewBox="0 0 ${widthPx} ${heightPx}">
|
||||
<rect x="0" y="0" width="${widthPx}" height="${heightPx}" fill="#FFFFFF"/>
|
||||
${pathElements}
|
||||
</svg>`.trim(),
|
||||
lineCount: lines.length,
|
||||
lineLimit,
|
||||
overflow: lines.length > lineLimit,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Pfad mit Signaturen: Text in Segmente aufteilen ───────────────────────
|
||||
// Jede Signatur-Zeile ist 2 Zeilen hoch; bis zu 3 Signaturen nebeneinander.
|
||||
const sigHeightPx = 2 * lineHeightPx;
|
||||
const sigSlotW = maxWidthPx / 3; // Breite pro Signatur-Slot
|
||||
const sigScaleH = sigHeightPx / SIG_CANVAS_H;
|
||||
const sigScaleW = sigSlotW / SIG_CANVAS_W;
|
||||
const sigScale = Math.min(sigScaleH, sigScaleW); // gleichmäßig skalieren
|
||||
const sigPaddingPx = lineHeightPx * 0.3; // kleiner Abstand ober/unterhalb
|
||||
|
||||
const rawText = String(text || '');
|
||||
const segments = [];
|
||||
sigMarkerRe.lastIndex = 0;
|
||||
let lastEnd = 0;
|
||||
let matchSig;
|
||||
while ((matchSig = sigMarkerRe.exec(rawText)) !== null) {
|
||||
if (matchSig.index > lastEnd) {
|
||||
segments.push({ type: 'text', content: rawText.slice(lastEnd, matchSig.index) });
|
||||
}
|
||||
segments.push({ type: 'sig', key: matchSig[1].toLowerCase() });
|
||||
lastEnd = matchSig.index + matchSig[0].length;
|
||||
}
|
||||
if (lastEnd < rawText.length) {
|
||||
segments.push({ type: 'text', content: rawText.slice(lastEnd) });
|
||||
}
|
||||
|
||||
const allSvgElements = [];
|
||||
let currentY = marginTopPx + fontSizePx;
|
||||
let totalLineCount = 0;
|
||||
const lineLimit = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
||||
|
||||
let si = 0;
|
||||
while (si < segments.length) {
|
||||
const seg = segments[si];
|
||||
|
||||
if (seg.type === 'text') {
|
||||
const trimmed = seg.content.replace(/^\n+/, '').replace(/\n+$/, '');
|
||||
if (!trimmed) { si++; continue; }
|
||||
const lines = wrapTextToLinesByWidth({
|
||||
text: seg.content,
|
||||
maxWidthPx,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
});
|
||||
const paths = layoutTextToPaths({
|
||||
lines,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
startX: marginLeftPx,
|
||||
startY: currentY,
|
||||
lineHeightPx,
|
||||
realisticHandwriting: options.realisticHandwriting ?? false,
|
||||
maxWidthPx,
|
||||
});
|
||||
paths.forEach(p => allSvgElements.push(
|
||||
`<path d="${escapeXml(p.d)}" transform="${p.transform}"
|
||||
stroke="#000000" stroke-width="0.6" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"
|
||||
vector-effect="non-scaling-stroke"/>`
|
||||
));
|
||||
currentY += lines.length * lineHeightPx;
|
||||
totalLineCount += lines.length;
|
||||
si++;
|
||||
} else {
|
||||
// Aufeinanderfolgende Signaturen als Zeile nebeneinander rendern
|
||||
const sigRow = [];
|
||||
while (si < segments.length && segments[si].type === 'sig') {
|
||||
sigRow.push(segments[si]);
|
||||
si++;
|
||||
}
|
||||
currentY += sigPaddingPx;
|
||||
sigRow.forEach((sigSeg, slotIdx) => {
|
||||
const svgString = signatures[sigSeg.key] || null;
|
||||
if (svgString) {
|
||||
// Feinjustierung: Versatz in mm + Größen-Faktor relativ zur Auto-Position.
|
||||
const off = signatureOffsets[sigSeg.key] || {};
|
||||
const dx = mmToPx(Number(off.x) || 0);
|
||||
const dy = mmToPx(Number(off.y) || 0);
|
||||
const sc = Number(off.scale) > 0 ? Number(off.scale) : 1;
|
||||
const sigX = marginLeftPx + slotIdx * sigSlotW + dx;
|
||||
const sigEl = buildSignatureElement(svgString, sigX, currentY + dy, sigScale * sc);
|
||||
if (sigEl) allSvgElements.push(sigEl);
|
||||
}
|
||||
});
|
||||
currentY += sigHeightPx + sigPaddingPx;
|
||||
totalLineCount += 2; // ganze Zeile zählt als 2 Zeilen, unabhängig von Anzahl
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
svg: `<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="${widthMm}mm" height="${heightMm}mm"
|
||||
viewBox="0 0 ${widthPx} ${heightPx}">
|
||||
<rect x="0" y="0" width="${widthPx}" height="${heightPx}" fill="#FFFFFF"/>
|
||||
${allSvgElements.join('\n ')}
|
||||
</svg>`.trim(),
|
||||
lineCount: totalLineCount,
|
||||
lineLimit,
|
||||
overflow: totalLineCount > lineLimit,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generiert einen Umschlag als SVG
|
||||
* @param {string} text - Der scriptalisierte Text
|
||||
* @param {string} format - Format: c6, din_lang
|
||||
* @param {string} type - Typ: 'recipient' (links), 'free' (links, freie Adresse), 'custom' (mittig)
|
||||
* @param {object} options - { font: 'tilda' }
|
||||
*/
|
||||
function generateEnvelopeSVG(text, format, type, options = {}) {
|
||||
const fontKey = normalizeFontKey(options.font);
|
||||
const fontConfig = SVG_FONT_CONFIG[fontKey];
|
||||
|
||||
const { widthPx, heightPx, widthMm, heightMm } = getPageDimensions(format);
|
||||
const { marginTopPx, marginLeftPx, lineHeightPx: baseLineHeightPx } = getLayoutForFormat(format);
|
||||
|
||||
// Relative Schriftgröße (getrennt vom Brief einstellbar). Default 1 = unverändert.
|
||||
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
||||
const fontSizePx = FONT_SIZE_PX * fontScale;
|
||||
const lineHeightPx = baseLineHeightPx * fontScale;
|
||||
|
||||
let lines;
|
||||
let startX;
|
||||
let startY;
|
||||
|
||||
if (type === 'custom') {
|
||||
// Mittig zentriert, 70% der Umschlagsbreite
|
||||
const maxWidthPx = widthPx * 0.7;
|
||||
|
||||
lines = wrapTextToLinesByWidth({
|
||||
text: String(text || ''),
|
||||
maxWidthPx,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
});
|
||||
|
||||
// Zentrierung berechnen
|
||||
const totalTextHeight = lines.length * lineHeightPx;
|
||||
startY = (heightPx - totalTextHeight) / 2 + fontSizePx;
|
||||
|
||||
// Jede Zeile einzeln zentrieren
|
||||
// startX wird später pro Zeile berechnet
|
||||
startX = 0; // Dummy-Wert, wird für jede Zeile überschrieben
|
||||
|
||||
} else {
|
||||
// type === 'recipient' / 'free': Links, max. 60% der Umschlagsbreite
|
||||
const maxWidthPx = Math.min(widthPx - marginLeftPx - 20, widthPx * 0.6);
|
||||
|
||||
lines = wrapTextToLinesByWidth({
|
||||
text: String(text || ''),
|
||||
maxWidthPx,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
});
|
||||
|
||||
startX = marginLeftPx;
|
||||
startY = marginTopPx + fontSizePx;
|
||||
}
|
||||
|
||||
let paths = [];
|
||||
|
||||
if (type === 'custom') {
|
||||
// Bei custom type: Jede Zeile einzeln zentrieren
|
||||
let currentY = startY;
|
||||
for (const line of lines) {
|
||||
const lineWidth = measureTextWidthPx({
|
||||
text: line,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx
|
||||
});
|
||||
const centeredX = (widthPx - lineWidth) / 2;
|
||||
|
||||
const linePaths = layoutTextToPaths({
|
||||
lines: [line],
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
startX: centeredX,
|
||||
startY: currentY,
|
||||
lineHeightPx,
|
||||
realisticHandwriting: options.realisticHandwriting ?? false,
|
||||
});
|
||||
|
||||
paths.push(...linePaths);
|
||||
currentY += lineHeightPx;
|
||||
}
|
||||
} else {
|
||||
// Bei recipient type: Normal links ausrichten
|
||||
paths = layoutTextToPaths({
|
||||
lines,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
startX,
|
||||
startY,
|
||||
lineHeightPx,
|
||||
realisticHandwriting: options.realisticHandwriting ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
const pathElements = paths
|
||||
.map(
|
||||
(p) => `<path d="${escapeXml(p.d)}"
|
||||
transform="${p.transform}"
|
||||
stroke="#000000"
|
||||
stroke-width="0.6"
|
||||
fill="none"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
vector-effect="non-scaling-stroke"
|
||||
/>`
|
||||
)
|
||||
.join('\n ');
|
||||
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="${widthMm}mm"
|
||||
height="${heightMm}mm"
|
||||
viewBox="0 0 ${widthPx} ${heightPx}">
|
||||
<rect x="0" y="0" width="${widthPx}" height="${heightPx}" fill="#FFFFFF" />
|
||||
${pathElements}
|
||||
</svg>`;
|
||||
|
||||
// Overflow-Erkennung: zu viele Zeilen für die verfügbare Fläche
|
||||
const overflowStartY = (type === 'custom')
|
||||
? (heightPx - lines.length * lineHeightPx) / 2 + fontSizePx
|
||||
: marginTopPx + fontSizePx;
|
||||
const available = heightPx - overflowStartY - fontSizePx * 0.5;
|
||||
const lineLimit = Math.max(1, Math.floor(available / lineHeightPx) + 1);
|
||||
const lineCount = lines.length;
|
||||
|
||||
return { svg: svg.trim(), overflow: lineCount > lineLimit, lineCount, lineLimit };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mehrseitiges Schriftstück: Der Text fließt automatisch über so viele Seiten,
|
||||
* wie nötig (linesPerPage = Zeilenlimit des Formats). Ein erzwungener Umbruch ist
|
||||
* über den Marker [[seitenumbruch]] möglich – jeder so getrennte Block beginnt auf
|
||||
* einer neuen Seite. Gibt die Seiten in natürlicher Reihenfolge (Seite 1..N) zurück.
|
||||
*
|
||||
* Bewusst OHNE Signatur-Unterstützung (kommt als eigener Schritt). Tab-/Rechts-
|
||||
* bündig-Logik und relative Schriftgröße greifen pro Seite wie beim Einzelbrief.
|
||||
*/
|
||||
function generateLetterPages(text, format, options = {}) {
|
||||
const fontKey = normalizeFontKey(options.font);
|
||||
const fontConfig = SVG_FONT_CONFIG[fontKey];
|
||||
|
||||
const { widthPx, heightPx, widthMm, heightMm } = getPageDimensions(format);
|
||||
const { marginTopPx, marginLeftPx, marginRightPx, lineHeightPx: baseLineHeightPx } = getLayoutForFormat(format);
|
||||
const maxWidthPx = widthPx - marginLeftPx - (marginRightPx ?? marginLeftPx);
|
||||
|
||||
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
||||
const fontSizePx = FONT_SIZE_PX * fontScale;
|
||||
const lineHeightPx = baseLineHeightPx * fontScale;
|
||||
const linesPerPage = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
||||
|
||||
// Erzwungene Seitenumbrüche zuerst; danach jeden Block nach Zeilen auto-fließen.
|
||||
const bloecke = String(text || '').split(/\[\[seitenumbruch\]\]/gi);
|
||||
const seitenZeilen = [];
|
||||
for (const block of bloecke) {
|
||||
const lines = wrapTextToLinesByWidth({ text: block, maxWidthPx, fontFileName: fontConfig.file, fontSizePx });
|
||||
for (let i = 0; i < lines.length; i += linesPerPage) {
|
||||
seitenZeilen.push(lines.slice(i, i + linesPerPage));
|
||||
}
|
||||
}
|
||||
if (seitenZeilen.length === 0) seitenZeilen.push(['']);
|
||||
|
||||
// Leere Seiten verwerfen: enthält eine Seite kein sichtbares Zeichen (nur
|
||||
// Leerzeichen, Tabs, Umbrüche), wird sie weder generiert noch gedruckt.
|
||||
// Bleibt nichts übrig (komplett leerer Text), eine einzige Seite behalten.
|
||||
const istLeer = (lines) => lines.join('').split(TAB_MARKER).join('').replace(/\s/g, '') === '';
|
||||
let seiten = seitenZeilen.filter((lines) => !istLeer(lines));
|
||||
if (seiten.length === 0) seiten = [['']];
|
||||
|
||||
const pages = seiten.map((lines) => {
|
||||
const paths = layoutTextToPaths({
|
||||
lines,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
startX: marginLeftPx,
|
||||
startY: marginTopPx + fontSizePx,
|
||||
lineHeightPx,
|
||||
realisticHandwriting: options.realisticHandwriting ?? false,
|
||||
maxWidthPx,
|
||||
});
|
||||
const pathElements = paths
|
||||
.map(p => `<path d="${escapeXml(p.d)}"
|
||||
transform="${p.transform}"
|
||||
stroke="#000000" stroke-width="0.6" fill="none"
|
||||
stroke-linecap="round" stroke-linejoin="round"
|
||||
vector-effect="non-scaling-stroke"/>`)
|
||||
.join('\n ');
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="${widthMm}mm" height="${heightMm}mm"
|
||||
viewBox="0 0 ${widthPx} ${heightPx}">
|
||||
<rect x="0" y="0" width="${widthPx}" height="${heightPx}" fill="#FFFFFF"/>
|
||||
${pathElements}
|
||||
</svg>`.trim();
|
||||
});
|
||||
|
||||
return { pages, pageCount: pages.length, lineCount: seiten.reduce((a, l) => a + l.length, 0) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Zählt, wie viele Seiten ein Text ergäbe (gleiche Logik wie generateLetterPages,
|
||||
* aber ohne SVG/Scriptalizer) – für die Seiten-Übersicht je Schriftstück.
|
||||
*/
|
||||
function countLetterPages(text, format, options = {}) {
|
||||
const fontConfig = SVG_FONT_CONFIG[normalizeFontKey(options.font)];
|
||||
const { widthPx } = getPageDimensions(format);
|
||||
const { marginLeftPx, marginRightPx } = getLayoutForFormat(format);
|
||||
const maxWidthPx = widthPx - marginLeftPx - (marginRightPx ?? marginLeftPx);
|
||||
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
||||
const fontSizePx = FONT_SIZE_PX * fontScale;
|
||||
const linesPerPage = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
||||
|
||||
const seitenZeilen = [];
|
||||
for (const block of String(text || '').split(/\[\[seitenumbruch\]\]/gi)) {
|
||||
const lines = wrapTextToLinesByWidth({ text: block, maxWidthPx, fontFileName: fontConfig.file, fontSizePx });
|
||||
for (let i = 0; i < lines.length; i += linesPerPage) seitenZeilen.push(lines.slice(i, i + linesPerPage));
|
||||
}
|
||||
const istLeer = (lines) => lines.join('').split(TAB_MARKER).join('').replace(/\s/g, '') === '';
|
||||
const seiten = seitenZeilen.filter((lines) => !istLeer(lines));
|
||||
return Math.max(1, seiten.length);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateLetterSVG,
|
||||
generateEnvelopeSVG,
|
||||
generateLetterPages,
|
||||
countLetterPages
|
||||
};
|
||||
Reference in New Issue
Block a user