From 3ac16948e61593f459210f0c7a63f0e3e8338e61 Mon Sep 17 00:00:00 2001 From: Gabriel Horacio Cutrini Date: Mon, 23 Nov 2026 17:37:29 -0300 Subject: [PATCH] feat(pdf): add font metrics, time limits and image loading A URL font that doesn't download within 10 seconds, isn't a TTF, OTF or WOFF file, is cut short, or is WOFF2 (which pdfmake prints blank) falls back to Helvetica, and isn't cached. A missing bold or italics style uses the closest file the font has. loadFont also returns each style's ascender and capital height, and createDocument passes them to the template as fontMetrics. loadImage loads an image within 10 seconds: PNG and JPEG as they are, SVG as vector, other formats drawn to PNG. It returns null when the image can't be loaded. --- src/utils/pdf/__fixtures__/fetch.js | 33 +++ src/utils/pdf/__fixtures__/font-files.js | 129 +++++++++++ src/utils/pdf/__tests__/base64.test.js | 24 ++ .../pdf/__tests__/create-document.test.js | 8 +- src/utils/pdf/__tests__/font-metrics.test.js | 96 ++++++++ src/utils/pdf/__tests__/load-image.test.js | 187 +++++++++++++++ src/utils/pdf/__tests__/resolve-font.test.js | 209 +++++++++++++++-- src/utils/pdf/base64.js | 26 +++ src/utils/pdf/create-document.js | 25 +- src/utils/pdf/font-metrics.js | 206 +++++++++++++++++ src/utils/pdf/image-data-url.js | 23 +- src/utils/pdf/index.js | 3 +- src/utils/pdf/load-image.js | 131 +++++++++++ src/utils/pdf/resolve-font.js | 213 ++++++++++++++---- 14 files changed, 1232 insertions(+), 81 deletions(-) create mode 100644 src/utils/pdf/__fixtures__/fetch.js create mode 100644 src/utils/pdf/__fixtures__/font-files.js create mode 100644 src/utils/pdf/__tests__/base64.test.js create mode 100644 src/utils/pdf/__tests__/font-metrics.test.js create mode 100644 src/utils/pdf/__tests__/load-image.test.js create mode 100644 src/utils/pdf/base64.js create mode 100644 src/utils/pdf/font-metrics.js create mode 100644 src/utils/pdf/load-image.js diff --git a/src/utils/pdf/__fixtures__/fetch.js b/src/utils/pdf/__fixtures__/fetch.js new file mode 100644 index 00000000..094f99aa --- /dev/null +++ b/src/utils/pdf/__fixtures__/fetch.js @@ -0,0 +1,33 @@ +/** + * Stand-ins for fetch(). A response offers arrayBuffer() and blob() the way a + * browser's does. jsdom's Blob has no arrayBuffer(), so blob() gives a plain + * object with one. Its type is generic, as servers often send it. + */ +const response = (bytes, { ok = true, status = 200 } = {}) => { + const data = Uint8Array.from(bytes); + return { + ok, + status, + arrayBuffer: () => Promise.resolve(data.buffer), + blob: () => Promise.resolve({ + type: 'application/octet-stream', + arrayBuffer: () => Promise.resolve(data.buffer), + }), + }; +}; + +// Answer every URL with these bytes. +export const serveBytes = (bytes, options) => + jest.fn(() => Promise.resolve(response(bytes, options))); + +// Answer each URL with its bytes, and with a 404 for a URL not listed. +export const serveFiles = (filesByUrl) => + jest.fn((url) => Promise.resolve( + filesByUrl[url] ? response(filesByUrl[url]) : response([], { ok: false, status: 404 }), + )); + +// A server that never answers: the fetch rejects only when it is aborted. +export const neverAnswers = () => + jest.fn((url, { signal }) => new Promise((resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('aborted'))); + })); diff --git a/src/utils/pdf/__fixtures__/font-files.js b/src/utils/pdf/__fixtures__/font-files.js new file mode 100644 index 00000000..6d06356f --- /dev/null +++ b/src/utils/pdf/__fixtures__/font-files.js @@ -0,0 +1,129 @@ +/* eslint-disable no-magic-numbers */ +// Font files built byte by byte, at their OpenType and WOFF offsets. +import { deflateSync } from 'zlib'; + +// A table of `size` bytes, filled in by `write`. +const table = (size, write) => { + const bytes = new Uint8Array(size); + write(new DataView(bytes.buffer)); + return bytes; +}; +const head = (unitsPerEm) => table(54, (v) => v.setUint16(18, unitsPerEm)); +const hhea = (ascender) => table(36, (v) => v.setInt16(4, ascender)); +const os2 = (version, capHeight) => + table(96, (v) => { + v.setUint16(0, version); + v.setInt16(88, capHeight); + }); +// A Unicode format 4 cmap that maps "H" (0x48) to glyph 1. +const cmapH = () => + table(44, (v) => { + v.setUint16(2, 1); // one subtable + v.setUint16(4, 3); // platform: Windows + v.setUint16(6, 1); // encoding: Unicode BMP + v.setUint32(8, 12); // subtable offset + v.setUint16(12, 4); // format 4 + v.setUint16(18, 4); // two segments: "H" and the closing 0xFFFF one + v.setUint16(26, 0x48); // end codes + v.setUint16(28, 0xffff); + v.setUint16(32, 0x48); // start codes + v.setUint16(34, 0xffff); + v.setUint16(36, 0x10000 + 1 - 0x48); // id deltas: "H" + delta wraps to 1 + v.setUint16(38, 1); + }); +// Short loca offsets: glyph 0 is empty, glyph 1 takes 12 bytes. +const loca = () => table(6, (v) => v.setUint16(4, 6)); +const glyf = (yMax) => table(12, (v) => v.setInt16(8, yMax)); + +// A font with a cap height in OS/2, and one that needs the "H" glyph. +export const modernTables = () => ({ + head: head(2048), + hhea: hhea(2070), + 'OS/2': os2(4, 1434), +}); +export const oldTables = () => ({ + head: head(1000), + hhea: hhea(1011), + 'OS/2': os2(1, 0), + cmap: cmapH(), + loca: loca(), + glyf: glyf(705), +}); +export const MODERN = { ascender: 2070 / 2048, capHeight: 1434 / 2048 }; +export const OLD = { ascender: 1.011, capHeight: 0.705 }; + +// Helvetica's metrics for every style, as loadFont gives them. +const HELVETICA = { ascender: 0.718, capHeight: 0.718 }; +export const HELVETICA_FONT_METRICS = { + normal: HELVETICA, + bold: HELVETICA, + italics: HELVETICA, + bolditalics: HELVETICA, +}; + +// Lay out a file: a header, one directory entry per table, then the tables. +const pack = (tables, headerSize, entrySize, writeHeader, writeEntry) => { + const tags = Object.keys(tables); + let end = headerSize + tags.length * entrySize; + const offsets = tags.map((tag) => { + const offset = end; + end += tables[tag].length; + return offset; + }); + const bytes = new Uint8Array(end); + const view = new DataView(bytes.buffer); + writeHeader(view, tags.length, end); + tags.forEach((tag, i) => { + const entry = headerSize + i * entrySize; + for (let c = 0; c < 4; c++) bytes[entry + c] = tag.charCodeAt(c); + writeEntry(view, entry, tag, offsets[i]); + bytes.set(tables[tag], offsets[i]); + }); + return bytes; +}; + +// A TTF file, or an OTF one with version 0x4f54544f ("OTTO"). +export const ttf = (tables, version = 0x00010000) => + pack( + tables, + 12, + 16, + (view, numTables) => { + view.setUint32(0, version); + view.setUint16(4, numTables); + }, + (view, entry, tag, offset) => { + view.setUint32(entry + 8, offset); + view.setUint32(entry + 12, tables[tag].length); + }, + ); + +// A WOFF file. Each table is compressed with zlib, unless that doesn't make +// it smaller: then it is stored as it is, as WOFF requires. The tiny loca and +// glyf tables here are stored that way. +export const woff = (tables) => { + const stored = {}; + Object.keys(tables).forEach((tag) => { + const packed = new Uint8Array(deflateSync(tables[tag])); + stored[tag] = packed.length < tables[tag].length ? packed : tables[tag]; + }); + return pack( + stored, + 44, + 20, + (view, numTables, length) => { + view.setUint32(0, 0x774f4646); // "wOFF" + view.setUint32(4, 0x00010000); + view.setUint32(8, length); + view.setUint16(12, numTables); + }, + (view, entry, tag, offset) => { + view.setUint32(entry + 4, offset); + view.setUint32(entry + 8, stored[tag].length); + view.setUint32(entry + 12, tables[tag].length); + }, + ); +}; + +// The first bytes of a WOFF2 file; enough for a signature check. +export const woff2 = () => Uint8Array.from([0x77, 0x4f, 0x46, 0x32, 0, 1, 0, 0]); diff --git a/src/utils/pdf/__tests__/base64.test.js b/src/utils/pdf/__tests__/base64.test.js new file mode 100644 index 00000000..1c3c8fd2 --- /dev/null +++ b/src/utils/pdf/__tests__/base64.test.js @@ -0,0 +1,24 @@ +/** + * @jest-environment node + */ +/* eslint-disable no-magic-numbers */ +import { bytesToBase64, base64ToBytes } from '../base64'; + +describe('base64', () => { + // Longer than one 0x8000-byte chunk, with every byte value. + const bytes = Uint8Array.from({ length: 0x8000 * 2 + 7 }, (_, i) => i % 256); + + it('encodes bytes the way Node does, across chunks', () => { + expect(bytesToBase64(bytes)).toBe(Buffer.from(bytes).toString('base64')); + expect(bytesToBase64(new Uint8Array(0))).toBe(''); + }); + + it('encodes only the bytes a view covers', () => { + const view = bytes.subarray(10, 20); + expect(bytesToBase64(view)).toBe(Buffer.from(view).toString('base64')); + }); + + it('decodes what it encodes', () => { + expect(base64ToBytes(bytesToBase64(bytes))).toEqual(bytes); + }); +}); diff --git a/src/utils/pdf/__tests__/create-document.test.js b/src/utils/pdf/__tests__/create-document.test.js index 8a09b984..a2352124 100644 --- a/src/utils/pdf/__tests__/create-document.test.js +++ b/src/utils/pdf/__tests__/create-document.test.js @@ -3,6 +3,7 @@ */ import { createDocument } from '../create-document'; import { createFakePdfMake } from '../__fixtures__/fake-pdfmake'; +import { HELVETICA_FONT_METRICS } from '../__fixtures__/font-files'; describe('createDocument', () => { beforeEach(() => { @@ -11,13 +12,16 @@ describe('createDocument', () => { }); afterEach(() => jest.restoreAllMocks()); - it('resolves font, runs the template with it, and sets defaultStyle.font', async () => { + it('resolves font, runs the template with it and its metrics, and sets defaultStyle.font', async () => { const { pdfMake } = createFakePdfMake(); const template = jest.fn((data, ctx) => ({ content: [{ text: data.t }], _ctxFont: ctx.font })); const api = await createDocument({ pdfMake, font: 'Helvetica', template, data: { t: 'hi' } }); - expect(template).toHaveBeenCalledWith({ t: 'hi' }, { font: 'Helvetica' }); + expect(template).toHaveBeenCalledWith({ t: 'hi' }, { + font: 'Helvetica', + fontMetrics: HELVETICA_FONT_METRICS, + }); const doc = pdfMake.createPdf.mock.calls[0][0]; expect(doc.defaultStyle.font).toBe('Helvetica'); expect(typeof api.download).toBe('function'); diff --git a/src/utils/pdf/__tests__/font-metrics.test.js b/src/utils/pdf/__tests__/font-metrics.test.js new file mode 100644 index 00000000..bb2ba4d7 --- /dev/null +++ b/src/utils/pdf/__tests__/font-metrics.test.js @@ -0,0 +1,96 @@ +/** + * @jest-environment node + */ +// Node has DecompressionStream, Blob and Response, which jsdom lacks. +/* eslint-disable no-magic-numbers */ +import { fontFormat, isCompleteFontFile, readFontMetrics } from '../font-metrics'; +import { + modernTables, oldTables, ttf, woff, woff2, MODERN, OLD, +} from '../__fixtures__/font-files'; + +const html = new TextEncoder().encode(''); + +describe('fontFormat', () => { + it('tells the format from the first four bytes', () => { + expect(fontFormat(ttf(modernTables()))).toBe('sfnt'); + expect(fontFormat(ttf(modernTables(), 0x4f54544f))).toBe('sfnt'); // OTF + expect(fontFormat(ttf(modernTables(), 0x74727565))).toBe('sfnt'); // "true" + expect(fontFormat(woff(modernTables()))).toBe('woff'); + expect(fontFormat(woff2())).toBe('woff2'); + }); + + it('gives null for other files and files under four bytes', () => { + expect(fontFormat(html)).toBeNull(); + expect(fontFormat(new Uint8Array([0, 1, 0]))).toBeNull(); + }); +}); + +describe('isCompleteFontFile', () => { + it('accepts TTF and WOFF files whose tables lie inside them', () => { + expect(isCompleteFontFile(ttf(oldTables()))).toBe(true); + expect(isCompleteFontFile(woff(oldTables()))).toBe(true); + }); + + it('rejects a file cut short in its tables or in its table directory', () => { + const file = ttf(oldTables()); + expect(isCompleteFontFile(file.slice(0, file.length - 1))).toBe(false); + expect(isCompleteFontFile(file.slice(0, 20))).toBe(false); + const packed = woff(oldTables()); + expect(isCompleteFontFile(packed.slice(0, packed.length - 1))).toBe(false); + }); + + it('rejects other formats', () => { + expect(isCompleteFontFile(woff2())).toBe(false); + expect(isCompleteFontFile(html)).toBe(false); + }); +}); + +describe('readFontMetrics', () => { + it('reads the ascender from hhea and the cap height from OS/2', async () => { + await expect(readFontMetrics(ttf(modernTables()))).resolves.toEqual(MODERN); + // OpenType with CFF outlines has the same tables. + await expect(readFontMetrics(ttf(modernTables(), 0x4f54544f))).resolves.toEqual(MODERN); + }); + + it('measures the H glyph when OS/2 has no cap height', async () => { + await expect(readFontMetrics(ttf(oldTables()))).resolves.toEqual(OLD); + }); + + it("returns null when it can't find a cap height", async () => { + const tables = oldTables(); + delete tables.glyf; + await expect(readFontMetrics(ttf(tables))).resolves.toBeNull(); + }); + + it('inflates the tables of a WOFF file', async () => { + await expect(readFontMetrics(woff(modernTables()))).resolves.toEqual(MODERN); + }); + + it('reads WOFF tables stored compressed or as they are', async () => { + await expect(readFontMetrics(woff(oldTables()))).resolves.toEqual(OLD); + }); + + it("returns null for WOFF where the browser can't inflate it", async () => { + const { DecompressionStream } = global; + delete global.DecompressionStream; + try { + await expect(readFontMetrics(woff(modernTables()))).resolves.toBeNull(); + } finally { + global.DecompressionStream = DecompressionStream; + } + }); + + it("returns null for formats it can't read", async () => { + await expect(readFontMetrics(woff2())).resolves.toBeNull(); + await expect( + readFontMetrics(new TextEncoder().encode('')), + ).resolves.toBeNull(); + }); + + it('rejects for a damaged file', async () => { + await expect(readFontMetrics(ttf(modernTables()).slice(0, 40))).rejects.toThrow(); + const broken = woff(modernTables()); + broken.fill(0xff, 44 + 3 * 20); // tables that don't inflate + await expect(readFontMetrics(broken)).rejects.toThrow(); + }); +}); diff --git a/src/utils/pdf/__tests__/load-image.test.js b/src/utils/pdf/__tests__/load-image.test.js new file mode 100644 index 00000000..76ccd654 --- /dev/null +++ b/src/utils/pdf/__tests__/load-image.test.js @@ -0,0 +1,187 @@ +/** + * @jest-environment jsdom + */ +/* eslint-disable no-magic-numbers */ +// Test data: file signatures, sizes and status codes. +import { TextDecoder, TextEncoder } from 'util'; +import { loadImage } from '../load-image'; +import { bytesToBase64 } from '../base64'; +import { neverAnswers, serveBytes } from '../__fixtures__/fetch'; + +// jsdom doesn't give TextDecoder, which the SVG check uses. +global.TextDecoder = global.TextDecoder || TextDecoder; + +const bytesOf = (text) => [...new TextEncoder().encode(text)]; + +const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; +const JPEG = [0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]; +const GIF = bytesOf('GIF89a'); +const SVG = ` + +`; +// Older design tools declare entities in the doctype. +const SVG_WITH_DOCTYPE = ` + +]> +`; +const HTML_WITH_SVG = `Not found + Page not found`; + +// A browser that decodes the image to the given size, or fails to. With +// `onStall`, it starts decoding, calls `onStall`, and never finishes. +const decodeAs = ({ width, height, fail = false, onStall }) => { + global.Image = class { + set src(value) { + this.naturalWidth = width; + this.naturalHeight = height; + if (onStall) onStall(); + else setTimeout(() => (fail ? this.onerror() : this.onload())); + } + }; + const canvas = { + getContext: () => ({ drawImage: jest.fn() }), + toDataURL: jest.fn(() => 'data:image/png;base64,CANVAS'), + }; + const createElement = document.createElement.bind(document); + jest + .spyOn(document, 'createElement') + .mockImplementation((tag) => (tag === 'canvas' ? canvas : createElement(tag))); + return canvas; +}; + +describe('loadImage', () => { + const OriginalImage = global.Image; + + beforeEach(() => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + URL.createObjectURL = jest.fn(() => 'blob:image'); + URL.revokeObjectURL = jest.fn(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + delete global.fetch; + global.Image = OriginalImage; + }); + + it('returns null without fetching when there is no src', async () => { + global.fetch = jest.fn(); + await expect(loadImage(null)).resolves.toBeNull(); + expect(global.fetch).not.toHaveBeenCalled(); + }); + + it('embeds a PNG as is', async () => { + global.fetch = serveBytes(PNG); + await expect(loadImage('https://cdn.example/logo')).resolves.toEqual({ + image: `data:image/png;base64,${bytesToBase64(Uint8Array.from(PNG))}`, + }); + }); + + it('embeds a JPEG as is', async () => { + global.fetch = serveBytes(JPEG); + await expect(loadImage('https://cdn.example/logo')).resolves.toEqual({ + image: `data:image/jpeg;base64,${bytesToBase64(Uint8Array.from(JPEG))}`, + }); + }); + + it("returns an SVG as markup for pdfmake's svg node", async () => { + global.fetch = serveBytes(bytesOf(SVG)); + await expect(loadImage('https://cdn.example/logo')).resolves.toEqual({ svg: SVG }); + + global.fetch = serveBytes(bytesOf(SVG_WITH_DOCTYPE)); + await expect(loadImage('https://cdn.example/logo')).resolves.toEqual({ svg: SVG_WITH_DOCTYPE }); + }); + + it('does not take an HTML page with an inline svg for an SVG', async () => { + global.fetch = serveBytes(bytesOf(HTML_WITH_SVG)); + decodeAs({ width: 0, height: 0, fail: true }); + await expect(loadImage('https://cdn.example/logo')).resolves.toBeNull(); + expect(console.warn).toHaveBeenCalledWith( + '[pdf] image https://cdn.example/logo skipped:', + "the browser can't read this image", + ); + }); + + it('draws other formats on a canvas, at most 300 x 120 px by default', async () => { + global.fetch = serveBytes(GIF); + const canvas = decodeAs({ width: 1200, height: 200 }); + await expect(loadImage('https://cdn.example/logo.gif')).resolves.toEqual({ + image: 'data:image/png;base64,CANVAS', + }); + expect([canvas.width, canvas.height]).toEqual([300, 50]); + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:image'); + }); + + it('draws within the given maximum size', async () => { + global.fetch = serveBytes(GIF); + const canvas = decodeAs({ width: 1200, height: 600 }); + await loadImage('https://cdn.example/logo.gif', { maxWidth: 600, maxHeight: 150 }); + expect([canvas.width, canvas.height]).toEqual([300, 150]); + }); + + it('does not enlarge a small image', async () => { + global.fetch = serveBytes(GIF); + const canvas = decodeAs({ width: 80, height: 30 }); + await loadImage('https://cdn.example/logo.gif'); + expect([canvas.width, canvas.height]).toEqual([80, 30]); + }); + + it("returns null when the image can't be fetched", async () => { + global.fetch = serveBytes([], { ok: false, status: 404 }); + await expect(loadImage('https://cdn.example/missing.png')).resolves.toBeNull(); + expect(console.warn).toHaveBeenCalledWith( + '[pdf] image https://cdn.example/missing.png skipped:', + 'image fetch failed (404)', + ); + }); + + it('shows only the start of a long src in the warning', async () => { + global.fetch = serveBytes([], { ok: false, status: 400 }); + const src = `data:image/webp;base64,${'A'.repeat(500)}`; + await loadImage(src); + expect(console.warn).toHaveBeenCalledWith( + `[pdf] image ${src.slice(0, 80)}... skipped:`, + expect.any(String), + ); + }); + + it('stops waiting and returns null after 10 seconds', async () => { + jest.useFakeTimers(); + try { + global.fetch = neverAnswers(); + const image = loadImage('https://slow.example/logo.png'); + jest.advanceTimersByTime(10000); + await expect(image).resolves.toBeNull(); + expect(console.warn).toHaveBeenCalledWith( + expect.any(String), + "it didn't load within 10 seconds", + ); + } finally { + jest.useRealTimers(); + } + }); + + it('stops waiting for a decode that never ends after 10 seconds', async () => { + jest.useFakeTimers(); + try { + global.fetch = serveBytes(GIF); + let startDecode; + const decodeStarted = new Promise((resolve) => { + startDecode = resolve; + }); + decodeAs({ width: 80, height: 30, onStall: startDecode }); + const image = loadImage('https://cdn.example/logo.gif'); + await decodeStarted; + jest.advanceTimersByTime(10000); + await expect(image).resolves.toBeNull(); + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:image'); + expect(console.warn).toHaveBeenCalledWith( + expect.any(String), + "it didn't load within 10 seconds", + ); + } finally { + jest.useRealTimers(); + } + }); +}); diff --git a/src/utils/pdf/__tests__/resolve-font.test.js b/src/utils/pdf/__tests__/resolve-font.test.js index 41354b1c..4a108701 100644 --- a/src/utils/pdf/__tests__/resolve-font.test.js +++ b/src/utils/pdf/__tests__/resolve-font.test.js @@ -1,15 +1,28 @@ /** * @jest-environment jsdom */ -import { resolveFont } from '../resolve-font'; +/* eslint-disable no-magic-numbers */ +import { loadFont, resolveFont } from '../resolve-font'; +import { bytesToBase64 } from '../base64'; +import { createFakePdfMake } from '../__fixtures__/fake-pdfmake'; +import { neverAnswers, serveFiles } from '../__fixtures__/fetch'; +import { + modernTables, oldTables, ttf, woff2, MODERN, OLD, HELVETICA_FONT_METRICS, +} from '../__fixtures__/font-files'; -const fakePdfMake = () => ({ addFontContainer: jest.fn() }); +const HELVETICA_FONT = { family: 'Helvetica', fontMetrics: HELVETICA_FONT_METRICS }; -describe('resolveFont', () => { - afterEach(() => jest.restoreAllMocks()); +const newPdfMake = () => createFakePdfMake().pdfMake; + +beforeEach(() => jest.spyOn(console, 'warn').mockImplementation(() => {})); +afterEach(() => { + jest.restoreAllMocks(); + delete global.fetch; +}); +describe('resolveFont', () => { it('falls back to Helvetica for none / standard, registering nothing', async () => { - const pdfMake = fakePdfMake(); + const pdfMake = newPdfMake(); await expect(resolveFont(pdfMake, undefined)).resolves.toBe('Helvetica'); await expect(resolveFont(pdfMake, 'Helvetica')).resolves.toBe('Helvetica'); await expect(resolveFont(pdfMake, { family: 'Helvetica' })).resolves.toBe('Helvetica'); @@ -18,38 +31,206 @@ describe('resolveFont', () => { it('registers an imported/pre-baked container without fetching', async () => { global.fetch = jest.fn(); - const pdfMake = fakePdfMake(); + const pdfMake = newPdfMake(); const font = { family: 'Imported', vfs: { 'Imported-normal.ttf': 'QUFB' }, fonts: { Imported: { normal: 'Imported-normal.ttf' } } }; await expect(resolveFont(pdfMake, font)).resolves.toBe('Imported'); expect(global.fetch).not.toHaveBeenCalled(); - expect(pdfMake.addFontContainer).toHaveBeenCalledWith({ vfs: font.vfs, fonts: font.fonts }); + expect(pdfMake.addFontContainer).toHaveBeenCalledWith({ + vfs: font.vfs, + fonts: { + Imported: { + normal: 'Imported-normal.ttf', + bold: 'Imported-normal.ttf', + italics: 'Imported-normal.ttf', + bolditalics: 'Imported-normal.ttf', + }, + }, + }); }); it('falls back to Helvetica when a pre-baked container does not define its family', async () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - const pdfMake = fakePdfMake(); + const pdfMake = newPdfMake(); const font = { family: 'Brand', vfs: { 'BrandSans-normal.ttf': 'QUFB' }, fonts: { BrandSans: { normal: 'BrandSans-normal.ttf' } } }; await expect(resolveFont(pdfMake, font)).resolves.toBe('Helvetica'); expect(pdfMake.addFontContainer).not.toHaveBeenCalled(); }); it('fetches + base64s a URL font and registers a container', async () => { - global.fetch = jest.fn(() => Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(new Uint8Array([65, 66, 67]).buffer) })); - const pdfMake = fakePdfMake(); + const normal = ttf(modernTables()); + const bold = ttf(oldTables()); + global.fetch = serveFiles({ 'https://x/n.ttf': normal, 'https://x/b.ttf': bold }); + const pdfMake = newPdfMake(); const fam = await resolveFont(pdfMake, { family: 'Brand', urls: { normal: 'https://x/n.ttf', bold: 'https://x/b.ttf' } }); expect(fam).toBe('Brand'); expect(global.fetch).toHaveBeenCalledTimes(2); const container = pdfMake.addFontContainer.mock.calls[0][0]; - expect(container.vfs['Brand-normal.ttf']).toBe('QUJD'); // base64 of [65,66,67] + expect(container.vfs['Brand-normal.ttf']).toBe(bytesToBase64(normal)); + expect(container.vfs['Brand-bold.ttf']).toBe(bytesToBase64(bold)); expect(container.fonts.Brand.normal).toBe('Brand-normal.ttf'); expect(container.fonts.Brand.bold).toBe('Brand-bold.ttf'); }); it('falls back to Helvetica when the URL font fails to fetch', async () => { - global.fetch = jest.fn(() => Promise.resolve({ ok: false, status: 403 })); - const pdfMake = fakePdfMake(); + global.fetch = serveFiles({}); + const pdfMake = newPdfMake(); const fam = await resolveFont(pdfMake, { family: 'Broken', urls: { normal: 'https://x/nope.ttf' } }); expect(fam).toBe('Helvetica'); expect(pdfMake.addFontContainer).not.toHaveBeenCalled(); }); }); + +describe('loadFont', () => { + it("gives Helvetica's metrics for every style without a font", async () => { + await expect(loadFont(newPdfMake(), undefined)).resolves.toEqual(HELVETICA_FONT); + }); + + it("gives each style's metrics, read from the file that prints it", async () => { + global.fetch = serveFiles({ 'https://m/n.ttf': ttf(modernTables()), 'https://m/b.ttf': ttf(oldTables()) }); + const font = await loadFont(newPdfMake(), { + family: 'Metrics', + urls: { normal: 'https://m/n.ttf', bold: 'https://m/b.ttf' }, + }); + expect(font).toEqual({ + family: 'Metrics', + fontMetrics: { normal: MODERN, bold: OLD, italics: MODERN, bolditalics: OLD }, + }); + }); + + it('fetches each URL once and fills missing styles from the closest one', async () => { + global.fetch = serveFiles({ 'https://f/r.ttf': ttf(modernTables()) }); + const pdfMake = newPdfMake(); + await loadFont(pdfMake, { family: 'Regular', urls: { normal: 'https://f/r.ttf' } }); + expect(global.fetch).toHaveBeenCalledTimes(1); + const { vfs, fonts } = pdfMake.addFontContainer.mock.calls[0][0]; + expect(Object.keys(vfs)).toEqual(['Regular-normal.ttf']); + expect(fonts.Regular).toEqual({ + normal: 'Regular-normal.ttf', + bold: 'Regular-normal.ttf', + italics: 'Regular-normal.ttf', + bolditalics: 'Regular-normal.ttf', + }); + + global.fetch = serveFiles({ 'https://f/n.ttf': ttf(modernTables()), 'https://f/b.ttf': ttf(oldTables()) }); + const twoFiles = newPdfMake(); + await loadFont(twoFiles, { family: 'Two', urls: { normal: 'https://f/n.ttf', bold: 'https://f/b.ttf' } }); + expect(twoFiles.addFontContainer.mock.calls[0][0].fonts.Two).toEqual({ + normal: 'Two-normal.ttf', + bold: 'Two-bold.ttf', + italics: 'Two-normal.ttf', + bolditalics: 'Two-bold.ttf', + }); + }); + + it('caches a font, so the next document does not fetch it again', async () => { + global.fetch = serveFiles({ 'https://c/r.ttf': ttf(modernTables()) }); + const font = { family: 'Cached', urls: { normal: 'https://c/r.ttf' } }; + const first = await loadFont(newPdfMake(), font); + const pdfMake = newPdfMake(); + await expect(loadFont(pdfMake, font)).resolves.toEqual(first); + expect(global.fetch).toHaveBeenCalledTimes(1); + expect(pdfMake.addFontContainer).toHaveBeenCalled(); + }); + + it("prints a font whose metrics can't be read, with null metrics", async () => { + const tables = modernTables(); + delete tables['OS/2']; + global.fetch = serveFiles({ 'https://n/r.ttf': ttf(tables) }); + const pdfMake = newPdfMake(); + const font = await loadFont(pdfMake, { family: 'NoMetrics', urls: { normal: 'https://n/r.ttf' } }); + expect(font.family).toBe('NoMetrics'); + expect(font.fontMetrics.normal).toBeNull(); + expect(pdfMake.addFontContainer).toHaveBeenCalled(); + }); + + it("falls back to Helvetica for a file that isn't a font, and tries again next time", async () => { + const html = Uint8Array.from('Not found', (c) => c.charCodeAt(0)); + global.fetch = serveFiles({ 'https://h/r.ttf': html }); + const font = { family: 'Html', urls: { normal: 'https://h/r.ttf' } }; + const pdfMake = newPdfMake(); + await expect(loadFont(pdfMake, font)).resolves.toEqual(HELVETICA_FONT); + expect(pdfMake.addFontContainer).not.toHaveBeenCalled(); + expect(console.warn).toHaveBeenCalledWith( + '[pdf] font "Html" failed, using Helvetica:', + 'not a TTF, OTF or WOFF file: https://h/r.ttf', + ); + + global.fetch = serveFiles({ 'https://h/r.ttf': ttf(modernTables()) }); + await expect(loadFont(newPdfMake(), font)).resolves.toMatchObject({ family: 'Html' }); + }); + + it('falls back to Helvetica for a file cut short, and tries again next time', async () => { + const file = ttf(oldTables()); + global.fetch = serveFiles({ 'https://t/r.ttf': file.slice(0, file.length - 10) }); + const font = { family: 'Cut', urls: { normal: 'https://t/r.ttf' } }; + await expect(loadFont(newPdfMake(), font)).resolves.toEqual(HELVETICA_FONT); + expect(console.warn).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('cut short')); + + global.fetch = serveFiles({ 'https://t/r.ttf': file }); + await expect(loadFont(newPdfMake(), font)).resolves.toMatchObject({ family: 'Cut' }); + }); + + it('falls back to Helvetica for WOFF2, which pdfmake prints blank', async () => { + global.fetch = serveFiles({ 'https://w/r.woff2': woff2() }); + await expect( + loadFont(newPdfMake(), { family: 'Woff2', urls: { normal: 'https://w/r.woff2' } }), + ).resolves.toEqual(HELVETICA_FONT); + expect(console.warn).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('WOFF2')); + }); + + it('falls back to Helvetica for the whole font when one of its files fails, and stops the others', async () => { + const slow = neverAnswers(); + global.fetch = jest.fn((url, options) => (url === 'https://p/b.ttf' + ? slow(url, options) + : Promise.resolve({ ok: false, status: 404 }))); + const pdfMake = newPdfMake(); + await expect( + loadFont(pdfMake, { family: 'Partial', urls: { normal: 'https://p/n.ttf', bold: 'https://p/b.ttf' } }), + ).resolves.toEqual(HELVETICA_FONT); + expect(pdfMake.addFontContainer).not.toHaveBeenCalled(); + expect(slow.mock.calls[0][1].signal.aborted).toBe(true); + expect(console.warn).toHaveBeenCalledWith(expect.any(String), 'font fetch failed (404): https://p/n.ttf'); + }); + + it('stops waiting after 10 seconds, uses Helvetica, and tries again next time', async () => { + jest.useFakeTimers(); + try { + global.fetch = neverAnswers(); + const font = { family: 'Slow', urls: { normal: 'https://s/r.ttf' } }; + const loading = loadFont(newPdfMake(), font); + jest.advanceTimersByTime(10000); + await expect(loading).resolves.toEqual(HELVETICA_FONT); + expect(console.warn).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('10 seconds')); + + global.fetch = serveFiles({ 'https://s/r.ttf': ttf(modernTables()) }); + await expect(loadFont(newPdfMake(), font)).resolves.toMatchObject({ family: 'Slow' }); + } finally { + jest.useRealTimers(); + } + }); + + it('falls back to Helvetica for a URL font without a file URL', async () => { + global.fetch = jest.fn(); + await expect(loadFont(newPdfMake(), { family: 'Empty', urls: {} })).resolves.toEqual(HELVETICA_FONT); + expect(global.fetch).not.toHaveBeenCalled(); + }); + + it('falls back to Helvetica for a pre-baked container without files', async () => { + const pdfMake = newPdfMake(); + await expect( + loadFont(pdfMake, { family: 'Bare', vfs: {}, fonts: { Bare: {} } }), + ).resolves.toEqual(HELVETICA_FONT); + expect(pdfMake.addFontContainer).not.toHaveBeenCalled(); + }); + + it("reads a pre-baked container's metrics from its vfs", async () => { + const font = { + family: 'Baked', + vfs: { 'Baked-normal.ttf': bytesToBase64(ttf(modernTables())), 'Baked-bold.ttf': bytesToBase64(ttf(oldTables())) }, + fonts: { Baked: { normal: 'Baked-normal.ttf', bold: 'Baked-bold.ttf' } }, + }; + await expect(loadFont(newPdfMake(), font)).resolves.toEqual({ + family: 'Baked', + fontMetrics: { normal: MODERN, bold: OLD, italics: MODERN, bolditalics: OLD }, + }); + }); +}); diff --git a/src/utils/pdf/base64.js b/src/utils/pdf/base64.js new file mode 100644 index 00000000..aa15e1f0 --- /dev/null +++ b/src/utils/pdf/base64.js @@ -0,0 +1,26 @@ +// String.fromCharCode takes the bytes as arguments, and a whole font file is +// more arguments than a browser allows, so the bytes go in chunks. +const CHUNK = 0x8000; + +/** + * @param {Uint8Array} bytes + * @returns {string} base64 + */ +export const bytesToBase64 = (bytes) => { + let binary = ''; + for (let i = 0; i < bytes.length; i += CHUNK) { + binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK)); + } + return btoa(binary); +}; + +/** + * @param {string} base64 + * @returns {Uint8Array} + */ +export const base64ToBytes = (base64) => { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +}; diff --git a/src/utils/pdf/create-document.js b/src/utils/pdf/create-document.js index fa80951f..a6e8c283 100644 --- a/src/utils/pdf/create-document.js +++ b/src/utils/pdf/create-document.js @@ -1,27 +1,32 @@ -import { resolveFont } from './resolve-font'; +import { loadFont } from './resolve-font'; import { downloadBlob } from './download-blob'; /** * Build a PDF from a pure template and return the output verbs. * * The consumer passes its own (externalized, shared) `pdfMake` instance so there - * is one VFS. The `template` is a pure `(data, { font }) -> docDefinition`; the - * resolved family is applied to `defaultStyle.font`. Images referenced by the - * template must already be base64 `data:` URLs (see imageDataUrl) — pdfmake's - * browser build won't fetch remote images. + * is one VFS. The `template` is a pure `(data, { font, fontMetrics }) -> + * docDefinition`; the resolved family is applied to `defaultStyle.font`. + * `fontMetrics` gives each style's ascender and capital height (see loadFont). + * A style's metrics are null when its file can't be read for them, so a + * template checks before it uses them. + * Images referenced by the template must already be base64 `data:` URLs or svg + * markup (see loadImage) — pdfmake's browser build won't fetch remote images. * * @param {object} params.pdfMake consumer's pdfmake instance - * @param {*} params.font FontSpec (see resolveFont); omit for Helvetica - * @param {Function} params.template (data, { font }) => docDefinition + * @param {*} params.font FontSpec (see loadFont); omit for Helvetica + * @param {Function} params.template (data, { font, fontMetrics }) => docDefinition * @param {*} params.data payload for the template - * @param {Function} [params.onError] called on any build/fetch/layout failure + * @param {Function} [params.onError] called when building or outputting the + * document fails. A font that can't be loaded doesn't call it: the document + * prints in Helvetica instead. * @returns {Promise<{download, open, print, getBlob, getBase64}>} */ export const createDocument = async ({ pdfMake, font, template, data, onError }) => { let handle; try { - const family = await resolveFont(pdfMake, font); - const doc = template(data, { font: family }); + const { family, fontMetrics } = await loadFont(pdfMake, font); + const doc = template(data, { font: family, fontMetrics }); doc.defaultStyle = { font: family, ...(doc.defaultStyle || {}) }; handle = pdfMake.createPdf(doc); } catch (err) { diff --git a/src/utils/pdf/font-metrics.js b/src/utils/pdf/font-metrics.js new file mode 100644 index 00000000..7f75e8aa --- /dev/null +++ b/src/utils/pdf/font-metrics.js @@ -0,0 +1,206 @@ +/* eslint-disable no-magic-numbers */ +// The byte offsets, table versions and units below come from the OpenType and +// WOFF specs. + +// The first four bytes of each font format. +const SFNT_VERSIONS = [ + 0x00010000, // TrueType + 0x4f54544f, // "OTTO", OpenType with CFF outlines + 0x74727565, // "true", older Apple TrueType +]; +const WOFF_SIGNATURE = 0x774f4646; // "wOFF" +const WOFF2_SIGNATURE = 0x774f4632; // "wOF2" +const CAPITAL_H = 0x48; + +const viewOf = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + +const tagAt = (view, offset) => + String.fromCharCode(...[0, 1, 2, 3].map((i) => view.getUint8(offset + i))); + +/** + * Tell a font file's format from its first four bytes. + * + * @param {Uint8Array} bytes + * @returns {'sfnt'|'woff'|'woff2'|null} 'sfnt' is a TTF or OTF file; null is + * anything else, such as an HTML page or a font collection + */ +export const fontFormat = (bytes) => { + if (bytes.length < 4) return null; + const signature = viewOf(bytes).getUint32(0); + if (SFNT_VERSIONS.includes(signature)) return 'sfnt'; + if (signature === WOFF_SIGNATURE) return 'woff'; + if (signature === WOFF2_SIGNATURE) return 'woff2'; + return null; +}; + +// Where each table sits in a TTF, OTF or WOFF file, by tag: its offset and +// the bytes it takes in the file. A WOFF table also gives its size once +// inflated. Throws when the file ends inside the directory. +const tableDirectory = (view, format) => { + const entries = {}; + if (format === 'sfnt') { + const numTables = view.getUint16(4); + for (let i = 0; i < numTables; i++) { + const record = 12 + i * 16; + entries[tagAt(view, record)] = { + offset: view.getUint32(record + 8), + length: view.getUint32(record + 12), + }; + } + } else { + const numTables = view.getUint16(12); + for (let i = 0; i < numTables; i++) { + const entry = 44 + i * 20; + entries[tagAt(view, entry)] = { + offset: view.getUint32(entry + 4), + length: view.getUint32(entry + 8), + origLength: view.getUint32(entry + 12), + }; + } + } + return entries; +}; + +/** + * Whether every table of a TTF, OTF or WOFF file lies inside the file. A file + * cut short, or with a damaged table directory, fails this and would fail + * pdfmake when it prints. + * + * @param {Uint8Array} bytes + * @returns {boolean} + */ +export const isCompleteFontFile = (bytes) => { + const format = fontFormat(bytes); + if (format !== 'sfnt' && format !== 'woff') return false; + let entries; + try { + entries = tableDirectory(viewOf(bytes), format); + } catch (err) { + return false; + } + return Object.keys(entries).every((tag) => + entries[tag].offset + entries[tag].length <= bytes.length); +}; + +const inflate = async (data) => { + const stream = new Blob([data]) + .stream() + .pipeThrough(new DecompressionStream('deflate')); + return new DataView(await new Response(stream).arrayBuffer()); +}; + +// Returns a function that gives a table's DataView by tag. A TTF or OTF file +// stores its tables as they are. A WOFF file compresses each table with zlib, +// unless that doesn't make it smaller; only the tables asked for are inflated. +const fontTables = (bytes) => { + const format = fontFormat(bytes); + const woff = format === 'woff'; + if (format !== 'sfnt' && !(woff && typeof DecompressionStream !== 'undefined')) { + return null; + } + const view = viewOf(bytes); + const entries = tableDirectory(view, format); + return async (tag) => { + const table = entries[tag]; + if (!table) return undefined; + const data = new DataView(view.buffer, view.byteOffset + table.offset, table.length); + return woff && table.length < table.origLength ? inflate(data) : data; + }; +}; + +// Look up a character's glyph id in a Unicode format 4 cmap subtable. +const glyphId = (cmap, code) => { + const numSubtables = cmap.getUint16(2); + for (let i = 0; i < numSubtables; i++) { + const record = 4 + i * 8; + const platform = cmap.getUint16(record); + const encoding = cmap.getUint16(record + 2); + const subtable = cmap.getUint32(record + 4); + const unicode = platform === 0 || (platform === 3 && encoding === 1); + if (unicode && cmap.getUint16(subtable) === 4) { + const segCountX2 = cmap.getUint16(subtable + 6); + const endCodes = subtable + 14; + const startCodes = endCodes + segCountX2 + 2; + const idDeltas = startCodes + segCountX2; + const idRangeOffsets = idDeltas + segCountX2; + for (let seg = 0; seg < segCountX2; seg += 2) { + if (code <= cmap.getUint16(endCodes + seg)) { + const start = cmap.getUint16(startCodes + seg); + if (code < start) return 0; + const delta = cmap.getUint16(idDeltas + seg); + const rangeOffset = cmap.getUint16(idRangeOffsets + seg); + // Glyph ids wrap around at 65536. + if (rangeOffset === 0) return (code + delta) % 0x10000; + const id = cmap.getUint16( + idRangeOffsets + seg + rangeOffset + (code - start) * 2, + ); + return id === 0 ? 0 : (id + delta) % 0x10000; + } + } + } + } + return 0; +}; + +// The top of the "H" glyph's outline, in font units. Only TrueType outlines +// (the glyf table) are read. +const capitalHTop = async (table, head) => { + const [cmap, loca, glyf] = await Promise.all([ + table('cmap'), + table('loca'), + table('glyf'), + ]); + if (!cmap || !loca || !glyf) return null; + const id = glyphId(cmap, CAPITAL_H); + if (!id) return null; + const longOffsets = head.getInt16(50) === 1; + const offsetOf = (i) => + longOffsets ? loca.getUint32(i * 4) : loca.getUint16(i * 2) * 2; + const offset = offsetOf(id); + if (offsetOf(id + 1) === offset) return null; // a glyph with no outline + return glyf.getInt16(offset + 8); // yMax +}; + +/** + * Read a font's ascender and capital height, per em, from a TTF, OTF or WOFF + * file. + * + * pdfmake puts a line's baseline one ascender below the top of the line, and + * takes the ascender from the hhea table. Fonts differ a lot here, so text + * sits at a different height in its line in each font. A template that draws + * shapes around text (a pill behind a title, for example) needs these to + * line the two up. + * + * The capital height comes from the OS/2 table. Fonts whose OS/2 table is too + * old to have it get the height of their "H" glyph instead. + * + * @param {Uint8Array} bytes - a TTF, OTF or WOFF file + * @returns {Promise<{ascender: number, capHeight: number}|null>} null for + * other formats, for WOFF in a browser that can't inflate it, or when a + * value can't be found. It rejects for a damaged file. + */ +export const readFontMetrics = async (bytes) => { + const table = fontTables(bytes); + if (!table) return null; + + const [head, hhea, os2] = await Promise.all([ + table('head'), + table('hhea'), + table('OS/2'), + ]); + if (!head || !hhea) return null; + const unitsPerEm = head.getUint16(18); + if (!unitsPerEm) return null; + + // OS/2 has sCapHeight from version 2. + let capHeight = os2 && os2.getUint16(0) >= 2 ? os2.getInt16(88) : 0; + if (capHeight <= 0) capHeight = (await capitalHTop(table, head)) || 0; + if (capHeight <= 0) return null; + + return { + ascender: hhea.getInt16(4) / unitsPerEm, + capHeight: capHeight / unitsPerEm, + }; +}; + +export default readFontMetrics; diff --git a/src/utils/pdf/image-data-url.js b/src/utils/pdf/image-data-url.js index 78cce72b..c9fb88ac 100644 --- a/src/utils/pdf/image-data-url.js +++ b/src/utils/pdf/image-data-url.js @@ -1,3 +1,13 @@ +const cache = new Map(); + +const blobToDataUrl = (blob) => + new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = () => reject(reader.error || new Error('FileReader failed')); + reader.readAsDataURL(blob); + }); + /** * Resolve an image source to a base64 `data:` URL for pdfmake. * @@ -6,19 +16,12 @@ * that is already a `data:` URL (e.g. a bundled/imported asset) is returned * unchanged. Results are cached (and in-flight deduped) by source. * + * pdfmake's image node reads only PNG and JPEG. Use loadImage for other + * formats (SVG, WebP...) or for a time limit. + * * @param {string} src - http(s) URL or an existing data: URL * @returns {Promise} data: URL, or null for a falsy src */ -const cache = new Map(); - -const blobToDataUrl = (blob) => - new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(reader.result); - reader.onerror = () => reject(reader.error || new Error('FileReader failed')); - reader.readAsDataURL(blob); - }); - export const imageDataUrl = (src) => { if (!src) return Promise.resolve(null); if (src.indexOf('data:') === 0) return Promise.resolve(src); diff --git a/src/utils/pdf/index.js b/src/utils/pdf/index.js index 59cdc560..a0a72c60 100644 --- a/src/utils/pdf/index.js +++ b/src/utils/pdf/index.js @@ -1,5 +1,6 @@ export { createDocument } from './create-document'; -export { resolveFont } from './resolve-font'; +export { resolveFont, loadFont } from './resolve-font'; export { imageDataUrl } from './image-data-url'; +export { loadImage } from './load-image'; export { downloadBlob } from './download-blob'; export { field, badge } from './nodes'; diff --git a/src/utils/pdf/load-image.js b/src/utils/pdf/load-image.js new file mode 100644 index 00000000..d1f625b1 --- /dev/null +++ b/src/utils/pdf/load-image.js @@ -0,0 +1,131 @@ +/* eslint-disable no-magic-numbers */ +// File signatures and pixel sizes are data here. +import { bytesToBase64 } from './base64'; + +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47]; +const JPEG_SIGNATURE = [0xff, 0xd8, 0xff]; +const SVG_SNIFF_BYTES = 1024; +const IMAGE_TIMEOUT_MS = 10000; +// The default suits a small image such as a logo: three times a 100 x 40 pt +// box, so it stays sharp in print. +const DEFAULT_MAX_WIDTH = 300; +const DEFAULT_MAX_HEIGHT = 120; +// What may come before an SVG's root element: white space, an XML +// declaration, comments, and a doctype, which can hold entity declarations. +const SVG_PROLOG = /^(?:\s|<\?[\s\S]*?\?>||[]*(?:\[[\s\S]*?\])?\s*>)*/i; + +const hasSignature = (bytes, signature) => + signature.every((byte, i) => bytes[i] === byte); + +// An SVG file starts with an element, after its prolog. An HTML page +// that holds an inline starts with instead. +const isSvg = (bytes) => { + // TextDecoder drops a leading byte order mark. + const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES)); + return /^]/i.test(head.replace(SVG_PROLOG, '')); +}; + +// A data: URL can be long, so a warning shows only its start. +const shortened = (src) => (src.length > 80 ? `${src.slice(0, 80)}...` : src); + +// `signal` stops a decode that runs past the time limit. +const rasterize = (blob, maxWidth, maxHeight, signal) => + new Promise((resolve, reject) => { + const objectUrl = URL.createObjectURL(blob); + const img = new Image(); + const onAbort = () => { + img.onload = null; + img.onerror = null; + cleanUp(); + reject(new Error('aborted')); + }; + const cleanUp = () => { + signal.removeEventListener('abort', onAbort); + URL.revokeObjectURL(objectUrl); + }; + if (signal.aborted) { + onAbort(); + return; + } + signal.addEventListener('abort', onAbort, { once: true }); + img.onload = () => { + try { + const scale = Math.min( + 1, + maxWidth / img.naturalWidth, + maxHeight / img.naturalHeight, + ); + const canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(img.naturalWidth * scale)); + canvas.height = Math.max(1, Math.round(img.naturalHeight * scale)); + canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height); + resolve(canvas.toDataURL('image/png')); + } catch (err) { + reject(err); + } finally { + cleanUp(); + } + }; + img.onerror = () => { + cleanUp(); + reject(new Error("the browser can't read this image")); + }; + img.src = objectUrl; + }); + +/** + * Load an image, a logo for example, for a pdfmake document. + * + * pdfmake's image node reads only PNG and JPEG, and its browser build won't + * fetch a URL itself (getBlob hangs). So: + * - PNG and JPEG are embedded as they are. + * - SVG goes to pdfmake's svg node and prints as vector. + * - Any other format the browser can show (WebP, GIF, AVIF...) is drawn on a + * canvas and embedded as PNG. `maxWidth` and `maxHeight` cap the canvas in + * pixels. The default suits a small image such as a logo; pass a bigger + * size for a bigger image. + * + * The format comes from the file's first bytes, not the Content-Type header, + * which servers and CDNs often send as a generic type. + * + * @param {string} src - http(s) or data: URL + * @param {object} [options] + * @param {number} [options.maxWidth=300] + * @param {number} [options.maxHeight=120] + * @returns {Promise<{image: string}|{svg: string}|null>} a node to spread into + * the document (`{ ...logo, fit: [100, 40] }`), or null when there is no + * src, it doesn't load within 10 seconds, or it can't be read + */ +export const loadImage = async ( + src, + { maxWidth = DEFAULT_MAX_WIDTH, maxHeight = DEFAULT_MAX_HEIGHT } = {}, +) => { + if (!src) return null; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), IMAGE_TIMEOUT_MS); + try { + const res = await fetch(src, { signal: controller.signal }); + if (!res.ok) throw new Error(`image fetch failed (${res.status})`); + const blob = await res.blob(); + const bytes = new Uint8Array(await blob.arrayBuffer()); + if (hasSignature(bytes, PNG_SIGNATURE)) { + return { image: `data:image/png;base64,${bytesToBase64(bytes)}` }; + } + if (hasSignature(bytes, JPEG_SIGNATURE)) { + return { image: `data:image/jpeg;base64,${bytesToBase64(bytes)}` }; + } + if (isSvg(bytes)) return { svg: new TextDecoder().decode(bytes) }; + return { image: await rasterize(blob, maxWidth, maxHeight, controller.signal) }; + } catch (err) { + const reason = controller.signal.aborted + ? `it didn't load within ${IMAGE_TIMEOUT_MS / 1000} seconds` + : err && err.message; + // eslint-disable-next-line no-console + console.warn(`[pdf] image ${shortened(src)} skipped:`, reason); + return null; + } finally { + clearTimeout(timer); + } +}; + +export default loadImage; diff --git a/src/utils/pdf/resolve-font.js b/src/utils/pdf/resolve-font.js index 4390a1b3..ad91905e 100644 --- a/src/utils/pdf/resolve-font.js +++ b/src/utils/pdf/resolve-font.js @@ -1,5 +1,5 @@ /** - * Resolve a FontSpec into a registered pdfmake font family. + * Load a FontSpec for pdfmake: register its files and read its metrics. * * pdfmake's browser build won't fetch font URLs itself (getBlob hangs), so a * URL font must be fetched + base64'd and registered via addFontContainer. This @@ -12,84 +12,209 @@ * { family, vfs, fonts } imported/pre-baked base64 container (no fetch) * { family, urls: { normal, bold } } runtime-dynamic; we fetch + base64 + cache * - * @param {object} pdfMake - the consumer's pdfmake instance - * @param {string|object} font - FontSpec - * @returns {Promise} the font family to use as defaultStyle.font + * A font may also give `italics` and `bolditalics`. pdfmake fails a document + * that uses a style its font has no file for, so a missing style uses the + * closest one the font has: bold and italics use the regular file, bold + * italics uses the bold one. A font with no file at all falls back to + * Helvetica. + * + * A URL font also falls back to Helvetica when a file can't be fetched, + * doesn't download within 10 seconds, isn't a TTF, OTF or WOFF file (an HTML + * error page, for example), or is cut short. WOFF2 falls back too: pdfmake + * prints most WOFF2 fonts as blank text, without an error. None of these is + * cached, so the next document tries the font again. */ +/* eslint-disable no-magic-numbers */ +import { bytesToBase64, base64ToBytes } from './base64'; +import { fontFormat, isCompleteFontFile, readFontMetrics } from './font-metrics'; + const HELVETICA = 'Helvetica'; +const STYLES = ['normal', 'bold', 'italics', 'bolditalics']; +const FONT_TIMEOUT_MS = 10000; -// Cache resolved URL containers so repeated prints don't refetch. Keyed by the -// url set; stores the in-flight/resolved container promise. -const containerCache = new Map(); +// Adobe's AFM files for Helvetica, Helvetica-Bold, Helvetica-Oblique and +// Helvetica-BoldOblique, which pdfmake ships, give the same Ascender and +// CapHeight for all four: 718 per 1000 units. +const HELVETICA_METRICS = { ascender: 0.718, capHeight: 0.718 }; + +// Cache resolved URL fonts so repeated prints don't refetch. Keyed by the url +// set; stores the in-flight/resolved { container, fontMetrics } promise. +const fontCache = new Map(); + +const allStyles = (value) => + STYLES.reduce((acc, style) => ({ ...acc, [style]: value }), {}); + +const helvetica = () => ({ family: HELVETICA, fontMetrics: allStyles(HELVETICA_METRICS) }); + +// Give every style a file, taken from the closest style the font has. +const fillStyles = (files) => { + const normal = files.normal || files.bold || files.italics || files.bolditalics; + const bold = files.bold || normal; + return { + normal, + bold, + italics: files.italics || normal, + bolditalics: files.bolditalics || bold, + }; +}; -const arrayBufferToBase64 = (buffer) => { - let binary = ''; - const bytes = new Uint8Array(buffer); - const CHUNK = 0x8000; - for (let i = 0; i < bytes.length; i += CHUNK) { - binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK)); +// The metrics only help a template place shapes around text, so a file they +// can't be read from still prints. +const readMetricsOrNull = async (bytes) => { + try { + return await readFontMetrics(bytes); + } catch (err) { + return null; } - return btoa(binary); }; -const fetchFontBase64 = (url) => - fetch(url).then((res) => { - if (!res.ok) throw new Error(`font fetch failed: ${res.status}`); - return res.arrayBuffer(); - }).then(arrayBufferToBase64); +// A pre-baked container's files are base64 strings in its vfs. +const readVfsMetricsOrNull = async (file) => { + if (typeof file !== 'string') return null; + let bytes; + try { + bytes = base64ToBytes(file); + } catch (err) { + return null; + } + return readMetricsOrNull(bytes); +}; -// Build a pdfmake font container { vfs, fonts } from a set of weight -> URL. -const containerFromUrls = async (family, urls) => { - const vfs = {}; - const fonts = { [family]: {} }; +// Each style's metrics: those of the file it prints with. `readFile` runs +// once per file, even when several styles share it. +const metricsByStyle = async (files, readFile) => { + const metricsByFile = {}; + STYLES.forEach((style) => { + if (!(files[style] in metricsByFile)) metricsByFile[files[style]] = readFile(files[style]); + }); + const fontMetrics = {}; await Promise.all( - Object.keys(urls).map(async (weight) => { - const file = `${family}-${weight}.ttf`; - vfs[file] = await fetchFontBase64(urls[weight]); - fonts[family][weight] = file; + STYLES.map(async (style) => { + fontMetrics[style] = await metricsByFile[files[style]]; }), ); - return { vfs, fonts }; + return fontMetrics; +}; + +const checkFontFile = (bytes, url) => { + const format = fontFormat(bytes); + if (format === 'woff2') { + throw new Error(`pdfmake prints WOFF2 fonts as blank text, use a TTF, OTF or WOFF file: ${url}`); + } + if (!format) throw new Error(`not a TTF, OTF or WOFF file: ${url}`); + if (!isCompleteFontFile(bytes)) throw new Error(`the font file is cut short or damaged: ${url}`); +}; + +const fetchFontFile = async (url, signal) => { + const res = await fetch(url, { signal }); + if (!res.ok) throw new Error(`font fetch failed (${res.status}): ${url}`); + const bytes = new Uint8Array(await res.arrayBuffer()); + checkFontFile(bytes, url); + return bytes; +}; + +// Fetch a URL font's files, each URL once, and build a pdfmake font container +// { vfs, fonts } plus each style's metrics. +const loadUrlFont = async (family, urls) => { + const styles = fillStyles(urls); + if (!styles.normal) throw new Error('the font has no file URL'); + + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FONT_TIMEOUT_MS); + const bytesByUrl = {}; + try { + await Promise.all( + [...new Set(STYLES.map((style) => styles[style]))].map(async (url) => { + bytesByUrl[url] = await fetchFontFile(url, controller.signal); + }), + ); + } catch (err) { + if (controller.signal.aborted) { + throw new Error(`the font didn't download within ${FONT_TIMEOUT_MS / 1000} seconds`); + } + controller.abort(); // the other files aren't needed any more + throw err; + } finally { + clearTimeout(timer); + } + + // One vfs file per URL, named after the first style that uses it. + const vfsNameByUrl = {}; + const vfs = {}; + const fonts = { [family]: {} }; + STYLES.forEach((style) => { + const url = styles[style]; + if (!vfsNameByUrl[url]) { + vfsNameByUrl[url] = `${family}-${style}.ttf`; + vfs[vfsNameByUrl[url]] = bytesToBase64(bytesByUrl[url]); + } + fonts[family][style] = vfsNameByUrl[url]; + }); + const fontMetrics = await metricsByStyle(styles, (url) => readMetricsOrNull(bytesByUrl[url])); + return { container: { vfs, fonts }, fontMetrics }; }; -export const resolveFont = async (pdfMake, font) => { - if (!font || font === HELVETICA || font.family === HELVETICA) return HELVETICA; +/** + * Load a FontSpec: register it on pdfMake and read its metrics. + * + * @param {object} pdfMake - the consumer's pdfmake instance + * @param {string|object} font - FontSpec + * @returns {Promise<{family: string, fontMetrics: object}>} the font family to + * use as defaultStyle.font, and `fontMetrics.normal`, `.bold`, `.italics` + * and `.bolditalics`: each style's `{ ascender, capHeight }` per em, or null + * when its file can't be read for them (see readFontMetrics) + */ +export const loadFont = async (pdfMake, font) => { + if (!font || font === HELVETICA || font.family === HELVETICA) return helvetica(); // Imported / pre-baked container — no fetch. if (font.family && font.vfs && font.fonts) { - if (!font.fonts[font.family]) { + const files = font.fonts[font.family] && fillStyles(font.fonts[font.family]); + if (!files || !files.normal) { // eslint-disable-next-line no-console - console.warn('[pdf] font container lacks family, using Helvetica:', font.family); - return HELVETICA; + console.warn(`[pdf] font container has no file for "${font.family}", using Helvetica`); + return helvetica(); } - pdfMake.addFontContainer({ vfs: font.vfs, fonts: font.fonts }); - return font.family; + pdfMake.addFontContainer({ vfs: font.vfs, fonts: { ...font.fonts, [font.family]: files } }); + return { + family: font.family, + fontMetrics: await metricsByStyle(files, (name) => readVfsMetricsOrNull(font.vfs[name])), + }; } // Runtime-dynamic URLs — fetch + base64 (cached), fall back on failure. if (font.family && font.urls) { const key = font.family + '|' + JSON.stringify(font.urls); - if (!containerCache.has(key)) { - containerCache.set( + if (!fontCache.has(key)) { + fontCache.set( key, - containerFromUrls(font.family, font.urls).catch((err) => { - containerCache.delete(key); + loadUrlFont(font.family, font.urls).catch((err) => { + fontCache.delete(key); throw err; }), ); } try { - const container = await containerCache.get(key); + const { container, fontMetrics } = await fontCache.get(key); pdfMake.addFontContainer(container); - return font.family; + return { family: font.family, fontMetrics }; } catch (err) { // eslint-disable-next-line no-console - console.warn('[pdf] custom font failed, using Helvetica:', err && err.message); - return HELVETICA; + console.warn(`[pdf] font "${font.family}" failed, using Helvetica:`, err && err.message); + return helvetica(); } } - return HELVETICA; + return helvetica(); }; +/** + * Resolve a FontSpec and register it on pdfMake. + * + * @param {object} pdfMake - the consumer's pdfmake instance + * @param {string|object} font - FontSpec + * @returns {Promise} the font family to use as defaultStyle.font + */ +export const resolveFont = async (pdfMake, font) => (await loadFont(pdfMake, font)).family; + export default resolveFont;