feat(print): styled PDF export and printouts with branded header, real tables and podium marks (1.72.0)

This commit is contained in:
larssand committed 2026-11-06 22:52:02 +01:00
1 parent c4375daa93
commit 7c25f23ad0
8 files changed
+504 -372

No files matched your search

+6
View File
@@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.72.0
### Changed
- PDF export redesigned: Helvetica instead of the typewriter font, a coloured club header (with logo), real tables with a filled header row, striped rows, gold/silver/bronze marks for the top three, right-aligned times, the table header repeated on every page and page numbers. The PDF theme (Classic, Motorsport, Minimal) sets the colours.
- Printouts (race overview, start lists, results, team report, series standings, heat sheets, day schedule) get the same look: coloured header band, tables with a dark header row and striped rows, podium marks, and title plus page number at the foot of each page.
## 1.71.0
### Added
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.71.0",
"version": "1.72.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.71.0",
"version": "1.72.0",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.71.0",
"version": "1.72.0",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+2 -354
View File
@@ -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 = [];
+411
View File
@@ -0,0 +1,411 @@
// Styled A4 PDF for result lists, start lists and standings: a branded header, real tables
// (coloured header row, striped rows, podium marks), page numbers. Uses the PDF standard fonts
// Helvetica / Helvetica-Bold with WinAnsiEncoding so Swedish å/ä/ö print without embedding fonts.
const THEMES = {
classic: { band: "#14213d", accent: "#2f6fde", headFill: "#14213d", headText: "#ffffff", zebra: "#f2f5fa" },
motorsport: { band: "#111111", accent: "#d61f2c", headFill: "#1c1c1c", headText: "#ffffff", zebra: "#f5f2f2" },
minimal: { band: null, accent: "#3c4454", headFill: "#e9ecf1", headText: "#1d2330", zebra: "#f7f8fa" },
};
const PODIUM = { 1: "#d4af37", 2: "#a9b0bb", 3: "#c27c3e" };
const TEXT = "#1d2330";
const MUTED = "#6b7486";
const RULE = "#d8dde6";
// Glyph widths (1/1000 em) from the Adobe Helvetica AFM files, characters 32-126.
const HELVETICA = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
const HELVETICA_BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];
function charWidth(char, bold) {
const code = char.codePointAt(0);
if (code >= 32 && code <= 126) return (bold ? HELVETICA_BOLD : HELVETICA)[code - 32];
if (char === "…" || char === "—") return 1000;
if (char === "•") return 350;
return char !== char.toLowerCase() ? (bold ? 740 : 700) : bold ? 600 : 556;
}
function textWidth(text, size, bold = false) {
let sum = 0;
for (const char of String(text || "")) sum += charWidth(char, bold);
return (sum * size) / 1000;
}
function fitText(text, size, bold, maxWidth) {
const value = String(text || "");
if (textWidth(value, size, bold) <= maxWidth) return value;
const chars = [...value];
while (chars.length && textWidth(`${chars.join("")}…`, size, bold) > maxWidth) chars.pop();
return chars.length ? `${chars.join("")}…` : "";
}
function wrapText(text, size, bold, maxWidth) {
const lines = [];
let current = "";
String(text || "").split(/\s+/).filter(Boolean).forEach((word) => {
const next = current ? `${current} ${word}` : word;
if (current && textWidth(next, size, bold) > maxWidth) {
lines.push(current);
current = word;
} else {
current = next;
}
});
if (current) lines.push(fitText(current, size, bold, maxWidth));
return lines.length ? lines : [""];
}
const rgb = (hex) => [1, 3, 5].map((index) => (parseInt(hex.slice(index, index + 2), 16) / 255).toFixed(3)).join(" ");
const escapePdfText = (text) => String(text || "").replaceAll("\\", "\\\\").replaceAll("(", "\\(").replaceAll(")", "\\)");
const n = (value) => Number(value.toFixed(2));
// Byte-for-byte WinAnsi (~CP1252): Latin-1 maps one-to-one above 0x9F (å/ä/ö/Å/Ä/Ö), only the
// 0x80-0x9F "smart punctuation" block needs its own table.
const 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 (WIN_ANSI_OVERRIDES[code] !== undefined) bytes.push(WIN_ANSI_OVERRIDES[code]);
else bytes.push(0x3f);
}
return Buffer.from(bytes);
}
const MARGIN = 40;
const PAD = 5;
const HEAD_SIZE = 8.5;
const CELL_SIZE = 9;
const PORTRAIT_WIDTH = 595 - MARGIN * 2;
const NUMERIC = /^[-+()0-9.:,\s%/]+$/;
const POS_HEADER = /^(pos|plac|placering|place|rank|#|nr)\.?$/i;
function naturalWidths(section) {
return section.headers.map((header, index) => Math.min(230, Math.max(
textWidth(header, HEAD_SIZE, true),
...section.rows.map((row) => textWidth(row[index], CELL_SIZE, false)),
) * 1.08 + PAD * 2 + 2));
}
function pdfNeedsLandscape(payload) {
return payload.sections.some((section) => section.headers.length && naturalWidths(section).reduce((a, b) => a + b, 0) > PORTRAIT_WIDTH);
}
// Columns as wide as their content; spare room goes to the widest (usually the driver name),
// too little room shrinks the widest columns first.
function columnWidths(section, available) {
const widths = naturalWidths(section);
let total = widths.reduce((a, b) => a + b, 0);
if (total < available) {
widths[widths.indexOf(Math.max(...widths))] += available - total;
return widths;
}
while (total > available) {
const widest = widths.indexOf(Math.max(...widths));
if (widths[widest] <= 22) break;
widths[widest] -= 1;
total -= 1;
}
return widths;
}
// Page writer: collects drawing commands per page and starts a new page when space runs out.
function createWriter(pageWidth, pageHeight, title) {
const pages = [];
const writer = {
width: pageWidth - MARGIN * 2,
y: 0,
page: null,
newPage() {
writer.page = [];
pages.push(writer.page);
if (pages.length > 1) {
writer.text(MARGIN, pageHeight - 26, fitText(title, 8, true, writer.width), 8, { bold: true, color: MUTED });
writer.line(MARGIN, pageHeight - 32, pageWidth - MARGIN, pageHeight - 32, RULE, 0.5);
writer.y = pageHeight - 50;
}
},
ensure(height) {
if (writer.y - height < MARGIN + 24) {
writer.newPage();
return true;
}
return false;
},
rect(x, y, w, h, color) {
writer.page.push(`${rgb(color)} rg ${n(x)} ${n(y)} ${n(w)} ${n(h)} re f`);
},
line(x1, y1, x2, y2, color, width = 0.5) {
writer.page.push(`${rgb(color)} RG ${width} w ${n(x1)} ${n(y1)} m ${n(x2)} ${n(y2)} l S`);
},
text(x, y, value, size, { bold = false, color = TEXT, align = "left", width = 0 } = {}) {
if (!value) return;
let left = x;
if (align === "right") left = x + width - textWidth(value, size, bold);
if (align === "center") left = x + (width - textWidth(value, size, bold)) / 2;
writer.page.push(`BT ${rgb(color)} rg /${bold ? "F2" : "F1"} ${size} Tf ${n(left)} ${n(y)} Td (${escapePdfText(value)}) Tj ET`);
},
image(x, y, w, h) {
writer.page.push(`q ${n(w)} 0 0 ${n(h)} ${n(x)} ${n(y)} cm /Im1 Do Q`);
},
};
writer.newPage();
writer.y = pageHeight - MARGIN;
return { writer, pages };
}
function drawHeader(writer, payload, theme, logo, pageWidth, pageHeight) {
const bandHeight = 62;
const dark = Boolean(theme.band);
if (dark) {
writer.rect(0, pageHeight - bandHeight, pageWidth, bandHeight, theme.band);
writer.rect(0, pageHeight - bandHeight - 4, pageWidth, 4, theme.accent);
}
let textX = MARGIN;
if (logo) {
const boxY = pageHeight - bandHeight / 2 - logo.displayHeight / 2;
if (dark) writer.rect(MARGIN - 4, boxY - 4, logo.displayWidth + 8, logo.displayHeight + 8, "#ffffff");
writer.image(MARGIN, boxY, logo.displayWidth, logo.displayHeight);
textX = MARGIN + logo.displayWidth + 14;
}
const brandColor = dark ? "#ffffff" : TEXT;
writer.text(textX, pageHeight - 30, payload.brandName, 15, { bold: true, color: brandColor });
writer.text(textX, pageHeight - 45, payload.brandTagline, 9, { color: dark ? "#c9d0dc" : MUTED });
writer.text(MARGIN, pageHeight - 36, new Date().toISOString().slice(0, 10), 9, { color: dark ? "#c9d0dc" : MUTED, align: "right", width: pageWidth - MARGIN * 2 });
if (!dark) writer.line(MARGIN, pageHeight - bandHeight, pageWidth - MARGIN, pageHeight - bandHeight, theme.accent, 1.5);
writer.y = pageHeight - bandHeight - 34;
wrapText(payload.title, 20, true, writer.width).forEach((line) => {
writer.text(MARGIN, writer.y, line, 20, { bold: true });
writer.y -= 24;
});
if (payload.subtitle) {
wrapText(payload.subtitle, 10, false, writer.width).forEach((line) => {
writer.text(MARGIN, writer.y + 4, line, 10, { color: MUTED });
writer.y -= 14;
});
}
writer.y -= 6;
}
function drawSectionTitle(writer, title, theme) {
writer.ensure(60);
writer.y -= 8;
writer.rect(MARGIN, writer.y - 3, 3.5, 15, theme.accent);
writer.text(MARGIN + 10, writer.y, fitText(title, 12.5, true, writer.width - 10), 12.5, { bold: true });
writer.y -= 14;
}
function drawTable(writer, section, theme) {
const widths = columnWidths(section, writer.width);
const numeric = section.headers.map((_h, index) => {
const values = section.rows.map((row) => String(row[index] || "").trim()).filter(Boolean);
return values.length > 0 && values.every((value) => NUMERIC.test(value));
});
const hasPos = POS_HEADER.test(String(section.headers[0] || "").trim());
const align = (index) => (index === 0 && numeric[0] ? "center" : numeric[index] ? "right" : "left");
const headHeight = 19;
const rowHeight = 16.5;
const drawHead = () => {
writer.rect(MARGIN, writer.y - headHeight, writer.width, headHeight, theme.headFill);
let x = MARGIN;
section.headers.forEach((header, index) => {
writer.text(x + PAD, writer.y - 12.5, fitText(header, HEAD_SIZE, true, widths[index] - PAD * 2), HEAD_SIZE, { bold: true, color: theme.headText, align: align(index), width: widths[index] - PAD * 2 });
x += widths[index];
});
writer.y -= headHeight;
};
writer.ensure(headHeight + rowHeight * 2);
drawHead();
section.rows.forEach((row, rowIndex) => {
if (writer.ensure(rowHeight)) drawHead();
const top = writer.y;
if (rowIndex % 2 === 1) writer.rect(MARGIN, top - rowHeight, writer.width, rowHeight, theme.zebra);
const podium = hasPos ? PODIUM[String(row[0] || "").trim()] : null;
if (podium) writer.rect(MARGIN, top - rowHeight, 3.5, rowHeight, podium);
let x = MARGIN;
section.headers.forEach((_h, index) => {
const bold = Boolean(podium) && index <= 1;
writer.text(x + PAD, top - 11.5, fitText(row[index], CELL_SIZE, bold, widths[index] - PAD * 2), CELL_SIZE, { bold, align: align(index), width: widths[index] - PAD * 2 });
x += widths[index];
});
writer.line(MARGIN, top - rowHeight, MARGIN + writer.width, top - rowHeight, RULE, 0.4);
writer.y -= rowHeight;
});
writer.y -= 10;
}
function drawParagraphs(writer, section) {
section.rows.forEach((row) => row.forEach((value) => {
wrapText(value, 10, false, writer.width).forEach((line) => {
writer.ensure(14);
writer.text(MARGIN, writer.y - 10, line, 10);
writer.y -= 14;
});
}));
writer.y -= 6;
}
function drawFooters(writer, pages, payload, theme, pageWidth) {
pages.forEach((commands, index) => {
writer.page = commands;
writer.line(MARGIN, 34, pageWidth - MARGIN, 34, RULE, 0.5);
writer.text(MARGIN, 22, fitText(payload.footer, 8, false, pageWidth - MARGIN * 2 - 60), 8, { color: MUTED });
writer.text(MARGIN, 22, `${index + 1} / ${pages.length}`, 8, { bold: true, color: theme.accent, align: "right", width: pageWidth - MARGIN * 2 });
});
}
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 buildStyledPdf(payload) {
const landscape = pdfNeedsLandscape(payload);
const pageWidth = landscape ? 842 : 595;
const pageHeight = landscape ? 595 : 842;
const theme = THEMES[payload.theme] || THEMES.classic;
const logo = parsePdfLogo(payload.logoDataUrl);
const { writer, pages } = createWriter(pageWidth, pageHeight, [payload.brandName, payload.title].filter(Boolean).join(" · "));
drawHeader(writer, payload, theme, logo, pageWidth, pageHeight);
payload.sections.forEach((section) => {
if (section.title) drawSectionTitle(writer, section.title, theme);
if (section.headers.length) drawTable(writer, section, theme);
else drawParagraphs(writer, section);
});
drawFooters(writer, pages, payload, theme, pageWidth);
const objects = [];
const pageIds = [];
const contentIds = [];
let nextId = 3;
pages.forEach(() => { pageIds.push(nextId++); contentIds.push(nextId++); });
const fontId = nextId++;
const boldId = nextId++;
const imageId = logo ? nextId++ : null;
objects.push(createPdfTextObject(1, "<< /Type /Catalog /Pages 2 0 R >>"));
objects.push(createPdfTextObject(2, `<< /Type /Pages /Count ${pages.length} /Kids [${pageIds.map((id) => `${id} 0 R`).join(" ")}] >>`));
objects.push(createPdfTextObject(fontId, "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"));
objects.push(createPdfTextObject(boldId, "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>"));
if (logo) {
objects.push(createPdfStreamObject(imageId, `<< /Type /XObject /Subtype /Image /Width ${logo.width} /Height ${logo.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode`, logo.data));
}
const resources = `<< /Font << /F1 ${fontId} 0 R /F2 ${boldId} 0 R >>${logo ? ` /XObject << /Im1 ${imageId} 0 R >>` : ""} >>`;
pages.forEach((commands, index) => {
objects.push(createPdfTextObject(pageIds[index], `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pageWidth} ${pageHeight}] /Resources ${resources} /Contents ${contentIds[index]} 0 R >>`));
objects.push(createPdfStreamObject(contentIds[index], "<<", pdfWinAnsiBuffer(commands.join("\n"))));
});
return assemblePdf(objects);
}
module.exports = { buildStyledPdf, textWidth, fitText, pdfNeedsLandscape };
+59 -15
View File
@@ -7415,7 +7415,37 @@ function clearGeneratedFinals(eventId) {
});
}
// Same colours as the PDF themes (server/pdf_render.js).
const PRINT_THEMES = {
classic: { band: "#14213d", bandText: "#ffffff", bandMuted: "#c9d0dc", kicker: "#8fb4ff", accent: "#2f6fde", headFill: "#14213d", headText: "#ffffff", zebra: "#f2f5fa" },
motorsport: { band: "#111111", bandText: "#ffffff", bandMuted: "#c9c9c9", kicker: "#ff6b74", accent: "#d61f2c", headFill: "#1c1c1c", headText: "#ffffff", zebra: "#f5f2f2" },
minimal: { band: "#ffffff", bandText: "#1d2330", bandMuted: "#6b7486", kicker: "#3c4454", accent: "#3c4454", headFill: "#e9ecf1", headText: "#1d2330", zebra: "#f7f8fa" },
};
// Podium marks for result tables (first column Pos/Plac) and right-aligned number columns.
function decoratePrintTables(doc) {
const numeric = /^[-+()0-9.:,\s%/]+$/;
doc.querySelectorAll("table").forEach((table) => {
const headers = [...table.querySelectorAll("thead th")];
const rows = [...table.querySelectorAll("tbody tr")].filter((row) => !row.querySelector("td[colspan]"));
headers.forEach((th, index) => {
const values = rows.map((row) => row.children[index]?.textContent.trim() || "").filter((value) => value && value !== "-");
if (!values.length || !values.every((value) => numeric.test(value))) return;
const cls = index === 0 ? "pos" : "num";
th.classList.add(cls);
rows.forEach((row) => row.children[index]?.classList.add(cls));
});
if (/^(pos|plac|placering|place|#)\.?$/i.test(headers[0]?.textContent.trim() || "")) {
rows.forEach((row) => {
const pos = row.children[0]?.textContent.trim();
if (["1", "2", "3"].includes(pos)) row.classList.add(`podium-${pos}`);
});
}
});
}
function openPrintWindow(title, bodyHtml) {
const theme = PRINT_THEMES[state.settings.pdfTheme] || PRINT_THEMES.classic;
// noopener/noreferrer force window.open() to return null even when the window opens
// successfully (WHATWG spec, all modern browsers), which made the blocked-popup check
// below always fire and this always exit before writing any content. The opened window
@@ -7433,23 +7463,36 @@ function openPrintWindow(title, bodyHtml) {
<meta charset="utf-8" />
<title>${escapeHtml(title)}</title>
<style>
@page { size: A4 portrait; margin: 14mm; }
body { font-family: Arial, sans-serif; padding: 0; color: #10131a; }
h1, h2, h3 { margin: 0 0 12px; }
h1 { font-size: 28px; }
h2 { font-size: 18px; border-bottom: 2px solid #10131a; padding-bottom: 4px; }
p { margin: 0 0 12px; color: #44506b; }
.print-header { display: flex; justify-content: space-between; gap: 24px; align-items: flex-start; padding-bottom: 16px; border-bottom: 4px solid #10131a; }
.print-kicker { text-transform: uppercase; letter-spacing: 0.08em; color: #5b677f; font-size: 12px; }
.print-meta { text-align: right; font-size: 13px; }
@page { size: A4 portrait; margin: 12mm 12mm 16mm; @bottom-left { content: "${escapeHtml(String(title).replace(/["\\]/g, ""))}"; font: 9px Arial, sans-serif; color: #6b7486; } @bottom-right { content: counter(page) " / " counter(pages); font: bold 9px Arial, sans-serif; color: ${theme.accent}; } }
* { -webkit-print-color-adjust: exact; print-color-adjust: exact; box-sizing: border-box; }
body { font-family: "Helvetica Neue", Arial, sans-serif; margin: 0; padding: 0; color: #1d2330; font-size: 12px; }
h1, h2, h3 { margin: 0 0 8px; line-height: 1.2; }
h1 { font-size: 26px; }
h2 { font-size: 16px; margin-top: 4px; padding-left: 10px; border-left: 4px solid ${theme.accent}; }
h3 { font-size: 13px; color: #1d2330; }
p { margin: 0 0 8px; color: #6b7486; }
.print-header { display: flex; justify-content: space-between; gap: 24px; align-items: center; margin: 0 0 20px; padding: 18px 20px; border-radius: 6px; background: ${theme.band}; color: ${theme.bandText}; border-bottom: 4px solid ${theme.accent}; }
.print-header h1 { color: ${theme.bandText}; margin: 2px 0 4px; }
.print-header p { color: ${theme.bandMuted}; margin: 0; }
.print-header .print-kicker { color: ${theme.kicker}; }
.print-kicker { text-transform: uppercase; letter-spacing: 0.1em; font-size: 11px; font-weight: 700; color: ${theme.accent}; }
.print-meta { text-align: right; font-size: 12px; }
.print-brand-block { display: flex; align-items: center; justify-content: flex-end; gap: 12px; }
.print-brand-block strong { font-size: 15px; }
.print-brand-block p { margin: 0; }
.print-logo { max-width: 92px; max-height: 52px; object-fit: contain; }
.print-block { margin-top: 24px; break-inside: avoid; }
table { width: 100%; border-collapse: collapse; margin-top: 12px; }
th, td { border: 1px solid #b9c2d4; padding: 8px; text-align: left; }
th { background: #eef2f8; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
tbody tr:nth-child(even) { background: #f8faff; }
.print-logo { max-width: 92px; max-height: 52px; object-fit: contain; background: #fff; border-radius: 4px; padding: 3px; }
.print-block { margin-top: 22px; break-inside: avoid; }
table { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 11.5px; }
thead { display: table-header-group; }
tr { break-inside: avoid; }
th, td { padding: 6px 8px; text-align: left; border: 0; border-bottom: 1px solid #e1e5ec; }
th { background: ${theme.headFill}; color: ${theme.headText}; font-size: 10.5px; font-weight: 700; letter-spacing: 0.03em; }
th:first-child { border-top-left-radius: 4px; } th:last-child { border-top-right-radius: 4px; }
tbody tr:nth-child(even) td { background: ${theme.zebra}; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
td.pos, th.pos { text-align: center; width: 1%; white-space: nowrap; }
tr.podium-1 td:first-child { box-shadow: inset 4px 0 #d4af37; } tr.podium-2 td:first-child { box-shadow: inset 4px 0 #a9b0bb; } tr.podium-3 td:first-child { box-shadow: inset 4px 0 #c27c3e; }
tr.podium-1 td, tr.podium-2 td, tr.podium-3 td { font-weight: 700; }
</style>
</head>
<body>
@@ -7458,6 +7501,7 @@ function openPrintWindow(title, bodyHtml) {
</html>
`);
printWindow.document.close();
decoratePrintTables(printWindow.document);
printWindow.focus();
setTimeout(() => {
printWindow.print();
+22
View File
@@ -0,0 +1,22 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createRequire } from "node:module";
const { buildStyledPdf } = createRequire(import.meta.url)("../server/pdf_render.js");
const base = { title: "Resultat", subtitle: "", brandName: "Klubben", brandTagline: "", footer: "RC RaceCore", theme: "classic", logoDataUrl: "" };
test("the PDF has real tables: Helvetica fonts, a filled header row, podium marks and page numbers", () => {
const rows = Array.from({ length: 70 }, (_, i) => [String(i + 1), `Förare ${i + 1}`, String(20 - (i % 5)), "0:14.812"]);
const pdf = buildStyledPdf({ ...base, sections: [{ title: "A-final", headers: ["Pos", "Förare", "Varv", "Bästa varv"], rows }] }).toString("latin1");
assert.ok(pdf.includes("/BaseFont /Helvetica ") && pdf.includes("/BaseFont /Helvetica-Bold"), "Helvetica and Helvetica-Bold");
assert.ok(!pdf.includes("Courier"), "no typewriter font any more");
assert.ok(pdf.includes("0.831 0.686 0.216 rg"), "gold mark for the winner");
assert.match(pdf, /\/Count 2 /, "70 rows run onto a second page");
assert.equal((pdf.match(/\(Bästa varv\) Tj/g) || []).length, 2, "the table header repeats on the new page");
assert.ok(pdf.includes("(1 / 2) Tj") && pdf.includes("(2 / 2) Tj"), "page numbers");
});
test("a long name is shortened with … instead of running into the next column", () => {
const pdf = buildStyledPdf({ ...base, sections: [{ title: "", headers: ["Pos", "Förare", ...Array.from({ length: 14 }, (_, i) => `R${i + 1}`)], rows: [["1", "A".repeat(120), ...Array.from({ length: 14 }, () => "(100)")]] }] });
assert.ok(pdf.includes(Buffer.from([0x85])), "ellipsis as a WinAnsi byte");
});
+1
View File
@@ -46,3 +46,4 @@ import "./public_training_refresh.test.js";
import "./list_sorting.test.js";
import "./sync_status.test.js";
import "./decoder_diagnostics.test.js";
import "./pdf_render.test.js";