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:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user