events 3.9.0: SVG logos in PDFs (svg-to-pdfkit), the Accounts logo copied for PDFs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -45,6 +45,7 @@
|
||||
"pg-boss": "^11.1.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"raw-body": "^3.0.0",
|
||||
"svg-to-pdfkit": "0.1.8",
|
||||
"swagger-ui-dist": "^5.34.0",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3",
|
||||
|
||||
@@ -16,6 +16,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const PDFDocument = require('pdfkit');
|
||||
const QRCode = require('qrcode');
|
||||
const { drawLogo } = require('./logoCopy');
|
||||
const prisma = require('../config/db');
|
||||
const { activeSessions, completionMet, normalizeCertificateConfig, attendanceBySession, groupTickets, TIMEZONE } = require('./sessions');
|
||||
|
||||
@@ -189,7 +190,7 @@ function drawTemplate(doc, template, ctx) {
|
||||
doc.rect(0, 0, 28, H).fill(color);
|
||||
doc.rect(28, 0, 6, H).fill(lighten(color, 0.6));
|
||||
const x = 90;
|
||||
safeImage(doc, logo, x, 70, { fit: [120, 50] });
|
||||
drawLogo(doc, logo, x, 70, { fit: [120, 50] });
|
||||
doc.font('Helvetica').fontSize(11).fillColor(color).text(branding.name.toUpperCase(), x, 150, { characterSpacing: 2 });
|
||||
doc.font('Helvetica-Bold').fontSize(36).fillColor('#0f172a').text(title, x, 175, { width: W - x - 80 });
|
||||
doc.font('Helvetica').fontSize(13).fillColor('#64748b').text('Presented to', x, 260);
|
||||
@@ -202,7 +203,7 @@ function drawTemplate(doc, template, ctx) {
|
||||
if (template === 'church') {
|
||||
doc.rect(0, 0, W, H).fill(lighten(color, 0.94));
|
||||
doc.rect(30, 30, W - 60, H - 60).lineWidth(1).strokeColor(lighten(color, 0.4)).stroke();
|
||||
const hasLogo = safeImage(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' });
|
||||
const hasLogo = drawLogo(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' });
|
||||
const top = hasLogo ? 150 : 115;
|
||||
doc.font('Times-Italic').fontSize(14).fillColor(color).text(branding.name, 0, top, { width: W, align: 'center' });
|
||||
doc.font('Times-Bold').fontSize(34).fillColor('#1e293b').text(title, 60, top + 26, { width: W - 120, align: 'center' });
|
||||
@@ -228,7 +229,7 @@ function drawTemplate(doc, template, ctx) {
|
||||
const y = top ? 48 + rnd() * 50 : 110 + rnd() * (H - 260);
|
||||
doc.circle(x, y, 3 + rnd() * 5).fill(bright[i % bright.length]);
|
||||
}
|
||||
safeImage(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' });
|
||||
drawLogo(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' });
|
||||
doc.font('Helvetica-Bold').fontSize(38).fillColor(color).text(title, 100, 165, { width: W - 200, align: 'center' });
|
||||
doc.font('Helvetica-Bold').fontSize(15).fillColor('#f59e0b').text('Well done,', 0, 230, { width: W, align: 'center' });
|
||||
doc.font('Helvetica-Bold').fontSize(36).fillColor('#1e293b').text(cert.name, 100, 250, { width: W - 200, align: 'center' });
|
||||
@@ -244,7 +245,7 @@ function drawTemplate(doc, template, ctx) {
|
||||
for (const [cx, cy] of [[34, 34], [W - 34, 34], [34, H - 34], [W - 34, H - 34]]) {
|
||||
doc.circle(cx, cy, 6).fill(color);
|
||||
}
|
||||
safeImage(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' });
|
||||
drawLogo(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' });
|
||||
doc.font('Times-Bold').fontSize(38).fillColor('#1e293b').text(title.toUpperCase(), 60, 150, { width: W - 120, align: 'center', characterSpacing: 1.5 });
|
||||
doc.font('Times-Italic').fontSize(14).fillColor('#64748b').text('This certificate is proudly presented to', 0, 212, { width: W, align: 'center' });
|
||||
doc.font('Times-BoldItalic').fontSize(34).fillColor(color).text(cert.name, 60, 236, { width: W - 120, align: 'center' });
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
// The logo for PDFs (tickets, invoices, receipts, certificates, privacy exports). PDFs need a file
|
||||
// on disk. A logo uploaded here already is one; the church's logo from its Accounts profile is an
|
||||
// address on another site, so a copy is kept in uploads/accounts (one per address, made the first
|
||||
// time it's needed and when Accounts says the church changed; older copies are removed).
|
||||
// address on another site, so a copy is kept in uploads/accounts (one per address, made when the
|
||||
// profile arrives or the first PDF needs it; older copies are removed).
|
||||
//
|
||||
// Only PNG and JPEG can be drawn into a PDF, so another kind of logo (SVG, WebP) isn't copied and
|
||||
// the PDFs show the church's name without it, as before.
|
||||
// PNG and JPEG are drawn as pictures; SVG (the demo churches' logos, and many churches') is drawn
|
||||
// as shapes with svg-to-pdfkit (`drawLogo`). Anything else (WebP, GIF) isn't copied, and the PDFs
|
||||
// show the church's name without a logo.
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const SVGtoPDF = require('svg-to-pdfkit');
|
||||
const { UPLOADS_DIR, uploadsDir } = require('./uploads');
|
||||
|
||||
const MAX_BYTES = 2 * 1024 * 1024;
|
||||
const TIMEOUT_MS = 5000;
|
||||
const KINDS = { png: 'png', jpeg: 'jpg' };
|
||||
const EXT = { png: 'png', jpeg: 'jpg', svg: 'svg' };
|
||||
|
||||
/** PNG or JPEG by its first bytes (never by what the server says it is), else null. */
|
||||
function rasterKind(buf) {
|
||||
/** PNG, JPEG or SVG by the file's own bytes (never by what a server says it is), else null. */
|
||||
function logoKind(buf) {
|
||||
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
|
||||
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';
|
||||
const head = buf.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart();
|
||||
if (head.startsWith('<') && /<svg[\s>]/i.test(head)) return 'svg';
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -35,7 +39,7 @@ function fetchable(url) {
|
||||
|
||||
function existingCopy(url) {
|
||||
const base = nameFor(url);
|
||||
for (const ext of Object.values(KINDS)) {
|
||||
for (const ext of Object.values(EXT)) {
|
||||
const p = path.join(UPLOADS_DIR, 'accounts', `${base}.${ext}`);
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
@@ -53,11 +57,11 @@ async function download(url) {
|
||||
if (Number(res.headers.get('content-length') || 0) > MAX_BYTES) throw new Error('is larger than 2 MB');
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
if (buf.length > MAX_BYTES) throw new Error('is larger than 2 MB');
|
||||
const kind = rasterKind(buf);
|
||||
if (!kind) return null; // SVG, WebP…: not drawable in a PDF
|
||||
const kind = logoKind(buf);
|
||||
if (!kind) return null; // WebP, GIF…: not drawable in a PDF
|
||||
const dir = uploadsDir('accounts');
|
||||
const base = nameFor(url);
|
||||
const file = path.join(dir, `${base}.${KINDS[kind]}`);
|
||||
const file = path.join(dir, `${base}.${EXT[kind]}`);
|
||||
fs.writeFileSync(file, buf);
|
||||
// The church changed its logo: the copies of the old ones go.
|
||||
for (const f of fs.readdirSync(dir)) if (f.startsWith('logo-') && !f.startsWith(`${base}.`)) fs.rmSync(path.join(dir, f), { force: true });
|
||||
@@ -65,15 +69,19 @@ async function download(url) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The logo as a file a PDF can draw, or null. `logoUrl` is the logo_url setting: a path on this
|
||||
* site (/uploads/…) or the church's logo address from Accounts. Never throws.
|
||||
* The logo as a file a PDF can draw (`drawLogo`), or null. `logoUrl` is the logo_url setting: a
|
||||
* path on this site (/uploads/…) or the church's logo address from Accounts. Never throws.
|
||||
*/
|
||||
async function pdfLogoPath(logoUrl) {
|
||||
const url = String(logoUrl || '').trim();
|
||||
if (!url) return null;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
const p = path.join(UPLOADS_DIR, '..', url.replace(/^\//, ''));
|
||||
return fs.existsSync(p) && rasterKind(fs.readFileSync(p).subarray(0, 8)) ? p : null;
|
||||
try {
|
||||
return fs.existsSync(p) && logoKind(fs.readFileSync(p)) ? p : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (!fetchable(url)) return null;
|
||||
const have = existingCopy(url);
|
||||
@@ -95,9 +103,35 @@ async function pdfLogoPath(logoUrl) {
|
||||
return pending.get(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the logo `file` (from pdfLogoPath) at x, y within `fit` [w, h], as doc.image does; centred
|
||||
* in that box with `align: 'center'`. True when drawn. Never throws.
|
||||
*/
|
||||
function drawLogo(doc, file, x, y, { fit, align } = {}) {
|
||||
if (!file) return false;
|
||||
try {
|
||||
if (file.toLowerCase().endsWith('.svg')) {
|
||||
const [width, height] = fit || [100, 50];
|
||||
SVGtoPDF(doc, fs.readFileSync(file, 'utf8'), x, y, {
|
||||
width,
|
||||
height,
|
||||
preserveAspectRatio: align === 'center' ? 'xMidYMid meet' : 'xMinYMid meet',
|
||||
// Only pictures inside the SVG itself: never a file or address it names.
|
||||
imageCallback: (link) => (/^data:image\/(png|jpe?g);base64,/i.test(String(link).trim()) ? String(link).replace(/\s+/g, '') : ''),
|
||||
warningCallback: () => {},
|
||||
});
|
||||
} else {
|
||||
doc.image(file, x, y, { fit, ...(align ? { align } : {}) });
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Tests: forget the addresses that gave nothing. */
|
||||
function resetLogoCopies() {
|
||||
misses.clear();
|
||||
}
|
||||
|
||||
module.exports = { pdfLogoPath, resetLogoCopies, rasterKind };
|
||||
module.exports = { pdfLogoPath, drawLogo, resetLogoCopies, logoKind };
|
||||
|
||||
@@ -193,7 +193,7 @@ async function generateReceiptPdf(payment) {
|
||||
const bannerH = 150;
|
||||
doc.rect(0, 0, pageWidth, bannerH).fill(org.brandColor);
|
||||
if (org.logoPath) {
|
||||
try { doc.image(org.logoPath, marginX, 28, { fit: [36, 36] }); } catch {}
|
||||
require('./logoCopy').drawLogo(doc, org.logoPath, marginX, 28, { fit: [36, 36] });
|
||||
}
|
||||
doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(13).text(org.name, marginX + (org.logoPath ? 46 : 0), 38, { width: 260 });
|
||||
doc.font('Helvetica-Bold').fontSize(26).text('Payment Receipt', marginX, 68, { width: 320 });
|
||||
@@ -298,7 +298,7 @@ async function generateInvoicePdf(registration, { paymentUrl = null, totalDue =
|
||||
doc.rect(0, 0, sidebarW, pageHeight).fill('#111827');
|
||||
let sy = 40;
|
||||
if (org.logoPath) {
|
||||
try { doc.image(org.logoPath, 28, sy, { fit: [32, 32] }); sy += 0; } catch {}
|
||||
require('./logoCopy').drawLogo(doc, org.logoPath, 28, sy, { fit: [32, 32] });
|
||||
}
|
||||
doc.font('Helvetica-Bold').fontSize(12).fillColor('#ffffff').text(org.name, org.logoPath ? 68 : 28, sy + 8, { width: sidebarW - (org.logoPath ? 96 : 56) });
|
||||
sy += 60;
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
// The logo for PDFs: an uploaded one is used as it is; the church's logo from Accounts (an address
|
||||
// on another site) is copied into uploads/accounts once, and only when it's a PNG or JPEG.
|
||||
// on another site) is copied into uploads/accounts once, when it's a PNG, JPEG or SVG; drawLogo
|
||||
// draws either kind into a PDF.
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { pdfLogoPath, resetLogoCopies } = require('../src/utils/logoCopy') as { pdfLogoPath(u: string): Promise<string | null>; resetLogoCopies(): void };
|
||||
const { pdfLogoPath, drawLogo, resetLogoCopies } = require('../src/utils/logoCopy') as {
|
||||
pdfLogoPath(u: string): Promise<string | null>;
|
||||
drawLogo(doc: unknown, file: string | null, x: number, y: number, o?: { fit?: [number, number]; align?: string }): boolean;
|
||||
resetLogoCopies(): void;
|
||||
};
|
||||
const PDFDocument = require('pdfkit');
|
||||
const { UPLOADS_DIR } = require('../src/utils/uploads') as { UPLOADS_DIR: string };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]);
|
||||
const SVG = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>');
|
||||
const SVG = Buffer.from('<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#1f4e79"/><path d="M232 96h48v320h-48z" fill="#fff"/></svg>');
|
||||
const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]);
|
||||
const COPIES = path.join(UPLOADS_DIR, 'accounts');
|
||||
const realFetch = global.fetch;
|
||||
let served: Record<string, Buffer | number> = {};
|
||||
@@ -36,6 +43,17 @@ beforeEach(() => {
|
||||
});
|
||||
afterEach(() => { jest.restoreAllMocks(); });
|
||||
|
||||
function pdfOf(draw: (doc: unknown) => void): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const doc = new PDFDocument({ compress: false });
|
||||
const parts: Buffer[] = [];
|
||||
doc.on('data', (b: Buffer) => parts.push(b));
|
||||
doc.on('end', () => resolve(Buffer.concat(parts).toString('latin1')));
|
||||
draw(doc);
|
||||
doc.end();
|
||||
});
|
||||
}
|
||||
|
||||
test("the church's PNG logo from Accounts is copied once, and used from the copy after", async () => {
|
||||
served['https://accounts.hope.test/logo.png'] = PNG;
|
||||
const p = await pdfLogoPath('https://accounts.hope.test/logo.png');
|
||||
@@ -55,20 +73,53 @@ test('a new logo replaces the copy of the old one', async () => {
|
||||
expect(fs.readdirSync(COPIES)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("an SVG logo or one that can't be fetched gives none (the PDF shows the name), and isn't fetched again at once", async () => {
|
||||
test("an SVG logo (the demo churches') is copied too", async () => {
|
||||
served['https://accounts.hope.test/logo.svg'] = SVG;
|
||||
const p = await pdfLogoPath('https://accounts.hope.test/logo.svg');
|
||||
expect(p?.endsWith('.svg')).toBe(true);
|
||||
});
|
||||
|
||||
test("a logo a PDF can't draw, or one that can't be fetched, gives none (the PDF shows the name), and isn't fetched again at once", async () => {
|
||||
served['https://accounts.hope.test/logo.webp'] = WEBP;
|
||||
served['https://accounts.hope.test/gone.png'] = 404;
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.svg')).toBeNull();
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull();
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/gone.png')).toBeNull();
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.svg')).toBeNull();
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull();
|
||||
expect(fetched).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('drawLogo draws an SVG logo as shapes in its colours, and never opens a file the SVG names', async () => {
|
||||
fs.mkdirSync(COPIES, { recursive: true });
|
||||
const file = path.join(COPIES, 'logo-test.svg');
|
||||
fs.writeFileSync(file, SVG);
|
||||
let drawn = false;
|
||||
const pdf = await pdfOf((doc) => { drawn = drawLogo(doc, file, 40, 40, { fit: [60, 60], align: 'center' }); });
|
||||
expect(drawn).toBe(true);
|
||||
expect(pdf).toMatch(/0\.12156\d* 0\.30588\d* 0\.47450\d* scn/); // #1f4e79
|
||||
|
||||
const picture = path.join(COPIES, 'logo-test.png');
|
||||
fs.writeFileSync(picture, PNG);
|
||||
const sneaky = path.join(COPIES, 'logo-sneaky.svg');
|
||||
const href = picture.split(path.sep).join('/');
|
||||
fs.writeFileSync(sneaky, `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><image href="${href}" width="10" height="10"/></svg>`);
|
||||
const out = await pdfOf((doc) => { drawLogo(doc, sneaky, 0, 0, { fit: [10, 10] }); });
|
||||
expect(out).not.toContain('/Subtype /Image');
|
||||
});
|
||||
|
||||
test("drawLogo gives false, without throwing, for a file it can't draw", async () => {
|
||||
fs.mkdirSync(COPIES, { recursive: true });
|
||||
const bad = path.join(COPIES, 'logo-bad.png');
|
||||
fs.writeFileSync(bad, 'not a picture');
|
||||
let drawn = true;
|
||||
await pdfOf((doc) => { drawn = drawLogo(doc, bad, 0, 0, { fit: [10, 10] }); });
|
||||
expect(drawn).toBe(false);
|
||||
expect(drawLogo({}, null, 0, 0)).toBe(false);
|
||||
});
|
||||
|
||||
test('a logo uploaded here is used as it is; nothing for no logo', async () => {
|
||||
const dir = path.join(UPLOADS_DIR, 'accounts');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'own.png'), PNG);
|
||||
expect(await pdfLogoPath('/uploads/accounts/own.png')).toBe(path.join(dir, 'own.png'));
|
||||
fs.mkdirSync(COPIES, { recursive: true });
|
||||
fs.writeFileSync(path.join(COPIES, 'own.png'), PNG);
|
||||
expect(await pdfLogoPath('/uploads/accounts/own.png')).toBe(path.join(COPIES, 'own.png'));
|
||||
expect(await pdfLogoPath('')).toBeNull();
|
||||
expect(await pdfLogoPath('/uploads/accounts/missing.png')).toBeNull();
|
||||
expect(fetched).toHaveLength(0);
|
||||
|
||||
Reference in New Issue
Block a user