Skip to content
Merged
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 the Node build throwing once a bundler inlines it into an application bundle, `Cannot find module '#standard-fonts/Helvetica'` on the first document from an ESM bundle and `Invalid URL` while importing a CommonJS one, because the standard font metrics and the PDF/A ICC profile were resolved relative to pdfkit's own package directory at import time. Both are now resolved on first use, a standard font that cannot be loaded names itself and the fix in its error, and `registerStdFonts` is exported from the Node build as it already was from the browser build, so a bundle can register the fonts it uses from `pdfkit/standard-fonts/<Name>`. The Node build now requires the standard fonts by a path relative to the built file, which replaces the `#standard-fonts/*` import mapping and lets an ESM bundle load them from a copy of `js/standard-fonts` next to it. Fixes #1801
- Fix `doc.list()` drawing the label of a `numbered` or `lettered` item with the line wrapper's own options object, which threw `unsupported number: NaN` for `align` `center` and `right`, applied a word spacing derived from the previous line to the label for `align` `justify`, and sized the underline, strike, link and goTo of every label after the first from the previous item's text
- Add a `hidden` option to form annotation methods, for a field that should start hidden (e.g. one an interactive action reveals later) instead of the usual default of visible and printable
- Fix annotations placed under `doc.rotate()` marking the wrong area, because `_convertRect` derived each corner's y from the already transformed x and mapped only two of the four corners, so the rectangle a viewer makes interactive did not follow the rotated content. Fixes #1153
Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,41 @@ doc.end();
complex documents with a very small amount of code. For more, see the `demo` folder and the
[PDFKit programming guide](http://pdfkit.org/docs/getting_started.html).

## Bundling for Node

The Node build loads the metrics of the 14 standard fonts on first use from
`standard-fonts/` next to the built file, and PDF/A output reads the sRGB ICC
profile from `data/` next to it. Both are resolved relative to the built file
inside pdfkit's package directory, which a bundle that inlines pdfkit (esbuild,
rollup, webpack, the AWS CDK's `NodejsFunction`, ...) does not sit in. Pick one
of:

- Mark `pdfkit` as external in the bundler and ship `node_modules/pdfkit` next
to the bundle. File tracers such as `@vercel/nft` pick up every file pdfkit
needs.
- Copy pdfkit's `js/standard-fonts` directory next to an ESM bundle, which then
loads the fonts from there. A CommonJS bundle has no `import.meta.url` to
resolve against, so this route is not open to it.
- Register the standard fonts the document uses before creating it, the same
way as in the browser:

```javascript
import { PDFDocument, registerStdFonts } from 'pdfkit';
import Helvetica from 'pdfkit/standard-fonts/Helvetica';

registerStdFonts(Helvetica);
const doc = new PDFDocument();
```

Using a standard font that is neither registered nor loadable throws an
error naming the font. Fonts read from the file system or passed as data are
not affected.

PDF/A output additionally reads `data/sRGB_IEC61966_2_1.icc` relative to the
bundle's `import.meta.url`: copy pdfkit's `js/data` directory next to an ESM
bundle, or register the profile under that URL with `registerFile`. A CommonJS
bundle has no `import.meta.url` and says so when PDF/A output is requested.

## Browser Usage

There are three ways to use PDFKit in the browser:
Expand Down
4 changes: 2 additions & 2 deletions lib/document.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import LineWrapper from './line_wrapper';
import { registerStdFonts } from './font/standard_fonts';
import { registerFile } from '#fs';
import { fromBase64 } from './binary';
import { ICC_PROFILE_PATH } from './mixins/pdfa';
import { getIccProfilePath } from './mixins/pdfa';
import iccProfileBase64 from './mixins/data/sRGB_IEC61966_2_1.icc';

registerFile(ICC_PROFILE_PATH, fromBase64(iccProfileBase64));
registerFile(getIccProfilePath(), fromBase64(iccProfileBase64));

export { PDFDocument, LineWrapper, registerStdFonts, registerFile };
export default PDFDocument;
76 changes: 57 additions & 19 deletions lib/document.node.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,66 @@
import { createRequire } from 'module';
import PDFDocument from './document';
import LineWrapper from './line_wrapper';
import { registerStdFontLoaders } from './font/standard_fonts';
import {
registerStdFontLoaders,
registerStdFonts,
} from './font/standard_fonts';
import { registerFile } from '#fs';

const require = createRequire(import.meta.url);
// The standard fonts are required by a path relative to the built file, so they
// resolve next to `js/pdfkit.js` and `js/pdfkit.node.mjs`. A bundler that
// folds this module into its own output leaves `import.meta.url` undefined
// (CommonJS output) or pointing at a bundle with no `standard-fonts/` directory
// next to it (ESM output). Neither may fail before a document actually asks for
// a standard font, so the lookup falls back to a base createRequire accepts and
// a failed lookup explains itself.
const require = createRequire(import.meta.url ?? 'file:///');

registerStdFontLoaders({
Courier: () => require('#standard-fonts/Courier'),
'Courier-Bold': () => require('#standard-fonts/CourierBold'),
'Courier-BoldOblique': () => require('#standard-fonts/CourierBoldOblique'),
'Courier-Oblique': () => require('#standard-fonts/CourierOblique'),
Helvetica: () => require('#standard-fonts/Helvetica'),
'Helvetica-Bold': () => require('#standard-fonts/HelveticaBold'),
const loaders = {
Courier: () => require('./standard-fonts/Courier.cjs'),
'Courier-Bold': () => require('./standard-fonts/CourierBold.cjs'),
'Courier-BoldOblique': () =>
require('./standard-fonts/CourierBoldOblique.cjs'),
'Courier-Oblique': () => require('./standard-fonts/CourierOblique.cjs'),
Helvetica: () => require('./standard-fonts/Helvetica.cjs'),
'Helvetica-Bold': () => require('./standard-fonts/HelveticaBold.cjs'),
'Helvetica-BoldOblique': () =>
require('#standard-fonts/HelveticaBoldOblique'),
'Helvetica-Oblique': () => require('#standard-fonts/HelveticaOblique'),
Symbol: () => require('#standard-fonts/Symbol'),
'Times-Bold': () => require('#standard-fonts/TimesBold'),
'Times-BoldItalic': () => require('#standard-fonts/TimesBoldItalic'),
'Times-Italic': () => require('#standard-fonts/TimesItalic'),
'Times-Roman': () => require('#standard-fonts/TimesRoman'),
ZapfDingbats: () => require('#standard-fonts/ZapfDingbats'),
});
require('./standard-fonts/HelveticaBoldOblique.cjs'),
'Helvetica-Oblique': () => require('./standard-fonts/HelveticaOblique.cjs'),
Symbol: () => require('./standard-fonts/Symbol.cjs'),
'Times-Bold': () => require('./standard-fonts/TimesBold.cjs'),
'Times-BoldItalic': () => require('./standard-fonts/TimesBoldItalic.cjs'),
'Times-Italic': () => require('./standard-fonts/TimesItalic.cjs'),
'Times-Roman': () => require('./standard-fonts/TimesRoman.cjs'),
ZapfDingbats: () => require('./standard-fonts/ZapfDingbats.cjs'),
};

export { PDFDocument, LineWrapper, registerFile };
registerStdFontLoaders(
Object.fromEntries(
Object.entries(loaders).map(([name, load]) => [
name,
() => {
try {
return load();
} catch (error) {
if (error?.code !== 'MODULE_NOT_FOUND') {
throw error;
}

throw new Error(
`Cannot load the standard font "${name}" from pdfkit's package ` +
'directory, which is not available once pdfkit is bundled ' +
'into another file. Either mark pdfkit as external in the ' +
'bundler, or import the fonts the document uses from ' +
'"pdfkit/standard-fonts/<Name>" and pass them to ' +
'registerStdFonts() before creating the document.',
{ cause: error },
);
}
},
]),
),
);

export { PDFDocument, LineWrapper, registerStdFonts, registerFile };
export default PDFDocument;
28 changes: 22 additions & 6 deletions lib/mixins/pdfa.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
import fs from '#fs';

export const ICC_PROFILE_PATH = new URL(
'./data/sRGB_IEC61966_2_1.icc',
import.meta.url,
).href;

let iccProfilePath;
let iccProfile;

// Resolved on first use rather than at import time: a bundler that folds this
// module into a CommonJS output leaves `import.meta.url` undefined, and a
// document that never produces PDF/A output has no reason to fail over it.
export const getIccProfilePath = () => {
if (iccProfilePath === undefined) {
if (import.meta.url == null) {
throw new Error(
'pdfkit cannot locate its sRGB ICC profile because import.meta.url ' +
'is not available in this build. Bundle pdfkit as ESM or mark it ' +
'as external in the bundler.',
);
}

iccProfilePath = new URL('./data/sRGB_IEC61966_2_1.icc', import.meta.url)
.href;
}

return iccProfilePath;
};

export default {
initPDFA(pSubset) {
if (pSubset.charAt(pSubset.length - 3) === '-') {
Expand All @@ -28,7 +44,7 @@ export default {

_addColorOutputIntent() {
if (!iccProfile) {
iccProfile = fs.readFileSync(ICC_PROFILE_PATH);
iccProfile = fs.readFileSync(getIccProfilePath());
}

const colorProfileRef = this.ref({
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,7 @@
"#stream": {
"node": "./lib/stream/node.js",
"default": "./lib/stream/browser.js"
},
"#standard-fonts/*": "./js/standard-fonts/*.cjs"
}
},
"engine": [
"node >= v20.0.0"
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export default [
interop: 'default',
exports: 'named',
footer:
'module.exports = exports.default;\nmodule.exports.PDFDocument = exports.PDFDocument;\nmodule.exports.LineWrapper = exports.LineWrapper;\nmodule.exports.registerFile = exports.registerFile;',
'module.exports = exports.default;\nmodule.exports.PDFDocument = exports.PDFDocument;\nmodule.exports.LineWrapper = exports.LineWrapper;\nmodule.exports.registerStdFonts = exports.registerStdFonts;\nmodule.exports.registerFile = exports.registerFile;',
},
{
file: 'js/pdfkit.node.mjs',
Expand Down
5 changes: 4 additions & 1 deletion tests/package-resolution.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ assert.equal(typeof PDFDocument, 'function');
assert.equal(PDFDocument.name, 'PDFDocument');
assert.equal(PDFDocument.PDFDocument, PDFDocument);
assert.equal(typeof PDFDocument.LineWrapper, 'function');
assert.equal(typeof PDFDocument.registerStdFonts, 'function');
assert.equal(typeof PDFDocument.registerFile, 'function');
const { LineWrapper, registerFile } = require('pdfkit');
const { LineWrapper, registerStdFonts, registerFile } = require('pdfkit');
assert.equal(LineWrapper, PDFDocument.LineWrapper);
assert.equal(registerStdFonts, PDFDocument.registerStdFonts);
assert.equal(registerFile, PDFDocument.registerFile);
assert.equal(typeof outputHelpers.toBlob, 'function');
assert.equal(typeof outputHelpers.toBytes, 'function');
Expand All @@ -87,6 +89,7 @@ assert.equal(BrowserPDFDocument.registerFile, undefined);
assert.equal(typeof nodeEsModule.default, 'function');
assert.equal(nodeEsModule.PDFDocument, nodeEsModule.default);
assert.equal(typeof nodeEsModule.LineWrapper, 'function');
assert.equal(typeof nodeEsModule.registerStdFonts, 'function');
assert.equal(typeof nodeEsModule.registerFile, 'function');

const browserModule = await import(browserEsBundleUrl);
Expand Down
32 changes: 7 additions & 25 deletions tests/package-resolution.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import PDFDocument, { LineWrapper, registerFile } from 'pdfkit';
import PDFDocument, {
LineWrapper,
registerStdFonts,
registerFile,
} from 'pdfkit';
import { toBytes } from 'pdfkit/output';

const require = createRequire(import.meta.url);
const packageJson = require('../package.json');

assert.equal(
import.meta.resolve('pdfkit'),
Expand All @@ -15,8 +18,10 @@ assert.equal(
assert.equal(typeof PDFDocument, 'function');
assert.equal(PDFDocument.name, 'PDFDocument');
assert.equal(typeof LineWrapper, 'function');
assert.equal(typeof registerStdFonts, 'function');
assert.equal(typeof registerFile, 'function');
assert.equal(PDFDocument.LineWrapper, undefined);
assert.equal(PDFDocument.registerStdFonts, undefined);
assert.equal(PDFDocument.registerFile, undefined);

const loadedStandardFontModules = () =>
Expand All @@ -41,29 +46,6 @@ assert.equal(
false,
);

// The node ESM build reaches the standard fonts through createRequire, so the
// require condition is the only one ever taken at runtime. Bundlers and file
// tracers walk this same file as ESM and resolve `#standard-fonts/*` under the
// import condition instead: if the two point at different files, the tracer packs
// the modules that are never loaded, omits the ones that are, and the bundle
// throws `Cannot find module` on the first document. Keep every standard font
// resolving to the one file the runtime uses, under both conditions.
const standardFonts = Object.keys(packageJson.exports)
.filter((entry) => entry.startsWith('./standard-fonts/'))
.map((entry) => entry.slice('./standard-fonts/'.length));

assert.equal(standardFonts.length, 14);

for (const font of standardFonts) {
const expected = new URL(`../js/standard-fonts/${font}.cjs`, import.meta.url)
.href;
assert.equal(import.meta.resolve(`#standard-fonts/${font}`), expected);
assert.equal(
require.resolve(`#standard-fonts/${font}`),
fileURLToPath(expected),
);
}

const fileDocument = new PDFDocument();
const fileOutput = toBytes(fileDocument);
fileDocument.font(
Expand Down
Loading
Loading