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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Unreleased

- Fix text, measuring, `moveDown()`, lists and tables in a document created with `font: null` failing with `Cannot read properties of null` before a font is selected. They now throw an error saying that no font is set, and the docs show how to start a document with an embedded font instead. Fixes #1647
- Fix gradients whose last stop comes before 1 stretching the stops over the whole gradient. The last color now stays solid from that stop to the end
- Add a `headerRows` table option, which repeats the first rows at the top of each new page. Fixes #1657
- Add a `scaleDown` option to `doc.image()`, which works like `fit` but keeps an image smaller than the rectangle at its own size instead of enlarging it. Fixes #1347
Expand Down
14 changes: 13 additions & 1 deletion docs/getting_started.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ PDFKit provides an ES module build for browsers. Standard PDF font metrics are
not included in the main browser module. Import and register the generated data
for every standard font your application uses before selecting that font. The
default document font is Helvetica, so it must be registered before constructing
a document unless the document is created with `{ font: null }`.
a document unless the document is created with `{ font: null }` or with an
embedded font as its default (see [Setting default font](#setting-default-font)).

### Experimental output helpers

Expand Down Expand Up @@ -310,6 +311,17 @@ The default font is 'Helvetica'. It can be configured by passing `font` option
// use Courier font by default
const doc = new PDFDocument({font: 'Courier'});

A document that only uses embedded fonts can start with one of them, so it never
loads a standard font. Pass the font data as a `Uint8Array` or an `ArrayBuffer`,
or, in Node, the path to the font file:

const doc = new PDFDocument({font: robotoData});

With `font: null` the document starts without a font. Select one with
`doc.font()` before anything that needs font metrics, such as writing or
measuring text, `moveDown()`, or a list or table. Until then those methods throw
an error saying that no font is set.

## Setting document metadata

PDF documents can have various metadata associated with them, such as the
Expand Down
11 changes: 10 additions & 1 deletion lib/mixins/fonts.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,16 @@ export default {
},

currentLineHeight(includeGap) {
return this._font.lineHeight(this._fontSize, includeGap);
return this._requireFont().lineHeight(this._fontSize, includeGap);
},

_requireFont() {
if (!this._font) {
throw new Error(
'No font is set. Select one with doc.font(), or pass the font option when creating the document.',
);
}
return this._font;
},

registerFont(name, src, family) {
Expand Down
11 changes: 9 additions & 2 deletions lib/mixins/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,11 @@ export default {
widthOfString(string, options = {}) {
const horizontalScaling = options.horizontalScaling || 100;
return (
((this._font.widthOfString(string, this._fontSize, options.features) +
((this._requireFont().widthOfString(
string,
this._fontSize,
options.features,
) +
(options.characterSpacing || 0) * (string.length - 1)) *
horizontalScaling) /
100
Expand Down Expand Up @@ -282,7 +286,9 @@ export default {
options = this._initOptions(x, y, options);

const listType = options.listType || 'bullet';
const unit = Math.round((this._font.ascender / 1000) * this._fontSize);
const unit = Math.round(
(this._requireFont().ascender / 1000) * this._fontSize,
);
const midLine = unit / 2;
const r = options.bulletRadius || unit / 3;
const indent =
Expand Down Expand Up @@ -472,6 +478,7 @@ export default {
if (text.length === 0) {
return;
}
this._requireFont();

// handle options
const align = options.align || 'left';
Expand Down
31 changes: 31 additions & 0 deletions tests/unit/font.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,37 @@ describe('binary font sources', () => {
});
});

describe('a document without a font', () => {
const message =
'No font is set. Select one with doc.font(), or pass the font option when creating the document.';

test.each([
['moveDown', (doc) => doc.moveDown()],
['moveUp', (doc) => doc.moveUp()],
['currentLineHeight', (doc) => doc.currentLineHeight()],
['widthOfString', (doc) => doc.widthOfString('text')],
['heightOfString', (doc) => doc.heightOfString('text')],
['boundsOfString', (doc) => doc.boundsOfString('text')],
['text', (doc) => doc.text('text')],
['text without wrapping', (doc) => doc.text('text', { lineBreak: false })],
['list', (doc) => doc.list(['item'])],
['table', (doc) => doc.table({ data: [['cell']] })],
])('%s says that no font is set', (_, use) => {
expect(() => use(new PDFDocument({ font: null }))).toThrow(message);
});

test('an embedded font can be the default font instead', () => {
const doc = new PDFDocument({
font: new Uint8Array(readFileSync('tests/fonts/Roboto-Regular.ttf')),
compress: false,
});
doc.moveDown().text('embedded only');

expect(Object.keys(doc._fontFamilies)).toEqual(['Roboto-Regular']);
expect(missingObjects(collectPdf(doc))).toHaveLength(0);
});
});

describe('standard font metrics', () => {
test('are shared across documents', () => {
const first = new PDFDocument().font('Helvetica-Bold')._font;
Expand Down