feat(print): styled PDF export and printouts with branded header, real tables and podium marks (1.72.0)
This commit is contained in:
1 parent
c4375daa93
commit
7c25f23ad0
8 files changed
+504
-372
No files matched your search
@@ -12,6 +12,7 @@ const { createAuth, COOKIE_NAME: AUTH_COOKIE_NAME, TOKEN_MAX_AGE_MS } = require(
|
||||
const { createTts, resolvePiperBinary } = require("./server/tts");
|
||||
const { installAll: installPiperAll, VOICES: PIPER_VOICES } = require("./server/tts_install");
|
||||
const { createDecoderSimulator } = require("./server/decoder_sim");
|
||||
const { buildStyledPdf } = require("./server/pdf_render");
|
||||
|
||||
const PORT = Number(process.env.PORT || 8081);
|
||||
const HOST = process.env.HOST || "0.0.0.0";
|
||||
@@ -600,7 +601,7 @@ app.post("/api/passings/purge", (req, res) => {
|
||||
app.post("/api/export/pdf", (req, res) => {
|
||||
try {
|
||||
const payload = normalizePdfExportPayload(req.body || {});
|
||||
const pdf = buildSimplePdf(payload);
|
||||
const pdf = buildStyledPdf(payload);
|
||||
res.setHeader("Content-Type", "application/pdf");
|
||||
res.setHeader("Content-Disposition", `attachment; filename="${payload.filename}"`);
|
||||
res.send(pdf);
|
||||
@@ -860,359 +861,6 @@ function normalizePdfExportPayload(input = {}) {
|
||||
return { title, subtitle, brandName, brandTagline, footer, theme, logoDataUrl, filename, sections };
|
||||
}
|
||||
|
||||
// Wide tables (a series with 12 rounds has 16 columns) don't fit portrait A4 even when
|
||||
// compacted - the page then turns landscape (126 characters per line instead of 86).
|
||||
const PDF_PORTRAIT_CHARS = 86;
|
||||
const PDF_LANDSCAPE_CHARS = 126;
|
||||
function pdfNeedsLandscape(payload) {
|
||||
return payload.sections.some((section) => section.headers.length && getCompactTableWidth(section.headers, section.rows) > PDF_PORTRAIT_CHARS);
|
||||
}
|
||||
|
||||
function buildSimplePdf(payload) {
|
||||
const landscape = pdfNeedsLandscape(payload);
|
||||
const pageWidth = landscape ? 842 : 595;
|
||||
const pageHeight = landscape ? 595 : 842;
|
||||
const marginLeft = 42;
|
||||
const marginTop = 56;
|
||||
const marginBottom = 56;
|
||||
const lineHeight = 15;
|
||||
const maxChars = landscape ? PDF_LANDSCAPE_CHARS : PDF_PORTRAIT_CHARS;
|
||||
const logo = parsePdfLogo(payload.logoDataUrl);
|
||||
const headerOffset = logo ? logo.displayHeight + 18 : 0;
|
||||
const lines = buildPdfLines(payload, maxChars);
|
||||
const linesPerPage = Math.max(10, Math.floor((pageHeight - marginTop - marginBottom - headerOffset) / lineHeight));
|
||||
const pages = [];
|
||||
for (let index = 0; index < lines.length; index += linesPerPage) {
|
||||
pages.push(lines.slice(index, index + linesPerPage));
|
||||
}
|
||||
if (!pages.length) {
|
||||
pages.push(["No content"]);
|
||||
}
|
||||
|
||||
const objects = [];
|
||||
const pageObjectIds = [];
|
||||
const contentObjectIds = [];
|
||||
let nextObjectId = 3;
|
||||
for (let index = 0; index < pages.length; index += 1) {
|
||||
pageObjectIds.push(nextObjectId++);
|
||||
contentObjectIds.push(nextObjectId++);
|
||||
}
|
||||
const fontObjectId = nextObjectId++;
|
||||
const imageObjectId = logo ? nextObjectId++ : null;
|
||||
|
||||
objects.push(createPdfTextObject(1, "<< /Type /Catalog /Pages 2 0 R >>"));
|
||||
objects.push(createPdfTextObject(2, `<< /Type /Pages /Count ${pages.length} /Kids [${pageObjectIds.map((id) => `${id} 0 R`).join(" ")}] >>`));
|
||||
objects.push(createPdfTextObject(fontObjectId, "<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>"));
|
||||
|
||||
if (logo && imageObjectId) {
|
||||
objects.push(
|
||||
createPdfStreamObject(
|
||||
imageObjectId,
|
||||
`<< /Type /XObject /Subtype /Image /Width ${logo.width} /Height ${logo.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode`,
|
||||
logo.data
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
for (let index = 0; index < pages.length; index += 1) {
|
||||
const resources = imageObjectId
|
||||
? `<< /Font << /F1 ${fontObjectId} 0 R >> /XObject << /Im1 ${imageObjectId} 0 R >> >>`
|
||||
: `<< /Font << /F1 ${fontObjectId} 0 R >> >>`;
|
||||
const contentStream = pdfWinAnsiBuffer(
|
||||
buildPdfContentStream(
|
||||
pages[index],
|
||||
marginLeft,
|
||||
pageHeight - marginTop - headerOffset,
|
||||
lineHeight,
|
||||
logo
|
||||
? {
|
||||
x: marginLeft,
|
||||
y: pageHeight - marginTop - logo.displayHeight,
|
||||
width: logo.displayWidth,
|
||||
height: logo.displayHeight,
|
||||
}
|
||||
: null
|
||||
)
|
||||
);
|
||||
objects.push(
|
||||
createPdfTextObject(
|
||||
pageObjectIds[index],
|
||||
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pageWidth} ${pageHeight}] /Resources ${resources} /Contents ${contentObjectIds[index]} 0 R >>`
|
||||
)
|
||||
);
|
||||
objects.push(createPdfStreamObject(contentObjectIds[index], "<<", contentStream));
|
||||
}
|
||||
|
||||
return assemblePdf(objects);
|
||||
}
|
||||
|
||||
function createPdfTextObject(id, body) {
|
||||
return {
|
||||
id,
|
||||
buffer: Buffer.from(`${id} 0 obj\n${body}\nendobj\n`, "binary"),
|
||||
};
|
||||
}
|
||||
|
||||
function createPdfStreamObject(id, dictionaryPrefix, streamBuffer) {
|
||||
return {
|
||||
id,
|
||||
buffer: Buffer.concat([
|
||||
Buffer.from(`${id} 0 obj\n${dictionaryPrefix} /Length ${streamBuffer.length} >>\nstream\n`, "binary"),
|
||||
streamBuffer,
|
||||
Buffer.from("\nendstream\nendobj\n", "binary"),
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
function assemblePdf(objects) {
|
||||
const ordered = [...objects].sort((left, right) => left.id - right.id);
|
||||
const chunks = [Buffer.from("%PDF-1.4\n", "binary")];
|
||||
const offsets = [0];
|
||||
let position = chunks[0].length;
|
||||
ordered.forEach((object) => {
|
||||
offsets[object.id] = position;
|
||||
chunks.push(object.buffer);
|
||||
position += object.buffer.length;
|
||||
});
|
||||
const xrefOffset = position;
|
||||
const size = ordered.length + 1;
|
||||
let xref = `xref\n0 ${size}\n0000000000 65535 f \n`;
|
||||
for (let id = 1; id < size; id += 1) {
|
||||
xref += `${String(offsets[id] || 0).padStart(10, "0")} 00000 n \n`;
|
||||
}
|
||||
chunks.push(Buffer.from(`${xref}trailer\n<< /Size ${size} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF`, "binary"));
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
function parsePdfLogo(dataUrl) {
|
||||
const match = /^data:image\/jpeg;base64,([A-Za-z0-9+/=\s]+)$/i.exec(String(dataUrl || "").trim());
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const data = Buffer.from(match[1].replace(/\s+/g, ""), "base64");
|
||||
const dimensions = getJpegDimensions(data);
|
||||
if (!dimensions) {
|
||||
return null;
|
||||
}
|
||||
const scale = Math.min(150 / dimensions.width, 52 / dimensions.height, 1);
|
||||
return {
|
||||
data,
|
||||
width: dimensions.width,
|
||||
height: dimensions.height,
|
||||
displayWidth: Math.max(1, Math.round(dimensions.width * scale)),
|
||||
displayHeight: Math.max(1, Math.round(dimensions.height * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
function getJpegDimensions(buffer) {
|
||||
if (!Buffer.isBuffer(buffer) || buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) {
|
||||
return null;
|
||||
}
|
||||
let offset = 2;
|
||||
while (offset + 1 < buffer.length) {
|
||||
while (offset < buffer.length && buffer[offset] !== 0xff) {
|
||||
offset += 1;
|
||||
}
|
||||
while (offset < buffer.length && buffer[offset] === 0xff) {
|
||||
offset += 1;
|
||||
}
|
||||
if (offset >= buffer.length) {
|
||||
break;
|
||||
}
|
||||
const marker = buffer[offset];
|
||||
offset += 1;
|
||||
if (marker === 0xd9 || marker === 0xda) {
|
||||
break;
|
||||
}
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
|
||||
continue;
|
||||
}
|
||||
if (offset + 1 >= buffer.length) {
|
||||
break;
|
||||
}
|
||||
const length = buffer.readUInt16BE(offset);
|
||||
if (length < 2 || offset + length > buffer.length) {
|
||||
break;
|
||||
}
|
||||
if (
|
||||
(marker >= 0xc0 && marker <= 0xc3) ||
|
||||
(marker >= 0xc5 && marker <= 0xc7) ||
|
||||
(marker >= 0xc9 && marker <= 0xcb) ||
|
||||
(marker >= 0xcd && marker <= 0xcf)
|
||||
) {
|
||||
if (length >= 7) {
|
||||
return {
|
||||
height: buffer.readUInt16BE(offset + 3),
|
||||
width: buffer.readUInt16BE(offset + 5),
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildPdfLines(payload, maxChars) {
|
||||
const lines = [];
|
||||
const separator =
|
||||
payload.theme === "minimal"
|
||||
? ""
|
||||
: payload.theme === "motorsport"
|
||||
? "=".repeat(Math.min(maxChars, 70))
|
||||
: "-".repeat(Math.min(maxChars, 70));
|
||||
if (payload.brandName) {
|
||||
lines.push(payload.brandName);
|
||||
}
|
||||
if (payload.brandTagline) {
|
||||
lines.push(payload.brandTagline);
|
||||
}
|
||||
if (separator) {
|
||||
lines.push(separator);
|
||||
}
|
||||
if (payload.brandName || payload.brandTagline) {
|
||||
lines.push("");
|
||||
}
|
||||
lines.push(payload.title);
|
||||
if (payload.subtitle) {
|
||||
lines.push(payload.subtitle);
|
||||
}
|
||||
payload.sections.forEach((section) => {
|
||||
lines.push("");
|
||||
if (section.title) {
|
||||
lines.push(payload.theme === "motorsport" ? `> ${section.title}` : section.title);
|
||||
}
|
||||
if (section.headers.length) {
|
||||
const { widths, separator } = getColumnWidths(section.headers, section.rows, maxChars);
|
||||
lines.push(formatPdfRow(section.headers, widths, separator));
|
||||
lines.push(formatPdfRow(widths.map((width) => (payload.theme === "minimal" ? " ".repeat(Math.min(width, 1)) : "-".repeat(Math.min(width, 12)))), widths, separator));
|
||||
section.rows.forEach((row) => {
|
||||
lines.push(formatPdfRow(row, widths, separator));
|
||||
});
|
||||
} else {
|
||||
section.rows.forEach((row) => {
|
||||
row.forEach((value) => {
|
||||
wrapPdfText(value, maxChars).forEach((line) => lines.push(line));
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
if (payload.footer) {
|
||||
lines.push("");
|
||||
lines.push(payload.footer);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
const longestInColumn = (headers, rows, index) => Math.max(String(headers[index] || "").length, ...rows.map((row) => String(row[index] || "").length));
|
||||
// Columns exactly as wide as their content (max 26), one space between them.
|
||||
function getCompactTableWidth(headers, rows) {
|
||||
return headers.reduce((sum, _header, index) => sum + Math.min(26, Math.max(1, longestInColumn(headers, rows, index))), 0) + Math.max(0, headers.length - 1);
|
||||
}
|
||||
|
||||
// The usual layout (" | " between columns at least 4 wide) when it fits; otherwise compact
|
||||
// columns with a single space; only then is the widest column shortened.
|
||||
function getColumnWidths(headers, rows, maxChars) {
|
||||
const roomy = headers.map((_header, index) => Math.min(26, Math.max(4, longestInColumn(headers, rows, index))));
|
||||
if (roomy.reduce((sum, width) => sum + width, 0) + Math.max(0, (roomy.length - 1) * 3) <= maxChars) {
|
||||
return { widths: roomy, separator: " | " };
|
||||
}
|
||||
const widths = headers.map((_header, index) => Math.min(26, Math.max(1, longestInColumn(headers, rows, index))));
|
||||
let total = widths.reduce((sum, width) => sum + width, 0) + Math.max(0, widths.length - 1);
|
||||
while (total > maxChars) {
|
||||
const widestIndex = widths.findIndex((width) => width === Math.max(...widths));
|
||||
if (widths[widestIndex] <= 3) {
|
||||
break;
|
||||
}
|
||||
widths[widestIndex] -= 1;
|
||||
total -= 1;
|
||||
}
|
||||
return { widths, separator: " " };
|
||||
}
|
||||
|
||||
function formatPdfRow(values, widths, separator = " | ") {
|
||||
return values
|
||||
.map((value, index) => String(value || "").slice(0, widths[index]).padEnd(widths[index], " "))
|
||||
.join(separator);
|
||||
}
|
||||
|
||||
function wrapPdfText(text, maxChars) {
|
||||
const words = String(text || "").split(/\s+/).filter(Boolean);
|
||||
if (!words.length) {
|
||||
return [""];
|
||||
}
|
||||
const lines = [];
|
||||
let current = "";
|
||||
words.forEach((word) => {
|
||||
const next = current ? `${current} ${word}` : word;
|
||||
if (next.length > maxChars) {
|
||||
if (current) {
|
||||
lines.push(current);
|
||||
current = word;
|
||||
} else {
|
||||
lines.push(word.slice(0, maxChars));
|
||||
current = word.slice(maxChars);
|
||||
}
|
||||
} else {
|
||||
current = next;
|
||||
}
|
||||
});
|
||||
if (current) {
|
||||
lines.push(current);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function buildPdfContentStream(lines, x, y, lineHeight, logoPlacement = null) {
|
||||
const escaped = lines.map((line) => escapePdfText(line));
|
||||
const commands = [];
|
||||
if (logoPlacement) {
|
||||
commands.push("q");
|
||||
commands.push(`${logoPlacement.width} 0 0 ${logoPlacement.height} ${logoPlacement.x} ${logoPlacement.y} cm`);
|
||||
commands.push("/Im1 Do");
|
||||
commands.push("Q");
|
||||
}
|
||||
commands.push(
|
||||
"BT",
|
||||
"/F1 11 Tf",
|
||||
`${lineHeight} TL`,
|
||||
`${x} ${y} Td`,
|
||||
...escaped.map((line) => `(${line}) Tj\nT*`),
|
||||
"ET"
|
||||
);
|
||||
return commands.join("\n");
|
||||
}
|
||||
|
||||
function escapePdfText(text) {
|
||||
return String(text || "")
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("(", "\\(")
|
||||
.replaceAll(")", "\\)");
|
||||
}
|
||||
|
||||
// The content stream is declared with /Encoding /WinAnsiEncoding (see buildSimplePdf), so every
|
||||
// character must become exactly one WinAnsi (~CP1252) byte or a PDF viewer renders garbage/boxes
|
||||
// for anything outside plain ASCII - accented letters most of all (å, ä, ö, ...). WinAnsi matches
|
||||
// Latin-1 one-for-one above 0x9F (where å/ä/ö/Å/Ä/Ö all live), so a plain code-point clamp covers
|
||||
// Swedish text; only the narrow 0x80-0x9F "smart punctuation" block needs its own mapping.
|
||||
const PDF_WIN_ANSI_OVERRIDES = {
|
||||
0x20ac: 0x80, 0x201a: 0x82, 0x0192: 0x83, 0x201e: 0x84, 0x2026: 0x85, 0x2020: 0x86, 0x2021: 0x87,
|
||||
0x02c6: 0x88, 0x2030: 0x89, 0x0160: 0x8a, 0x2039: 0x8b, 0x0152: 0x8c, 0x017d: 0x8e,
|
||||
0x2018: 0x91, 0x2019: 0x92, 0x201c: 0x93, 0x201d: 0x94, 0x2022: 0x95, 0x2013: 0x96, 0x2014: 0x97,
|
||||
0x02dc: 0x98, 0x2122: 0x99, 0x0161: 0x9a, 0x203a: 0x9b, 0x0153: 0x9c, 0x017e: 0x9e, 0x0178: 0x9f,
|
||||
};
|
||||
|
||||
function pdfWinAnsiBuffer(text) {
|
||||
const bytes = [];
|
||||
for (const char of String(text || "")) {
|
||||
const code = char.codePointAt(0);
|
||||
if (code < 0x80 || (code > 0x9f && code <= 0xff)) bytes.push(code);
|
||||
else if (PDF_WIN_ANSI_OVERRIDES[code] !== undefined) bytes.push(PDF_WIN_ANSI_OVERRIDES[code]);
|
||||
else bytes.push(0x3f); // "?" - outside what a standard PDF font/WinAnsiEncoding can represent
|
||||
}
|
||||
return Buffer.from(bytes);
|
||||
}
|
||||
|
||||
function getLanUrls(port) {
|
||||
const interfaces = os.networkInterfaces();
|
||||
const urls = [];
|
||||
|
||||
Reference in new issue
Block a user