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
17 changes: 15 additions & 2 deletions lib/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,21 @@ class PDFPage {

this.content = this.document.ref();

if (options.font) document.font(options.font, options.fontFamily);
if (options.fontSize) document.fontSize(options.fontSize);
// `options` defaults to `document.options` (the PDFDocument constructor options) when
// addPage() is called without arguments, so it's the same object for every page. Applying
// font/fontSize from it unconditionally would silently override any doc.font()/doc.fontSize()
// call made since the previous page. Only (re-)apply them here when they were explicitly
// passed to this addPage() call, or for the very first page (document.page is still null),
// where they're the intended initial default - already applied by initFonts(), so this is
// just keeping fontSize/margin calculation below consistent.
const isInheritedDefaultOptions = options === document.options;
const isFirstPage = document.page == null;
if (options.font && (!isInheritedDefaultOptions || isFirstPage)) {
document.font(options.font, options.fontFamily);
}
if (options.fontSize && (!isInheritedDefaultOptions || isFirstPage)) {
document.fontSize(options.fontSize);
}

// process margins
// Margin calculation must occur after font assignment to ensure any dynamic sizes are calculated correctly
Expand Down
30 changes: 30 additions & 0 deletions tests/unit/page.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,34 @@ describe('page', function () {
expect(page.margins).toEqual({ top: 0, right: 0, bottom: 0, left: 0 });
});
});

// https://github.com/foliojs/pdfkit/issues/1739
describe('font persistence across addPage()', function () {
test('a font set with doc.font() persists onto a bare addPage() call', function () {
const doc = new PDFDocument({ font: 'Helvetica' });
doc.font('Helvetica-Bold');
doc.addPage();
expect(doc._font.name).toBe('Helvetica-Bold');
});

test('a font size set with doc.fontSize() persists onto a bare addPage() call', function () {
const doc = new PDFDocument({ font: 'Helvetica' });
doc.fontSize(30);
doc.addPage();
expect(doc._fontSize).toBe(30);
});

test('an explicit font passed to addPage() still overrides the current font', function () {
const doc = new PDFDocument({ font: 'Helvetica' });
doc.font('Helvetica-Bold');
doc.addPage({ font: 'Times-Roman' });
expect(doc._font.name).toBe('Times-Roman');
});

test('an explicit fontSize passed to addPage() still applies', function () {
const doc = new PDFDocument({ font: 'Helvetica' });
doc.addPage({ fontSize: 20 });
expect(doc._fontSize).toBe(20);
});
});
});