Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions src/utils/pdf/__fixtures__/fake-pdfmake.js
Original file line number Diff line number Diff line change
@@ -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.
*
Expand Down
58 changes: 37 additions & 21 deletions src/utils/pdf/__fixtures__/font-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/utils/pdf/__tests__/create-document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
55 changes: 54 additions & 1 deletion src/utils/pdf/__tests__/font-metrics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('<!doctype html><html></html>');
Expand Down Expand Up @@ -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);
});
});
34 changes: 34 additions & 0 deletions src/utils/pdf/__tests__/helvetica-metrics.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});
52 changes: 52 additions & 0 deletions src/utils/pdf/__tests__/nodes.test.js
Original file line number Diff line number Diff line change
@@ -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)', () => {
Expand Down Expand Up @@ -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:
'<svg xmlns="http://www.w3.org/2000/svg" width="45" height="17">' +
'<rect x="0" y="0" width="45" height="17" rx="8.5" fill="#0a7a2f"/>' +
'<text x="22.5" y="11.56" fill="#ffffff" font-family="Helvetica" font-size="9" ' +
'font-weight="bold" text-anchor="middle">PAID</text></svg>',
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 &amp; &quot;B&quot;"');
});

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']);
});
});

13 changes: 12 additions & 1 deletion src/utils/pdf/__tests__/resolve-font.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

Expand Down Expand Up @@ -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();
Expand Down
7 changes: 4 additions & 3 deletions src/utils/pdf/create-document.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
Loading
Loading