Files
Live_RC/server/pdf_render.js
T

456 lines
20 KiB
JavaScript

// 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" };
// Medal colours: rim, face, highlight, number.
const MEDALS = {
1: ["#9c7210", "#f0c53f", "#fff2b0", "#4a3500"],
2: ["#7d8691", "#cfd5dc", "#ffffff", "#33383f"],
3: ["#84491a", "#d38a4c", "#ffd7b0", "#3d2109"],
};
const PODIUM_TINT = { 1: "#fbeebf", 2: "#e9edf1", 3: "#f5dcc6" };
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 : [""];
}
// Blend two #rrggbb colours; amount 0 gives the first, 1 the second.
const mix = (from, to, amount) => `#${[1, 3, 5].map((index) => Math.round(parseInt(from.slice(index, index + 2), 16) * (1 - amount) + parseInt(to.slice(index, index + 2), 16) * amount).toString(16).padStart(2, "0")).join("")}`;
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`);
},
circle(cx, cy, r, color) {
const k = r * 0.5523;
writer.page.push(`${rgb(color)} rg ${n(cx + r)} ${n(cy)} m ${n(cx + r)} ${n(cy + k)} ${n(cx + k)} ${n(cy + r)} ${n(cx)} ${n(cy + r)} c ${n(cx - k)} ${n(cy + r)} ${n(cx - r)} ${n(cy + k)} ${n(cx - r)} ${n(cy)} c ${n(cx - r)} ${n(cy - k)} ${n(cx - k)} ${n(cy - r)} ${n(cx)} ${n(cy - r)} c ${n(cx + k)} ${n(cy - r)} ${n(cx + r)} ${n(cy - k)} ${n(cx + r)} ${n(cy)} c f`);
},
// A gold/silver/bronze medal: rim, face, a soft highlight and the place in bold.
medal(cx, cy, place, label = String(place)) {
const [rim, face, light, ink] = MEDALS[place];
writer.circle(cx, cy, 7, rim);
writer.circle(cx, cy, 5.8, face);
writer.circle(cx - 1.6, cy + 1.8, 2.4, light);
writer.circle(cx - 0.3, cy + 0.3, 4.1, face);
const size = label.length > 1 ? 6 : 7.5;
writer.text(cx - 6, cy - size / 3, label, size, { bold: true, color: ink, align: "center", width: 12 });
},
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 placeColumn = section.headers.map((_h, index) => {
const values = section.rows.map((row) => String(row[index] || "").trim()).filter(Boolean);
return values.length > 0 && values.every((value) => /^(TQ|[A-Z]?\d+|-)$/.test(value));
});
// The driver name is the first column that is not a place or a number; podium rows make it bold.
const nameIndex = section.headers.findIndex((_h, index) => index > 0 && !numeric[index] && !placeColumn[index]);
const align = (index) => (placeColumn[index] && index < 3 ? "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 place = hasPos ? /^A?([1-3])$/.exec(String(row[0] || "").trim())?.[1] : null;
const podium = place ? PODIUM[place] : null;
if (podium) {
// Tinted band fading out to the right, like House of RC's result lists.
const steps = 14;
const bandWidth = writer.width * 0.7;
for (let step = 0; step < steps; step += 1) {
writer.rect(MARGIN + (bandWidth / steps) * step, top - rowHeight, bandWidth / steps + 0.5, rowHeight, mix(PODIUM_TINT[place], rowIndex % 2 ? theme.zebra : "#ffffff", step / steps));
}
writer.rect(MARGIN, top - rowHeight, 3.5, rowHeight, podium);
}
let x = MARGIN;
section.headers.forEach((_h, index) => {
const bold = Boolean(podium) && index === nameIndex;
if (podium && index === 0) {
writer.medal(x + widths[0] / 2, top - rowHeight / 2, Number(place), String(row[0]).trim());
x += widths[0];
return;
}
const tq = String(row[index] || "").trim() === "TQ";
writer.text(x + PAD, top - 11.5, fitText(row[index], CELL_SIZE, bold || tq, widths[index] - PAD * 2), CELL_SIZE, { bold: bold || tq, color: tq ? "#b07d00" : TEXT, 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 };