unpdf 2.0.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -12
- package/dist/index.d.mts +13 -1
- package/dist/index.mjs +34 -13
- package/dist/pdfjs-decoders-workerd.mjs +1 -0
- package/dist/pdfjs-decoders.mjs +1 -1
- package/dist/pdfjs-jbig2_nowasm_fallback.mjs +1 -1
- package/dist/pdfjs-loader.mjs +1 -0
- package/dist/pdfjs-openjpeg.mjs +1 -1
- package/dist/pdfjs-openjpeg_nowasm_fallback.mjs +1 -2
- package/dist/pdfjs.mjs +39 -39
- package/dist/types/src/core/colorspace.d.ts +7 -0
- package/dist/types/src/core/crypto.d.ts +10 -2
- package/dist/types/src/core/flate_stream.d.ts +6 -1
- package/dist/types/src/core/image_resizer.d.ts +1 -1
- package/dist/types/src/core/image_utils.d.ts +10 -0
- package/dist/types/src/core/jpx.d.ts +0 -1
- package/dist/types/src/core/parser.d.ts +8 -1
- package/dist/types/src/core/pattern.d.ts +0 -4
- package/dist/types/src/core/primitives.d.ts +1 -0
- package/dist/types/src/core/struct_tree.d.ts +2 -0
- package/dist/types/src/core/wasm_image.d.ts +3 -3
- package/dist/types/src/display/annotation_layer.d.ts +9 -2
- package/dist/types/src/display/api.d.ts +38 -2
- package/dist/types/src/display/api_utils.d.ts +10 -0
- package/dist/types/src/display/canvas.d.ts +13 -3
- package/dist/types/src/display/canvas_dependency_tracker.d.ts +20 -10
- package/dist/types/src/display/canvas_factory.d.ts +1 -11
- package/dist/types/src/display/display_utils.d.ts +0 -71
- package/dist/types/src/display/dom_canvas_factory.d.ts +12 -0
- package/dist/types/src/display/dom_filter_factory.d.ts +23 -0
- package/dist/types/src/display/dom_utils.d.ts +68 -0
- package/dist/types/src/display/editor/draw.d.ts +2 -0
- package/dist/types/src/display/editor/drawers/inkdraw.d.ts +14 -17
- package/dist/types/src/display/editor/drawers/input_smoother.d.ts +28 -0
- package/dist/types/src/display/editor/drawers/outline.d.ts +2 -2
- package/dist/types/src/display/editor/ink.d.ts +2 -1
- package/dist/types/src/display/editor/tools.d.ts +2 -1
- package/dist/types/src/display/filter_factory.d.ts +0 -22
- package/dist/types/src/display/object_handler.d.ts +21 -0
- package/dist/types/src/display/pdf_objects.d.ts +10 -1
- package/dist/types/src/display/renderer_worker_proxy.d.ts +131 -0
- package/dist/types/src/display/text_layer.d.ts +1 -6
- package/dist/types/src/display/worker_options.d.ts +24 -0
- package/dist/types/src/pdf.d.ts +12 -12
- package/dist/types/src/shared/message_handler.d.ts +1 -0
- package/dist/types/src/shared/util.d.ts +4 -0
- package/dist/types/web/annotation_layer_builder.d.ts +1 -0
- package/dist/types/web/autolinker.d.ts +4 -4
- package/dist/types/web/base_download_manager.d.ts +3 -2
- package/dist/types/web/download_manager.d.ts +1 -0
- package/dist/types/web/pdf_page_view.d.ts +1 -0
- package/dist/types/web/pdf_scripting_manager.d.ts +1 -1
- package/dist/types/web/pdf_thumbnail_viewer.d.ts +7 -1
- package/package.json +33 -24
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ npm install unpdf
|
|
|
25
25
|
|
|
26
26
|
## Use Cases
|
|
27
27
|
|
|
28
|
-
Every method takes binary PDF data (`Uint8Array`, `ArrayBuffer`) or a document proxy from [`getDocumentProxy`](#getdocumentproxy). Pass a proxy to run several methods on one document without parsing it again.
|
|
28
|
+
Every method takes binary PDF data (`Uint8Array`, `ArrayBuffer`) or a document proxy from [`getDocumentProxy`](#getdocumentproxy). PDF.js takes ownership of binary data, so it works for one call only. Pass a proxy to run several methods on one document without parsing it again.
|
|
29
29
|
|
|
30
30
|
### Extract Text
|
|
31
31
|
|
|
@@ -94,20 +94,20 @@ const scannedPageNumbers = pages
|
|
|
94
94
|
|
|
95
95
|
PDF.js does not execute scripts embedded in PDFs, but resource limits are your job:
|
|
96
96
|
|
|
97
|
-
- **Image decoding:** `maxImageSize` is unlimited by default – pass e.g. `getDocumentProxy(data, { maxImageSize: 16_777_216 })` (~16 MP) so a single declared image
|
|
97
|
+
- **Image decoding:** `maxImageSize` is unlimited by default – pass e.g. `getDocumentProxy(data, { maxImageSize: 16_777_216 })` (~16 MP) so a single declared image cannot allocate gigabytes.
|
|
98
98
|
- **Page fan-out:** `extractText`, `extractTextItems`, `extractLinks`, and `inspectPages` process all pages in one call – check `pdf.numPages` against a limit first.
|
|
99
99
|
- **Timeouts:** with the serverless build, parsing runs on your event loop (no worker) – race extraction calls against a timeout.
|
|
100
100
|
|
|
101
101
|
## API
|
|
102
102
|
|
|
103
|
-
`data` is binary PDF data or a `PDFDocumentProxy` throughout.
|
|
103
|
+
`data` is binary PDF data or a `PDFDocumentProxy` throughout. `pageNumber` counts from 1.
|
|
104
104
|
|
|
105
105
|
### `getDocumentProxy`
|
|
106
106
|
|
|
107
|
-
Creates a `PDFDocumentProxy` with `useSystemFonts: true`. In Node.js with `pdfjs-dist` installed, it uses that package's standard fonts instead of system fonts
|
|
107
|
+
Creates a `PDFDocumentProxy` with `useSystemFonts: true`. In Node.js with `pdfjs-dist` installed, it uses that package's standard fonts instead of system fonts and its CJK character maps (`cMapUrl`). A PDF.js build other than the serverless one also gets that package's image decoders (`wasmUrl`). Cloudflare Workers have no local `pdfjs-dist` – to extract text from CJK fonts without embedded mappings, pass `cMapUrl: 'https://unpkg.com/pdfjs-dist@6.5.438/cmaps/'`, `cMapPacked: true`, and `useWorkerFetch: true`. Your options override the defaults.
|
|
108
108
|
|
|
109
109
|
```ts
|
|
110
|
-
function getDocumentProxy(data: Uint8Array | ArrayBuffer, options?:
|
|
110
|
+
function getDocumentProxy(data: Uint8Array | ArrayBuffer, options?: Parameters<typeof import('unpdf/pdfjs').getDocument>[0]): Promise<PDFDocumentProxy>
|
|
111
111
|
```
|
|
112
112
|
|
|
113
113
|
### `extractText`
|
|
@@ -136,7 +136,7 @@ function extractLinks(data): Promise<{ totalPages: number, links: string[][] }>
|
|
|
136
136
|
|
|
137
137
|
### `extractImages`
|
|
138
138
|
|
|
139
|
-
Extracts the images painted on a page – image XObjects, inline images, and image masks – as RGBA pixels or PNG bytes, each with `width
|
|
139
|
+
Extracts the images painted on a page – image XObjects, inline images, and image masks – as RGBA pixels or PNG bytes, each with its `width` and `height` in pixels and its `bounds` in PDF space.
|
|
140
140
|
|
|
141
141
|
```ts
|
|
142
142
|
function extractImages(data, pageNumber: number, options?: { format?: 'rgba' | 'png' }): Promise<ExtractedImage[]>
|
|
@@ -179,7 +179,7 @@ function getMeta(data, options?: { parseDates?: boolean }): Promise<{ info: PDFI
|
|
|
179
179
|
Sets the PDF.js build every other method uses. It loads on first use.
|
|
180
180
|
|
|
181
181
|
```ts
|
|
182
|
-
function definePDFJSModule(pdfjs: () => Promise<
|
|
182
|
+
function definePDFJSModule(pdfjs: () => Promise<typeof import('unpdf/pdfjs')>): void
|
|
183
183
|
```
|
|
184
184
|
|
|
185
185
|
### `getResolvedPDFJS`
|
|
@@ -187,7 +187,15 @@ function definePDFJSModule(pdfjs: () => Promise<PDFJS>): void
|
|
|
187
187
|
Returns the resolved PDF.js module – the serverless build, unless `definePDFJSModule` set another – to call the PDF.js API directly.
|
|
188
188
|
|
|
189
189
|
```ts
|
|
190
|
-
function getResolvedPDFJS(): Promise<
|
|
190
|
+
function getResolvedPDFJS(): Promise<typeof import('unpdf/pdfjs')>
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### `registerImageDecoders`
|
|
194
|
+
|
|
195
|
+
Registers PDF.js' JBIG2 and OpenJPEG decoders, which CCITT, JBIG2, and JPEG 2000 images need, with the serverless PDF.js build. `extractImages`, `renderPageAsImage`, and `inspectPages` call it themselves – call it before decoding these images through PDF.js directly, such as on the pages of a `getDocumentProxy` document. Another build set through `definePDFJSModule`, such as `pdfjs-dist`, ignores it and loads its decoders from `wasmUrl`, which [`getDocumentProxy`](#getdocumentproxy) sets in Node.js.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
function registerImageDecoders(): void
|
|
191
199
|
```
|
|
192
200
|
|
|
193
201
|
## Custom PDF.js Build
|
|
@@ -205,13 +213,13 @@ In Node.js, import the legacy build as shown. The default `pdfjs-dist` entry tar
|
|
|
205
213
|
## How It Works
|
|
206
214
|
|
|
207
215
|
> [!NOTE]
|
|
208
|
-
> The serverless PDF.js bundle is built from PDF.js v6.
|
|
216
|
+
> The serverless PDF.js bundle is built from PDF.js v6.5.438. It requires the global `Iterator` constructor (Safari 18.4+); without it, importing the bundle throws.
|
|
209
217
|
|
|
210
218
|
Heart and soul of this package is the [`pdfjs.rolldown.config.ts`](./pdfjs.rolldown.config.ts) file. It uses [Rolldown](https://rolldown.rs/) to bundle PDF.js for serverless environments. The key techniques:
|
|
211
219
|
|
|
212
|
-
- **
|
|
213
|
-
- **Worker inlining** embeds the PDF.js worker directly into the main bundle, since serverless runtimes
|
|
214
|
-
- **Bundled image decoders** ship PDF.js' JBIG2 and OpenJPEG decoders, WASM and JS fallback, as lazy chunks, so CCITT, JBIG2, and JPEG 2000 images decode without `pdfjs-dist
|
|
220
|
+
- **Source patches** make PDF.js use what the bundle provides: the inlined worker, the bundled image decoders, and the `@napi-rs/canvas` module passed as `canvasImport`.
|
|
221
|
+
- **Worker inlining** embeds the PDF.js worker directly into the main bundle, since serverless runtimes cannot load separate worker files.
|
|
222
|
+
- **Bundled image decoders** ship PDF.js' JBIG2 and OpenJPEG decoders, WASM and JS fallback, as lazy chunks, so CCITT, JBIG2, and JPEG 2000 images decode without `pdfjs-dist`, and a bundle that only extracts text leaves them out. Bundlers that resolve the `workerd` condition, like Wrangler, ship only the JS fallbacks.
|
|
215
223
|
- **Global polyfills** fill in newer APIs like `Promise.try` and `Map.prototype.getOrInsert` for runtimes that lack them, plus `FinalizationRegistry` for Cloudflare Workers.
|
|
216
224
|
|
|
217
225
|
## License
|
package/dist/index.d.mts
CHANGED
|
@@ -63,6 +63,17 @@ export declare function renderPageAsImage(data: DocumentInitParameters["data"] |
|
|
|
63
63
|
toDataURL: true;
|
|
64
64
|
}): Promise<string>;
|
|
65
65
|
export declare function renderPageAsImage(data: DocumentInitParameters["data"] | PDFDocumentProxy, pageNumber: number, options?: RenderPageAsImageOptions): Promise<Uint8Array | string>;
|
|
66
|
+
/**
|
|
67
|
+
* Registers PDF.js' JBIG2 and OpenJPEG decoders, which CCITT, JBIG2, and JPEG
|
|
68
|
+
* 2000 images need, with the serverless PDF.js build. `extractImages`,
|
|
69
|
+
* `renderPageAsImage`, and `inspectPages` call this themselves, so a bundle that
|
|
70
|
+
* only extracts text leaves the decoders out. Call it before decoding these
|
|
71
|
+
* images through PDF.js directly; the decoders load on the first such image.
|
|
72
|
+
* Another build set through `definePDFJSModule`, such as `pdfjs-dist`, ignores
|
|
73
|
+
* it and loads its decoders from `wasmUrl`, which `getDocumentProxy` sets in
|
|
74
|
+
* Node.js.
|
|
75
|
+
*/
|
|
76
|
+
export declare function registerImageDecoders(): void;
|
|
66
77
|
interface PageInspection {
|
|
67
78
|
/** Characters of all text on the page, visible or not, whitespace excluded. */
|
|
68
79
|
textLength: number;
|
|
@@ -166,7 +177,8 @@ export declare function extractText(data: DocumentInitParameters["data"] | PDFDo
|
|
|
166
177
|
/**
|
|
167
178
|
* Creates a `PDFDocumentProxy` from binary PDF data, with `useSystemFonts:
|
|
168
179
|
* true`. In Node.js with `pdfjs-dist` installed, it uses that package's
|
|
169
|
-
* standard fonts instead of system fonts
|
|
180
|
+
* standard fonts instead of system fonts and its packed CMaps. A PDF.js build
|
|
181
|
+
* other than the serverless one also gets that package's image decoders.
|
|
170
182
|
*/
|
|
171
183
|
export declare function getDocumentProxy(data: DocumentInitParameters["data"], options?: DocumentInitParameters): Promise<PDFDocumentProxy>;
|
|
172
184
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
1
|
// src/_internal/dommatrix-polyfill.ts
|
|
2
|
-
/**
|
|
3
|
-
* Stubs `DOMMatrix`, which PDF.js reads while its modules evaluate, so it must
|
|
4
|
-
* run before any PDF.js module is imported.
|
|
5
|
-
*/
|
|
6
2
|
function polyfillDOMMatrix() {
|
|
7
3
|
if (typeof globalThis.DOMMatrix !== "undefined") return;
|
|
8
4
|
globalThis.DOMMatrix = class DOMMatrix {
|
|
@@ -50,10 +46,12 @@ const isNode = isNodeProcess(globalThis.process);
|
|
|
50
46
|
/**
|
|
51
47
|
* Creates a `PDFDocumentProxy` from binary PDF data, with `useSystemFonts:
|
|
52
48
|
* true`. In Node.js with `pdfjs-dist` installed, it uses that package's
|
|
53
|
-
* standard fonts instead of system fonts
|
|
49
|
+
* standard fonts instead of system fonts and its packed CMaps. A PDF.js build
|
|
50
|
+
* other than the serverless one also gets that package's image decoders.
|
|
54
51
|
*/
|
|
55
52
|
async function getDocumentProxy(data, options = {}) {
|
|
56
53
|
const { getDocument } = await getResolvedPDFJS();
|
|
54
|
+
if (globalThis.Buffer?.isBuffer(data)) data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
57
55
|
let nodeDefaults = {};
|
|
58
56
|
if (isNode) try {
|
|
59
57
|
const nodeProcess = globalThis.process;
|
|
@@ -64,7 +62,8 @@ async function getDocumentProxy(data, options = {}) {
|
|
|
64
62
|
useSystemFonts: false,
|
|
65
63
|
standardFontDataUrl: `${join(pdfjsDir, "standard_fonts")}/`,
|
|
66
64
|
cMapUrl: `${join(pdfjsDir, "cmaps")}/`,
|
|
67
|
-
cMapPacked: true
|
|
65
|
+
cMapPacked: true,
|
|
66
|
+
wasmUrl: `${join(pdfjsDir, "wasm")}/`
|
|
68
67
|
};
|
|
69
68
|
} catch {}
|
|
70
69
|
return await getDocument({
|
|
@@ -119,9 +118,10 @@ async function interopDefault(m) {
|
|
|
119
118
|
return resolved.default || resolved;
|
|
120
119
|
}
|
|
121
120
|
async function loadPDFJS(loader) {
|
|
122
|
-
polyfillDOMMatrix();
|
|
123
121
|
try {
|
|
124
|
-
|
|
122
|
+
const pdfjs = await interopDefault(loader ? loader() : import("unpdf/pdfjs"));
|
|
123
|
+
polyfillDOMMatrix();
|
|
124
|
+
return pdfjs;
|
|
125
125
|
} catch (error) {
|
|
126
126
|
throw new Error(`PDF.js could not be resolved: ${error}`, { cause: error });
|
|
127
127
|
}
|
|
@@ -160,8 +160,8 @@ async function resolveCanvasModule(canvasImport) {
|
|
|
160
160
|
*
|
|
161
161
|
* @remarks
|
|
162
162
|
* `DOMMatrix` is always set because {@link polyfillDOMMatrix} may have
|
|
163
|
-
* installed a minimal stub
|
|
164
|
-
*
|
|
163
|
+
* installed a minimal stub – the real `@napi-rs/canvas` implementation must
|
|
164
|
+
* take precedence for rendering.
|
|
165
165
|
*/
|
|
166
166
|
function injectCanvasConstructors() {
|
|
167
167
|
if (!resolvedCanvasModule) return;
|
|
@@ -348,6 +348,23 @@ function createCRCTable() {
|
|
|
348
348
|
}
|
|
349
349
|
return table;
|
|
350
350
|
}
|
|
351
|
+
// src/image-decoders.ts
|
|
352
|
+
/**
|
|
353
|
+
* Registers PDF.js' JBIG2 and OpenJPEG decoders, which CCITT, JBIG2, and JPEG
|
|
354
|
+
* 2000 images need, with the serverless PDF.js build. `extractImages`,
|
|
355
|
+
* `renderPageAsImage`, and `inspectPages` call this themselves, so a bundle that
|
|
356
|
+
* only extracts text leaves the decoders out. Call it before decoding these
|
|
357
|
+
* images through PDF.js directly; the decoders load on the first such image.
|
|
358
|
+
* Another build set through `definePDFJSModule`, such as `pdfjs-dist`, ignores
|
|
359
|
+
* it and loads its decoders from `wasmUrl`, which `getDocumentProxy` sets in
|
|
360
|
+
* Node.js.
|
|
361
|
+
*/
|
|
362
|
+
function registerImageDecoders() {
|
|
363
|
+
globalThis[Symbol.for("unpdf.loadImageDecoder")] ??= async (fileName) => {
|
|
364
|
+
const { loadDecoder } = await import("#pdfjs-decoders");
|
|
365
|
+
return await loadDecoder(fileName);
|
|
366
|
+
};
|
|
367
|
+
}
|
|
351
368
|
// src/image.ts
|
|
352
369
|
/**
|
|
353
370
|
* Extracts the images painted on a page – image XObjects, inline images, and
|
|
@@ -362,6 +379,7 @@ function createCRCTable() {
|
|
|
362
379
|
* some images out as bitmaps instead of pixels, which are skipped.
|
|
363
380
|
*/
|
|
364
381
|
async function extractImages(data, pageNumber, options = {}) {
|
|
382
|
+
registerImageDecoders();
|
|
365
383
|
return await withDocument(data, async (pdf) => {
|
|
366
384
|
if (pageNumber < 1 || pageNumber > pdf.numPages) throw new Error(`Invalid page number. Must be between 1 and ${pdf.numPages}.`);
|
|
367
385
|
const page = await pdf.getPage(pageNumber);
|
|
@@ -398,6 +416,7 @@ async function extractImages(data, pageNumber, options = {}) {
|
|
|
398
416
|
});
|
|
399
417
|
}
|
|
400
418
|
async function renderPageAsImage(data, pageNumber, options = {}) {
|
|
419
|
+
registerImageDecoders();
|
|
401
420
|
await prepareCanvasEnvironment(options.canvasImport);
|
|
402
421
|
return await withDocument(data, async (pdf) => {
|
|
403
422
|
if (pageNumber < 1 || pageNumber > pdf.numPages) throw new Error(`Invalid page number. Must be between 1 and ${pdf.numPages}.`);
|
|
@@ -476,7 +495,8 @@ function toRGBA(image, isMask, imageKind) {
|
|
|
476
495
|
return rgba;
|
|
477
496
|
}
|
|
478
497
|
async function prepareCanvasEnvironment(canvasImport) {
|
|
479
|
-
|
|
498
|
+
const isWorkerd = globalThis.navigator?.userAgent === "Cloudflare-Workers";
|
|
499
|
+
if (isNode && !isWorkerd) {
|
|
480
500
|
if (!canvasImport) throw new Error("Parameter \"canvasImport\" is required in Node.js environment.");
|
|
481
501
|
await resolveCanvasModule(canvasImport);
|
|
482
502
|
injectCanvasConstructors();
|
|
@@ -494,6 +514,7 @@ const WHITESPACE_PATTERN = /\s/g;
|
|
|
494
514
|
* from born-digital ones. Where that line lies is left to the caller.
|
|
495
515
|
*/
|
|
496
516
|
async function inspectPages(data) {
|
|
517
|
+
registerImageDecoders();
|
|
497
518
|
return await withDocument(data, async (pdf) => {
|
|
498
519
|
const { OPS } = await getResolvedPDFJS();
|
|
499
520
|
const optionalContentConfig = await pdf.getOptionalContentConfig();
|
|
@@ -548,7 +569,7 @@ function getCoverage(boxes, view) {
|
|
|
548
569
|
const right = edges[i + 1];
|
|
549
570
|
const spans = clippedBoxes.filter((box) => box.x0 <= left && box.x1 >= right).sort((a, b) => a.y0 - b.y0);
|
|
550
571
|
let coveredHeight = 0;
|
|
551
|
-
let coveredTop = -
|
|
572
|
+
let coveredTop = -1e400;
|
|
552
573
|
for (const { y0, y1 } of spans) {
|
|
553
574
|
const start = Math.max(y0, coveredTop);
|
|
554
575
|
if (y1 > start) {
|
|
@@ -660,4 +681,4 @@ async function getPageText(document, pageNumber) {
|
|
|
660
681
|
function normalizeMergedText(texts) {
|
|
661
682
|
return texts.join("\n").replace(/[^\S\n]+/g, " ").replace(/ ?\n ?/g, "\n").replace(/\n{3,}/g, "\n\n");
|
|
662
683
|
}
|
|
663
|
-
export { definePDFJSModule, extractImages, extractLinks, extractText, extractTextItems, getDocumentProxy, getMeta, getResolvedPDFJS, inspectPages, renderPageAsImage };
|
|
684
|
+
export { definePDFJSModule, extractImages, extractLinks, extractText, extractTextItems, getDocumentProxy, getMeta, getResolvedPDFJS, inspectPages, registerImageDecoders, renderPageAsImage };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./pdfjs-loader.mjs";const t=e({"jbig2_nowasm_fallback.js":()=>import(`./pdfjs-jbig2_nowasm_fallback.mjs`),"openjpeg_nowasm_fallback.js":()=>import(`./pdfjs-openjpeg_nowasm_fallback.mjs`)});export{t as loadDecoder};
|
package/dist/pdfjs-decoders.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e
|
|
1
|
+
import{t as e}from"./pdfjs-loader.mjs";const t=e({"jbig2.wasm":()=>import(`./pdfjs-jbig2.mjs`),"jbig2_nowasm_fallback.js":()=>import(`./pdfjs-jbig2_nowasm_fallback.mjs`),"openjpeg.wasm":()=>import(`./pdfjs-openjpeg.mjs`),"openjpeg_nowasm_fallback.js":()=>import(`./pdfjs-openjpeg_nowasm_fallback.mjs`)});export{t as loadDecoder};
|