Skip to content

Commit 79d6885

Browse files
feat: auto-apply standard font defaults in Node.js (closes #15)
1 parent 573aedc commit 79d6885

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

README.md

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -273,19 +273,13 @@ In order to use this method, make sure to meet the following requirements:
273273
- Install the [`@napi-rs/canvas`](https://github.com/Brooooooklyn/canvas) package if you are using Node.js. This package is required to render the PDF page as an image.
274274

275275
> [!TIP]
276-
> If fonts render incorrectly, create a `PDFDocumentProxy` with custom options and pass it directly:
276+
> In Node.js, `getDocumentProxy` automatically sets `disableFontFace: true` and resolves `standardFontDataUrl` from your local `pdfjs-dist` package for correct font rendering. To customize this behavior, pass your own options:
277277
>
278278
> ```ts
279-
> import { getDocumentProxy, renderPageAsImage } from 'unpdf'
280-
>
281279
> const pdf = await getDocumentProxy(buffer, {
282-
> disableFontFace: true,
280+
> disableFontFace: false,
283281
> standardFontDataUrl: 'https://unpkg.com/pdfjs-dist@latest/standard_fonts/',
284282
> })
285-
>
286-
> const image = await renderPageAsImage(pdf, 1, {
287-
> canvasImport: () => import('@napi-rs/canvas'),
288-
> })
289283
> ```
290284

291285
**Type Declaration**

src/utils.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,37 @@ export const isBrowser = typeof window !== 'undefined'
1414
* Applies the following defaults:
1515
* - `isEvalSupported: false`
1616
* - `useSystemFonts: true`
17+
*
18+
* In Node.js environments, additionally applies:
19+
* - `disableFontFace: true`
20+
* - `standardFontDataUrl` resolved from the local `pdfjs-dist` package
1721
*/
1822
export async function getDocumentProxy(
1923
data: DocumentInitParameters['data'],
2024
options: DocumentInitParameters = {},
2125
) {
2226
const { getDocument } = await getResolvedPDFJS()
27+
28+
let nodeDefaults: Partial<DocumentInitParameters> = {}
29+
if (isNode) {
30+
try {
31+
const base = import.meta.resolve('pdfjs-dist/package.json')
32+
nodeDefaults = {
33+
disableFontFace: true,
34+
standardFontDataUrl: new URL('./standard_fonts/', base).href,
35+
}
36+
}
37+
catch {
38+
// pdfjs-dist not installed (e.g. using serverless bundle), skip font defaults
39+
}
40+
}
41+
2342
const pdf = await getDocument({
2443
data,
2544
isEvalSupported: false,
2645
// See: https://github.com/mozilla/pdf.js/issues/4244#issuecomment-1479534301
2746
useSystemFonts: true,
47+
...nodeDefaults,
2848
...options,
2949
}).promise
3050

0 commit comments

Comments
 (0)