diff --git a/src/utils/pdf/__fixtures__/fake-pdfmake.js b/src/utils/pdf/__fixtures__/fake-pdfmake.js index 28540b4d..742b0520 100644 --- a/src/utils/pdf/__fixtures__/fake-pdfmake.js +++ b/src/utils/pdf/__fixtures__/fake-pdfmake.js @@ -1,13 +1,11 @@ /** - * A promise-based fake of pdfmake 0.3.x, matching the REAL contract: - * createPdf(dd).getBlob() / .getBase64() / .open() / .print() / .download() - * are all async (return promises) and take NO callbacks. The old 0.1 callback - * form is gone. + * A fake of pdfmake 0.3.x. Like the real one, createPdf(dd).getBlob(), + * .getBase64(), .open(), .print() and .download() return promises and take + * no callbacks. * - * Every pdf test that exercises createDocument must build its fake from here, so - * a hand-rolled fake can't drift back to the callback API and false-green (which - * is exactly what once hid a real "never downloads" bug — the unit test passed - * while the browser did nothing). + * Every pdf test that exercises createDocument builds its fake from here. A + * fake that took callbacks would let a test pass while a real download never + * starts. * * Lives in __fixtures__ (not __tests__) so jest doesn't collect it as a suite. * diff --git a/src/utils/pdf/__fixtures__/font-files.js b/src/utils/pdf/__fixtures__/font-files.js index 6d06356f..b7815286 100644 --- a/src/utils/pdf/__fixtures__/font-files.js +++ b/src/utils/pdf/__fixtures__/font-files.js @@ -9,28 +9,44 @@ const table = (size, write) => { return bytes; }; const head = (unitsPerEm) => table(54, (v) => v.setUint16(18, unitsPerEm)); -const hhea = (ascender) => table(36, (v) => v.setInt16(4, ascender)); +const hhea = (ascender, numberOfHMetrics = 0) => + table(36, (v) => { + v.setInt16(4, ascender); + v.setUint16(34, numberOfHMetrics); + }); 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) => { +// A Unicode format 4 cmap with one segment per character, mapping each +// character to its glyph id: { H: 1 }. The closing 0xFFFF segment maps to 0. +const cmap = (glyphs) => { + const codes = Object.keys(glyphs).map((char) => char.charCodeAt(0)); + codes.sort((a, b) => a - b); + const segments = [...codes, 0xffff]; + const endCodes = 26; + const startCodes = endCodes + segments.length * 2 + 2; + const idDeltas = startCodes + segments.length * 2; + return table(idDeltas + segments.length * 4, (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); + v.setUint16(18, segments.length * 2); + segments.forEach((code, i) => { + const id = code === 0xffff ? 0 : glyphs[String.fromCharCode(code)]; + v.setUint16(endCodes + i * 2, code); + v.setUint16(startCodes + i * 2, code); + v.setUint16(idDeltas + i * 2, (0x10000 + id - code) % 0x10000); // id - code, wrapped + }); }); +}; +// Advance widths, one per glyph id, as hmtx stores them (each with a left side +// bearing of 0). +const hmtx = (advances) => + table(advances.length * 4, (v) => advances.forEach((advance, i) => v.setUint16(i * 4, advance))); // 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)); @@ -45,22 +61,22 @@ export const oldTables = () => ({ head: head(1000), hhea: hhea(1011), 'OS/2': os2(1, 0), - cmap: cmapH(), + cmap: cmap({ H: 1 }), loca: loca(), glyf: glyf(705), }); +// A font with text widths: glyph 0 is 500 units wide, "A" 600 and "B" 700. +// hmtx lists three advance widths, so the space (glyph 3) takes the last one. +export const widthTables = () => ({ + head: head(1000), + hhea: hhea(900, 3), + 'OS/2': os2(4, 700), + cmap: cmap({ A: 1, B: 2, ' ': 3 }), + hmtx: hmtx([500, 600, 700]), +}); 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); diff --git a/src/utils/pdf/__tests__/create-document.test.js b/src/utils/pdf/__tests__/create-document.test.js index a2352124..f7329a4c 100644 --- a/src/utils/pdf/__tests__/create-document.test.js +++ b/src/utils/pdf/__tests__/create-document.test.js @@ -3,7 +3,7 @@ */ import { createDocument } from '../create-document'; import { createFakePdfMake } from '../__fixtures__/fake-pdfmake'; -import { HELVETICA_FONT_METRICS } from '../__fixtures__/font-files'; +import { HELVETICA_FONT_METRICS } from '../helvetica-metrics'; describe('createDocument', () => { beforeEach(() => { diff --git a/src/utils/pdf/__tests__/font-metrics.test.js b/src/utils/pdf/__tests__/font-metrics.test.js index bb2ba4d7..62b78e98 100644 --- a/src/utils/pdf/__tests__/font-metrics.test.js +++ b/src/utils/pdf/__tests__/font-metrics.test.js @@ -5,7 +5,7 @@ /* eslint-disable no-magic-numbers */ import { fontFormat, isCompleteFontFile, readFontMetrics } from '../font-metrics'; import { - modernTables, oldTables, ttf, woff, woff2, MODERN, OLD, + modernTables, oldTables, widthTables, ttf, woff, woff2, MODERN, OLD, } from '../__fixtures__/font-files'; const html = new TextEncoder().encode(''); @@ -94,3 +94,56 @@ describe('readFontMetrics', () => { await expect(readFontMetrics(broken)).rejects.toThrow(); }); }); + +describe('textWidth', () => { + // The font in widthTables: an ascender of 0.9 and a cap height of 0.7. + const WITHOUT_WIDTHS = { ascender: 0.9, capHeight: 0.7 }; + const textWidthOf = async (bytes) => (await readFontMetrics(bytes)).textWidth; + + it('adds up the advance widths of the characters, per em', async () => { + const textWidth = await textWidthOf(ttf(widthTables())); + expect(textWidth('AB')).toBeCloseTo(1.3); + expect(textWidth('')).toBe(0); + }); + + it('gives a glyph past the last hmtx width that last width', async () => { + const textWidth = await textWidthOf(ttf(widthTables())); + expect(textWidth(' ')).toBeCloseTo(0.7); + }); + + it("gives a character the font doesn't have the width of glyph 0", async () => { + const textWidth = await textWidthOf(ttf(widthTables())); + expect(textWidth('Z')).toBeCloseTo(0.5); + expect(textWidth('\u{1F600}')).toBeCloseTo(0.5); // one character, outside format 4 + }); + + it('reads the widths from a WOFF file', async () => { + const textWidth = await textWidthOf(woff(widthTables())); + expect(textWidth('A B')).toBeCloseTo(2); + }); + + it('leaves out textWidth without an hmtx table or a format 4 cmap', async () => { + const noHmtx = widthTables(); + delete noHmtx.hmtx; + await expect(readFontMetrics(ttf(noHmtx))).resolves.toEqual(WITHOUT_WIDTHS); + + const noFormat4 = widthTables(); + new DataView(noFormat4.cmap.buffer).setUint16(12, 6); // the subtable's format + await expect(readFontMetrics(ttf(noFormat4))).resolves.toEqual(WITHOUT_WIDTHS); + }); + + it('leaves out textWidth when hmtx is shorter than hhea says', async () => { + const tables = widthTables(); + tables.hmtx = tables.hmtx.slice(0, 8); // two widths of three + await expect(readFontMetrics(ttf(tables))).resolves.toEqual(WITHOUT_WIDTHS); + }); + + it('gives glyph 0 for a cmap entry that points past the end of the cmap', async () => { + const tables = widthTables(); + // The idRangeOffset of the "A" segment (the second of four). + new DataView(tables.cmap.buffer).setUint16(52 + 2, 0xfff0); + const textWidth = await textWidthOf(ttf(tables)); + expect(textWidth('A')).toBeCloseTo(0.5); + expect(textWidth('B')).toBeCloseTo(0.7); + }); +}); diff --git a/src/utils/pdf/__tests__/helvetica-metrics.test.js b/src/utils/pdf/__tests__/helvetica-metrics.test.js new file mode 100644 index 00000000..bfa7c1d2 --- /dev/null +++ b/src/utils/pdf/__tests__/helvetica-metrics.test.js @@ -0,0 +1,34 @@ +/* eslint-disable no-magic-numbers */ +import { HELVETICA_FONT_METRICS } from '../helvetica-metrics'; + +const { normal, bold, italics, bolditalics } = HELVETICA_FONT_METRICS; + +describe('HELVETICA_FONT_METRICS', () => { + it("gives every style Helvetica's ascender and cap height", () => { + [normal, bold, italics, bolditalics].forEach((style) => { + expect(style).toMatchObject({ ascender: 0.718, capHeight: 0.718 }); + }); + }); + + it('measures text with the widths of the AFM files', () => { + expect(bold.textWidth('PAID')).toBeCloseTo((667 + 722 + 278 + 722) / 1000); + expect(bold.textWidth('WM')).toBeCloseTo((944 + 833) / 1000); + expect(normal.textWidth('il')).toBeCloseTo((222 + 222) / 1000); + expect(bold.textWidth('')).toBe(0); + }); + + it('measures Windows-1252 characters outside ASCII', () => { + expect(bold.textWidth('é')).toBeCloseTo(0.556); // é + expect(bold.textWidth('€')).toBeCloseTo(0.556); // €, at 0x80 + expect(normal.textWidth('—')).toBeCloseTo(1); // em dash, at 0x97 + }); + + it('counts a character Helvetica has no glyph for as an average letter', () => { + expect(bold.textWidth('日')).toBeCloseTo(0.6); + }); + + it('gives the oblique styles the widths of the upright ones', () => { + expect(italics).toBe(normal); + expect(bolditalics).toBe(bold); + }); +}); diff --git a/src/utils/pdf/__tests__/nodes.test.js b/src/utils/pdf/__tests__/nodes.test.js index ceafc4a3..4ae2f79a 100644 --- a/src/utils/pdf/__tests__/nodes.test.js +++ b/src/utils/pdf/__tests__/nodes.test.js @@ -1,4 +1,6 @@ +/* eslint-disable no-magic-numbers */ import { field, badge } from '../nodes'; +import { HELVETICA_FONT_METRICS } from '../helvetica-metrics'; describe('field', () => { it('returns a [label, value] pair with an opinionated default (bold value)', () => { @@ -51,4 +53,54 @@ describe('badge', () => { const b = badge('PAID', { color: '#0a7a2f', margin: [0, -2, 0, 0] }); expect(b.margin).toEqual([0, -2, 0, 0]); }); + + it('draws the same badge as before without font or fontMetrics', () => { + expect(badge('PAID')).toEqual({ + svg: + '' + + '' + + 'PAID', + width: 45, + }); + }); + + it('prints the label in the given font', () => { + expect(badge('PAID', { font: 'Roboto' }).svg).toContain('font-family="Roboto"'); + expect(badge('PAID', { font: 'A & "B"' }).svg).toContain('font-family="A & "B""'); + }); + + it("fits the label's measured width and centers its capitals with fontMetrics", () => { + const fontMetrics = { + normal: { ascender: 1, capHeight: 0.5, textWidth: () => 99 }, + bold: { ascender: 0.9, capHeight: 0.7, textWidth: (text) => text.length * 0.5 }, + }; + const b = badge('PAID', { fontSize: 10, padX: 4, fontMetrics }); + // 4 letters of 0.5 em at 10 pt, plus 4 pt of padding on each side; the bold style. + expect(b.width).toBe(28); + // Half the height (19 / 2) plus half the capital height (0.7 * 10 / 2). + expect(b.svg).toContain('y="13"'); + }); + + it('fits a label of wide capitals with Helvetica metrics, where the estimate is too narrow', () => { + const label = 'MMMMMMMMMMMM'; + const estimated = badge(label, { fontSize: 6 }).width; + const measured = badge(label, { fontSize: 6, font: 'Helvetica', fontMetrics: HELVETICA_FONT_METRICS }); + expect(estimated).toBe(59); // 45 for the label, which needs 60 + expect(measured.width).toBe(Math.ceil(12 * 0.833 * 6) + 14); + }); + + it('estimates the width without the bold metrics or their textWidth', () => { + const estimated = badge('PAID'); + expect(badge('PAID', { fontMetrics: { bold: null } })).toEqual(estimated); + const noWidths = badge('PAID', { fontMetrics: { bold: { ascender: 0.9, capHeight: 0.7 } } }); + expect(noWidths.width).toBe(estimated.width); + expect(noWidths.svg).toContain(`y="${17 / 2 + (9 * 0.7) / 2}"`); + }); + + it('keeps font and fontMetrics off the returned node', () => { + const b = badge('PAID', { font: 'Roboto', fontMetrics: HELVETICA_FONT_METRICS }); + expect(Object.keys(b)).toEqual(['svg', 'width']); + }); }); + diff --git a/src/utils/pdf/__tests__/resolve-font.test.js b/src/utils/pdf/__tests__/resolve-font.test.js index 4a108701..3223e9fd 100644 --- a/src/utils/pdf/__tests__/resolve-font.test.js +++ b/src/utils/pdf/__tests__/resolve-font.test.js @@ -7,8 +7,9 @@ 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, + modernTables, oldTables, widthTables, ttf, woff2, MODERN, OLD, } from '../__fixtures__/font-files'; +import { HELVETICA_FONT_METRICS } from '../helvetica-metrics'; const HELVETICA_FONT = { family: 'Helvetica', fontMetrics: HELVETICA_FONT_METRICS }; @@ -96,6 +97,16 @@ describe('loadFont', () => { }); }); + it("gives each style's text widths, read from the file that prints it", async () => { + global.fetch = serveFiles({ 'https://w/r.ttf': ttf(widthTables()) }); + const { fontMetrics } = await loadFont(newPdfMake(), { + family: 'Widths', + urls: { normal: 'https://w/r.ttf' }, + }); + expect(fontMetrics.bold.textWidth('AB')).toBeCloseTo(1.3); + expect(fontMetrics.italics).toBe(fontMetrics.normal); + }); + 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(); diff --git a/src/utils/pdf/create-document.js b/src/utils/pdf/create-document.js index a6e8c283..3c28fc9e 100644 --- a/src/utils/pdf/create-document.js +++ b/src/utils/pdf/create-document.js @@ -7,9 +7,10 @@ import { downloadBlob } from './download-blob'; * The consumer passes its own (externalized, shared) `pdfMake` instance so there * 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. + * `fontMetrics` gives each style's ascender, capital height and text widths + * (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. Pass `font` and + * `fontMetrics` to `badge` so its label prints in the document's font. * 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. * diff --git a/src/utils/pdf/font-metrics.js b/src/utils/pdf/font-metrics.js index 7f75e8aa..c741451a 100644 --- a/src/utils/pdf/font-metrics.js +++ b/src/utils/pdf/font-metrics.js @@ -11,6 +11,7 @@ const SFNT_VERSIONS = [ const WOFF_SIGNATURE = 0x774f4646; // "wOFF" const WOFF2_SIGNATURE = 0x774f4632; // "wOF2" const CAPITAL_H = 0x48; +const SPACE = 0x20; const viewOf = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); @@ -108,7 +109,9 @@ const fontTables = (bytes) => { }; }; -// Look up a character's glyph id in a Unicode format 4 cmap subtable. +// Look up a character's glyph id in a Unicode format 4 cmap subtable. 0 is a +// character the font has no glyph for, and null a cmap without such a +// subtable. const glyphId = (cmap, code) => { const numSubtables = cmap.getUint16(2); for (let i = 0; i < numSubtables; i++) { @@ -139,17 +142,13 @@ const glyphId = (cmap, code) => { } } } - return 0; + return null; }; // 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'), - ]); +const capitalHTop = async (table, head, cmap) => { + const [loca, glyf] = await Promise.all([table('loca'), table('glyf')]); if (!cmap || !loca || !glyf) return null; const id = glyphId(cmap, CAPITAL_H); if (!id) return null; @@ -161,9 +160,47 @@ const capitalHTop = async (table, head) => { return glyf.getInt16(offset + 8); // yMax }; +// A copy of a table, so a function that keeps it doesn't keep the whole file. +const copyOf = (table) => + new DataView(new Uint8Array(table.buffer, table.byteOffset, table.byteLength).slice().buffer); + +// A function that gives a text's width per em: the sum of its characters' +// advance widths, from the cmap, hhea and hmtx tables. A character the font +// has no glyph for takes the width of glyph 0, which pdfmake prints in its +// place. Kerning isn't counted, so the result can be a little wider than the +// printed text. Undefined when the font has no Unicode format 4 cmap or no +// hmtx table. +const textWidthReader = (cmap, hhea, hmtx, unitsPerEm) => { + if (!cmap || !hmtx || glyphId(cmap, SPACE) === null) return undefined; + // Glyphs past the last advance width in hmtx take that last width. + const count = hhea.getUint16(34); // numberOfHMetrics + if (!count || hmtx.byteLength < count * 4) return undefined; + const advances = new Uint16Array(count); + for (let i = 0; i < count; i++) advances[i] = hmtx.getUint16(i * 4); + const map = copyOf(cmap); + const advanceByCode = new Map(); + const advanceOf = (code) => { + if (!advanceByCode.has(code)) { + let id; + try { + id = glyphId(map, code) || 0; + } catch (err) { + id = 0; // a cmap that points past its own end + } + advanceByCode.set(code, advances[Math.min(id, count - 1)]); + } + return advanceByCode.get(code); + }; + return (text) => { + let width = 0; + for (const char of String(text)) width += advanceOf(char.codePointAt(0)); + return width / unitsPerEm; + }; +}; + /** - * Read a font's ascender and capital height, per em, from a TTF, OTF or WOFF - * file. + * Read a font's ascender, capital height and text widths, 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 @@ -174,19 +211,26 @@ const capitalHTop = async (table, head) => { * 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. * + * `textWidth(text)` gives the width of a text in this font, per em, to size a + * shape that holds it (a badge, for example). It is missing when the font's + * tables can't be read for it. + * * @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. + * @returns {Promise<{ascender: number, capHeight: number, textWidth: Function}|null>} + * null for other formats, for WOFF in a browser that can't inflate it, or + * when the ascender or capital height 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([ + const [head, hhea, os2, cmap, hmtx] = await Promise.all([ table('head'), table('hhea'), table('OS/2'), + table('cmap'), + table('hmtx'), ]); if (!head || !hhea) return null; const unitsPerEm = head.getUint16(18); @@ -194,13 +238,21 @@ export const readFontMetrics = async (bytes) => { // 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) capHeight = (await capitalHTop(table, head, cmap)) || 0; if (capHeight <= 0) return null; - return { + const metrics = { ascender: hhea.getInt16(4) / unitsPerEm, capHeight: capHeight / unitsPerEm, }; + let textWidth; + try { + textWidth = textWidthReader(cmap, hhea, hmtx, unitsPerEm); + } catch (err) { + textWidth = undefined; // a table cut short + } + if (textWidth) metrics.textWidth = textWidth; + return metrics; }; export default readFontMetrics; diff --git a/src/utils/pdf/helvetica-metrics.js b/src/utils/pdf/helvetica-metrics.js new file mode 100644 index 00000000..b206cc3a --- /dev/null +++ b/src/utils/pdf/helvetica-metrics.js @@ -0,0 +1,85 @@ +/* eslint-disable no-magic-numbers */ +// Helvetica's metrics, as pdfmake prints its standard Helvetica fonts. The +// values come from Adobe's AFM files for Helvetica, Helvetica-Bold, +// Helvetica-Oblique and Helvetica-BoldOblique, which pdfmake ships. + +// All four fonts have an Ascender and CapHeight of 718 per 1000 units. +const ASCENDER = 0.718; +const CAP_HEIGHT = 0.718; + +// pdfmake writes Helvetica text in the Windows-1252 encoding. These are the +// characters that encoding moves into the bytes 0x80 to 0x9F. Any other +// character above 0xFF has no Helvetica glyph. +const WIN_ANSI = { + 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, +}; + +// Each byte's width per 1000 units, from 0x20 to 0xFF. 0 is a byte with no +// glyph. The oblique fonts have the same widths as the upright ones. +const REGULAR = [ + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, // 0x20 + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, // 0x30 + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, // 0x40 + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, // 0x50 + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, // 0x60 + 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0, // 0x70 + 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, // 0x80 + 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 500, // 0x90 + 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, // 0xA0 + 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, // 0xB0 + 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, // 0xC0 + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, // 0xD0 + 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, // 0xE0 + 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, // 0xF0 +]; +const BOLD = [ + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, // 0x20 + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, // 0x30 + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, // 0x40 + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, // 0x50 + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, // 0x60 + 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0, // 0x70 + 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, // 0x80 + 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 556, // 0x90 + 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, // 0xA0 + 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, // 0xB0 + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, // 0xC0 + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, // 0xD0 + 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, // 0xE0 + 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, // 0xF0 +]; + +// pdfmake prints a character Helvetica has no glyph for as stray letters. It +// counts as an average letter here, so it still takes up some room. +const NO_GLYPH_WIDTH = 0.6; + +// A text's width per em, from a width table above. Kerning isn't counted, so +// the result can be a little wider than the printed text. +const textWidthIn = (widths) => (text) => { + let width = 0; + for (const char of String(text)) { + const code = char.codePointAt(0); + const byte = WIN_ANSI[code] || code; + const glyphWidth = byte >= 0x20 && byte <= 0xff ? widths[byte - 0x20] : 0; + width += glyphWidth ? glyphWidth / 1000 : NO_GLYPH_WIDTH; + } + return width; +}; + +const regular = { ascender: ASCENDER, capHeight: CAP_HEIGHT, textWidth: textWidthIn(REGULAR) }; +const bold = { ascender: ASCENDER, capHeight: CAP_HEIGHT, textWidth: textWidthIn(BOLD) }; + +// Helvetica's metrics for each style, in the shape loadFont gives them. +export const HELVETICA_FONT_METRICS = { + normal: regular, + bold, + italics: regular, + bolditalics: bold, +}; + +export default HELVETICA_FONT_METRICS; diff --git a/src/utils/pdf/nodes.js b/src/utils/pdf/nodes.js index d4a77534..a3dd377a 100644 --- a/src/utils/pdf/nodes.js +++ b/src/utils/pdf/nodes.js @@ -1,6 +1,7 @@ /** - * Shared pdfmake node builders for the PDF toolkit. Pure functions that return - * plain pdfmake docDefinition nodes (no pdfMake instance needed) — so callers + * Shared pdfmake node builders for the PDF toolkit. A node is one item of a + * pdfmake docDefinition: a text, an svg, a table, a set of columns. These are + * pure functions that return plain nodes (no pdfMake instance needed) — so callers * can spread-override, compose, or post-process the result. Each carries an * opinionated default and a trailing `opts` with a `...rest` passthrough onto * the returned node for one-off overrides. @@ -29,20 +30,6 @@ export const field = (label, value, opts = {}) => { ]; }; -/** - * A colored badge with a centered label, drawn as an inline SVG (rounded rect + - * `text-anchor="middle"`). SVG is used because pdfmake `canvas` can't hold text - * and a `background:` can't be rounded; the SVG centers the label natively. - * Always returns a standalone `{ svg, width }` node. Height and horizontal - * padding derive from `fontSize`; the label is Helvetica-bold (always - * registered) regardless of the body font. - * - * @param {string} text - * @param {object} [opts] - { color, textColor='#fff', fontSize=9, radius, padX } + rest spread onto the node. - * `radius` behaves like CSS `border-radius`: it is clamped to half the height, - * so a large value (or the default) gives a full pill, `0` gives a square chip, - * and anything between gives rounded corners. - */ // Escape the five XML-significant characters so live data (tag names like // "AI & ML") can't break the SVG markup — an unescaped "&" yields invalid SVG // that pdfmake's parser drops. Safe for both text content and attribute values. @@ -54,19 +41,66 @@ const escapeXml = (s) => .replace(/"/g, '"') .replace(/'/g, '''); +// Without font metrics, a badge sizes its label as letters this wide (an +// average Helvetica Bold letter, per em) and puts the baseline this far below +// its middle (per em), which centers a Helvetica label. +const AVERAGE_LETTER_WIDTH = 0.62; +const BASELINE_BELOW_MIDDLE = 0.34; + +/** + * A colored badge with a centered bold label, drawn as an inline SVG (rounded + * rect + `text-anchor="middle"`). SVG is used because pdfmake `canvas` can't + * hold text and a `background:` can't be rounded; the SVG centers the label + * natively. Always returns a standalone `{ svg, width }` node. Height and + * horizontal padding derive from `fontSize`. + * + * The label prints in `font`, Helvetica by default. With `fontMetrics`, the + * badge is as wide as the label measures and centers its capital letters. + * Without them, the width is estimated from the number of letters. A template + * passes both from its context: + * `badge(text, { font: ctx.font, fontMetrics: ctx.fontMetrics })`. + * + * @param {string} text + * @param {object} [opts] - { color, textColor='#fff', fontSize=9, radius, padX, + * font, fontMetrics } + rest spread onto the node. + * `radius` behaves like CSS `border-radius`: it is clamped to half the height, + * so a large value (or the default) gives a full pill, `0` gives a square chip, + * and anything between gives rounded corners. + * `font` is a font family registered on pdfMake, such as the template's + * `font`. `fontMetrics` are that font's metrics, as the template gets them + * (see loadFont); the badge uses the bold style's. + */ export const badge = (text, opts = {}) => { - const { color = '#0a7a2f', textColor = '#ffffff', fontSize = 9, radius = 999, padX, ...rest } = opts; + const { + color = '#0a7a2f', + textColor = '#ffffff', + fontSize = 9, + radius = 999, + padX, + font, + fontMetrics, + ...rest + } = opts; const label = text == null ? '' : String(text); + const metrics = fontMetrics && fontMetrics.bold; const h = Math.round(fontSize * 1.9); const rx = Math.max(0, Math.min(radius, h / 2)); // CSS-like border-radius, clamped to a full pill const px = padX != null ? padX : Math.round(fontSize * 1.2); - const w = Math.ceil(label.length * fontSize * 0.62) + px * 2; // size from the raw length, not the escaped one - const y = h / 2 + fontSize * 0.34; // baseline that vertically centers the label + // Size from the raw label, not the escaped one. + const textWidth = metrics && metrics.textWidth + ? Math.ceil(metrics.textWidth(label) * fontSize) + : Math.ceil(label.length * fontSize * AVERAGE_LETTER_WIDTH); + const w = textWidth + px * 2; + // The baseline sits half a capital height below the middle, so capital + // letters are centered. + const y = metrics + ? h / 2 + (fontSize * metrics.capHeight) / 2 + : h / 2 + fontSize * BASELINE_BELOW_MIDDLE; const svg = `` + `` + - `${escapeXml(label)}` + + `${escapeXml(label)}` + ``; return { svg, width: w, ...rest }; }; diff --git a/src/utils/pdf/resolve-font.js b/src/utils/pdf/resolve-font.js index ad91905e..696baf44 100644 --- a/src/utils/pdf/resolve-font.js +++ b/src/utils/pdf/resolve-font.js @@ -27,24 +27,17 @@ /* eslint-disable no-magic-numbers */ import { bytesToBase64, base64ToBytes } from './base64'; import { fontFormat, isCompleteFontFile, readFontMetrics } from './font-metrics'; +import { HELVETICA_FONT_METRICS } from './helvetica-metrics'; const HELVETICA = 'Helvetica'; const STYLES = ['normal', 'bold', 'italics', 'bolditalics']; const FONT_TIMEOUT_MS = 10000; -// 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) }); +const helvetica = () => ({ family: HELVETICA, fontMetrics: { ...HELVETICA_FONT_METRICS } }); // Give every style a file, taken from the closest style the font has. const fillStyles = (files) => { @@ -161,8 +154,8 @@ const loadUrlFont = async (family, urls) => { * @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) + * and `.bolditalics`: each style's `{ ascender, capHeight, textWidth }`, 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();