diff --git a/CHANGELOG.md b/CHANGELOG.md index d5e0134..15a293f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/package-lock.json b/package-lock.json index 637c139..141676a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 3a0d097..534e0ae 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/server.js b/server.js index a70af3e..7aa366b 100644 --- a/server.js +++ b/server.js @@ -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 = []; diff --git a/server/pdf_render.js b/server/pdf_render.js new file mode 100644 index 0000000..8771064 --- /dev/null +++ b/server/pdf_render.js @@ -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 }; diff --git a/src/app.js b/src/app.js index 3c72d97..851b382 100644 --- a/src/app.js +++ b/src/app.js @@ -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) {