unpdf 1.9.1 → 2.0.1

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/dist/index.mjs CHANGED
@@ -1,4 +1,8 @@
1
- //#region src/_internal/dommatrix-polyfill.ts
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
+ */
2
6
  function polyfillDOMMatrix() {
3
7
  if (typeof globalThis.DOMMatrix !== "undefined") return;
4
8
  globalThis.DOMMatrix = class DOMMatrix {
@@ -33,50 +37,40 @@ function polyfillDOMMatrix() {
33
37
  }
34
38
  };
35
39
  }
36
- //#endregion
37
- //#region src/_internal/env.ts
40
+ // src/utils.ts
41
+ let pdfjsLoader;
42
+ let resolvedModule;
43
+ let isWasmCompilable;
38
44
  /**
39
- * Stubs browser globals that PDF.js expects at the module level
40
- * in non-browser environments.
41
- *
42
- * @remarks
43
- * Must be called before importing any PDF.js module, since PDF.js
44
- * accesses these globals at parse time (top-level constants).
45
+ * Whether PDF.js takes its Node.js code paths, by PDF.js' own rule: a
46
+ * `process` object outside of NW.js and Electron renderers. It decides between
47
+ * PDF.js' Node.js and DOM factories for canvases, fonts, and CMaps.
45
48
  */
46
- function stubBrowserGlobals() {
47
- polyfillDOMMatrix();
48
- }
49
- //#endregion
50
- //#region src/utils.ts
51
- let resolvedModule;
52
- const isNode = globalThis.process?.release?.name === "node";
53
- const isBrowser = typeof window !== "undefined";
49
+ const isNode = isNodeProcess(globalThis.process);
54
50
  /**
55
- * Creates a `PDFDocumentProxy` from binary PDF data.
56
- *
57
- * Applies the following defaults:
58
- * - `useSystemFonts: true`
59
- *
60
- * In Node.js environments, additionally applies:
61
- * - `disableFontFace: true`
62
- * - `standardFontDataUrl` resolved from the local `pdfjs-dist` package
63
- * - `cMapUrl` and `cMapPacked` resolved from the local `pdfjs-dist` package
51
+ * Creates a `PDFDocumentProxy` from binary PDF data, with `useSystemFonts:
52
+ * true`. In Node.js with `pdfjs-dist` installed, it uses that package's
53
+ * standard fonts instead of system fonts, and its packed CMaps.
64
54
  */
65
55
  async function getDocumentProxy(data, options = {}) {
66
56
  const { getDocument } = await getResolvedPDFJS();
67
57
  let nodeDefaults = {};
68
58
  if (isNode) try {
69
- const base = import.meta.resolve("pdfjs-dist/package.json");
59
+ const nodeProcess = globalThis.process;
60
+ const { dirname, join } = nodeProcess.getBuiltinModule("node:path");
61
+ const { fileURLToPath } = nodeProcess.getBuiltinModule("node:url");
62
+ const pdfjsDir = dirname(fileURLToPath(import.meta.resolve("pdfjs-dist/package.json")));
70
63
  nodeDefaults = {
71
- disableFontFace: true,
72
- standardFontDataUrl: new URL("./standard_fonts/", base).href,
73
- cMapUrl: new URL("./cmaps/", base).href,
64
+ useSystemFonts: false,
65
+ standardFontDataUrl: `${join(pdfjsDir, "standard_fonts")}/`,
66
+ cMapUrl: `${join(pdfjsDir, "cmaps")}/`,
74
67
  cMapPacked: true
75
68
  };
76
69
  } catch {}
77
70
  return await getDocument({
78
71
  data,
79
72
  useSystemFonts: true,
73
+ useWasm: canCompileWasm(),
80
74
  ...nodeDefaults,
81
75
  ...options
82
76
  }).promise;
@@ -95,24 +89,27 @@ async function withDocument(data, operation, options) {
95
89
  if (pdf !== data) await pdf.loadingTask.destroy();
96
90
  }
97
91
  }
98
- async function getResolvedPDFJS() {
99
- if (!resolvedModule) await resolvePDFJSImport();
100
- return resolvedModule;
92
+ /**
93
+ * Sets the PDF.js build every other method uses. The build loads on first use,
94
+ * so call this before any other method. Without it, the serverless build is
95
+ * used.
96
+ *
97
+ * @example
98
+ * // In Node.js, the legacy build of `pdfjs-dist` (install it first)
99
+ * import { definePDFJSModule } from 'unpdf'
100
+ *
101
+ * definePDFJSModule(() => import('pdfjs-dist/legacy/build/pdf.mjs'))
102
+ */
103
+ function definePDFJSModule(pdfjs) {
104
+ pdfjsLoader = pdfjs;
105
+ resolvedModule = void 0;
101
106
  }
102
- async function resolvePDFJSImport(pdfjsResolver, { reload = false } = {}) {
103
- if (resolvedModule && !reload) return;
104
- stubBrowserGlobals();
105
- if (pdfjsResolver) try {
106
- resolvedModule = await interopDefault(pdfjsResolver());
107
- return;
108
- } catch (error) {
109
- throw new Error(`PDF.js could not be resolved: ${error}`);
110
- }
111
- try {
112
- resolvedModule = await import("unpdf/pdfjs");
113
- } catch (error) {
114
- throw new Error(`Serverless PDF.js bundle could not be resolved: ${error}`);
115
- }
107
+ function getResolvedPDFJS() {
108
+ resolvedModule ??= loadPDFJS(pdfjsLoader).catch((error) => {
109
+ resolvedModule = void 0;
110
+ throw error;
111
+ });
112
+ return resolvedModule;
116
113
  }
117
114
  function isPDFDocumentProxy(data) {
118
115
  return typeof data === "object" && data !== null && "_pdfInfo" in data;
@@ -121,177 +118,455 @@ async function interopDefault(m) {
121
118
  const resolved = await m;
122
119
  return resolved.default || resolved;
123
120
  }
124
- //#endregion
125
- //#region src/_internal/canvas.ts
126
- let resolvedCanvasModule;
127
- /**
128
- * Derived from the PDF.js project by the Mozilla Foundation.
129
- * @see https://github.com/mozilla/pdf.js/blob/b8de9a372f9bbf7e33adb362eeae5ef1919dba73/src/display/canvas_factory.js#L18
130
- * @license Apache-2.0
131
- */
132
- var BaseCanvasFactory = class {
133
- #enableHWA = false;
134
- constructor({ enableHWA = false } = {}) {
135
- this.#enableHWA = enableHWA;
136
- }
137
- create(width, height) {
138
- const canvas = this._createCanvas(width, height);
139
- return {
140
- canvas,
141
- context: canvas.getContext("2d", { willReadFrequently: !this.#enableHWA })
142
- };
143
- }
144
- reset({ canvas }, width, height) {
145
- if (!canvas) throw new Error("Canvas is not specified");
146
- canvas.width = width;
147
- canvas.height = height;
148
- }
149
- destroy(context) {
150
- if (!context.canvas) throw new Error("Canvas is not specified");
151
- context.canvas.width = 0;
152
- context.canvas.height = 0;
153
- context.canvas = void 0;
154
- context.context = void 0;
155
- }
156
- _createCanvas(width, height) {
157
- throw new Error("Not implemented");
158
- }
159
- };
160
- /**
161
- * Derived from the PDF.js project by the Mozilla Foundation.
162
- * @see https://github.com/mozilla/pdf.js/blob/b8de9a372f9bbf7e33adb362eeae5ef1919dba73/src/display/canvas_factory.js#L18
163
- * @license Apache-2.0
164
- */
165
- var DOMCanvasFactory = class extends BaseCanvasFactory {
166
- constructor({ ownerDocument = globalThis.document, enableHWA = false } = {}) {
167
- super({ enableHWA });
168
- this._document = ownerDocument;
169
- }
170
- _createCanvas(width, height) {
171
- const canvas = this._document.createElement("canvas");
172
- canvas.width = width;
173
- canvas.height = height;
174
- return canvas;
175
- }
176
- };
177
- var NodeCanvasFactory = class extends BaseCanvasFactory {
178
- constructor({ enableHWA = false } = {}) {
179
- super({ enableHWA });
121
+ async function loadPDFJS(loader) {
122
+ polyfillDOMMatrix();
123
+ try {
124
+ return await interopDefault(loader ? loader() : import("unpdf/pdfjs"));
125
+ } catch (error) {
126
+ throw new Error(`PDF.js could not be resolved: ${error}`, { cause: error });
180
127
  }
181
- _createCanvas(width, height) {
182
- if (!resolvedCanvasModule) throw new Error("@napi-rs/canvas module is not resolved");
183
- return resolvedCanvasModule.createCanvas(width, height);
128
+ }
129
+ function canCompileWasm() {
130
+ if (isWasmCompilable === void 0) try {
131
+ new WebAssembly.Module(new Uint8Array([
132
+ 0,
133
+ 97,
134
+ 115,
135
+ 109,
136
+ 1,
137
+ 0,
138
+ 0,
139
+ 0
140
+ ]));
141
+ isWasmCompilable = true;
142
+ } catch {
143
+ isWasmCompilable = false;
184
144
  }
185
- };
145
+ return isWasmCompilable;
146
+ }
147
+ function isNodeProcess(nodeProcess) {
148
+ return typeof nodeProcess === "object" && `${nodeProcess}` === "[object process]" && !nodeProcess.versions.nw && !(nodeProcess.versions.electron && nodeProcess.type && nodeProcess.type !== "browser");
149
+ }
150
+ // src/_internal/canvas.ts
151
+ let resolvedCanvasModule;
186
152
  async function resolveCanvasModule(canvasImport) {
187
153
  resolvedCanvasModule ??= await interopDefault(canvasImport());
188
154
  globalThis[Symbol.for("unpdf.canvasModule")] = resolvedCanvasModule;
189
155
  }
190
156
  /**
191
- * Injects `DOMMatrix`, `ImageData` and `Path2D` constructors from the
192
- * `@napi-rs/canvas` package into the global scope. This is necessary for
193
- * Node.js environments that do not support these constructors natively.
157
+ * Injects the `DOMMatrix` and `Path2D` constructors of `@napi-rs/canvas` into
158
+ * the global scope, which the PDF.js display layer instantiates while
159
+ * rendering. Only the legacy `pdfjs-dist` build polyfills them itself.
194
160
  *
195
161
  * @remarks
196
- * `DOMMatrix` is always set because {@link stubBrowserGlobals} may have
162
+ * `DOMMatrix` is always set because {@link polyfillDOMMatrix} may have
197
163
  * installed a minimal stub to allow PDF.js to import – the real
198
164
  * `@napi-rs/canvas` implementation must take precedence for rendering.
199
165
  */
200
166
  function injectCanvasConstructors() {
201
167
  if (!resolvedCanvasModule) return;
202
168
  globalThis.DOMMatrix = resolvedCanvasModule.DOMMatrix;
203
- if (typeof globalThis.ImageData === "undefined") globalThis.ImageData = resolvedCanvasModule.ImageData;
204
169
  if (typeof globalThis.Path2D === "undefined") globalThis.Path2D = resolvedCanvasModule.Path2D;
205
170
  }
206
- //#endregion
207
- //#region src/image.ts
171
+ // src/_internal/operator-list.ts
172
+ const IDENTITY_MATRIX = [
173
+ 1,
174
+ 0,
175
+ 0,
176
+ 1,
177
+ 0,
178
+ 0
179
+ ];
180
+ /**
181
+ * Walks an operator list in painting order, with the graphics state each
182
+ * operation draws with and whether it is visible. Skips the content of soft
183
+ * masks, which only modulates transparency.
184
+ */
185
+ function* walkOperatorList(operatorList, ops, optionalContentConfig) {
186
+ const stateStack = [];
187
+ let state = {
188
+ transform: IDENTITY_MATRIX,
189
+ textRenderingMode: 0
190
+ };
191
+ const softMaskGroupFlags = [];
192
+ const contentVisibilityFlags = [];
193
+ for (let i = 0; i < operatorList.fnArray.length; i++) {
194
+ const fn = operatorList.fnArray[i];
195
+ const args = operatorList.argsArray[i];
196
+ if (fn === ops.save) stateStack.push(state);
197
+ else if (fn === ops.restore || fn === ops.paintFormXObjectEnd || fn === ops.endAnnotation) state = stateStack.pop() ?? state;
198
+ else if (fn === ops.transform) state = {
199
+ ...state,
200
+ transform: multiplyMatrices(state.transform, args)
201
+ };
202
+ else if (fn === ops.paintFormXObjectBegin) {
203
+ stateStack.push(state);
204
+ const [formMatrix] = args;
205
+ if (formMatrix) state = {
206
+ ...state,
207
+ transform: multiplyMatrices(state.transform, formMatrix)
208
+ };
209
+ } else if (fn === ops.beginAnnotation) {
210
+ stateStack.push(state);
211
+ const [, , annotationTransform, appearanceMatrix] = args;
212
+ state = {
213
+ transform: multiplyMatrices(Array.from(annotationTransform), appearanceMatrix),
214
+ textRenderingMode: 0
215
+ };
216
+ } else if (fn === ops.setTextRenderingMode) state = {
217
+ ...state,
218
+ textRenderingMode: args[0]
219
+ };
220
+ else if (fn === ops.beginGroup) softMaskGroupFlags.push(Boolean(args[0]?.smask));
221
+ else if (fn === ops.endGroup) softMaskGroupFlags.pop();
222
+ else if (fn === ops.beginMarkedContent) contentVisibilityFlags.push(true);
223
+ else if (fn === ops.beginMarkedContentProps) {
224
+ const [tag, properties] = args;
225
+ contentVisibilityFlags.push(tag !== "OC" || optionalContentConfig.isVisible(properties));
226
+ } else if (fn === ops.endMarkedContent) contentVisibilityFlags.pop();
227
+ if (softMaskGroupFlags.includes(true)) continue;
228
+ yield {
229
+ fn,
230
+ args,
231
+ ...state,
232
+ isVisible: !contentVisibilityFlags.includes(false)
233
+ };
234
+ }
235
+ }
208
236
  /**
209
- * Extracts images from a specific page of a PDF document, including necessary metadata,
210
- * such as width, height, and calculated color channels.
237
+ * Maps the unit square, which PDF images are drawn into, through a transform
238
+ * and returns the axis-aligned box around the result.
211
239
  */
212
- async function extractImages$1(data, pageNumber) {
240
+ function getUnitSquareBounds(transform) {
241
+ const [a, b, c, d, e, f] = transform;
242
+ const xs = [
243
+ e,
244
+ a + e,
245
+ c + e,
246
+ a + c + e
247
+ ];
248
+ const ys = [
249
+ f,
250
+ b + f,
251
+ d + f,
252
+ b + d + f
253
+ ];
254
+ const minX = Math.min(...xs);
255
+ const minY = Math.min(...ys);
256
+ return {
257
+ x: minX,
258
+ y: minY,
259
+ width: Math.max(...xs) - minX,
260
+ height: Math.max(...ys) - minY
261
+ };
262
+ }
263
+ /** Applies `inner` first, then `outer`, like `cm` concatenating onto the current matrix. */
264
+ function multiplyMatrices(outer, inner) {
265
+ const [a, b, c, d, e, f] = outer;
266
+ const [a2, b2, c2, d2, e2, f2] = Array.from(inner);
267
+ return [
268
+ a * a2 + c * b2,
269
+ b * a2 + d * b2,
270
+ a * c2 + c * d2,
271
+ b * c2 + d * d2,
272
+ a * e2 + c * f2 + e,
273
+ b * e2 + d * f2 + f
274
+ ];
275
+ }
276
+ // src/_internal/png.ts
277
+ const PNG_SIGNATURE = [
278
+ 137,
279
+ 80,
280
+ 78,
281
+ 71,
282
+ 13,
283
+ 10,
284
+ 26,
285
+ 10
286
+ ];
287
+ let crcTable;
288
+ /**
289
+ * Encodes RGBA pixels as an unfiltered 8-bit RGBA PNG, compressed through
290
+ * `CompressionStream`, which Node.js, Cloudflare Workers, and browsers all provide.
291
+ */
292
+ async function encodePNG(rgba, width, height) {
293
+ const rowLength = width * 4;
294
+ const scanlines = new Uint8Array((rowLength + 1) * height);
295
+ for (let y = 0; y < height; y++) scanlines.set(rgba.subarray(y * rowLength, (y + 1) * rowLength), y * (rowLength + 1) + 1);
296
+ const header = /* @__PURE__ */ new Uint8Array(13);
297
+ const headerView = new DataView(header.buffer);
298
+ headerView.setUint32(0, width);
299
+ headerView.setUint32(4, height);
300
+ header[8] = 8;
301
+ header[9] = 6;
302
+ const chunks = [
303
+ createChunk("IHDR", header),
304
+ createChunk("IDAT", await deflate(scanlines)),
305
+ createChunk("IEND", /* @__PURE__ */ new Uint8Array(0))
306
+ ];
307
+ const png = new Uint8Array(PNG_SIGNATURE.length + chunks.reduce((sum, chunk) => sum + chunk.length, 0));
308
+ png.set(PNG_SIGNATURE);
309
+ let offset = PNG_SIGNATURE.length;
310
+ for (const chunk of chunks) {
311
+ png.set(chunk, offset);
312
+ offset += chunk.length;
313
+ }
314
+ return png;
315
+ }
316
+ async function deflate(data) {
317
+ const stream = new CompressionStream("deflate");
318
+ const writer = stream.writable.getWriter();
319
+ const [compressed] = await Promise.all([
320
+ new Response(stream.readable).arrayBuffer(),
321
+ writer.write(data),
322
+ writer.close()
323
+ ]);
324
+ return new Uint8Array(compressed);
325
+ }
326
+ /** Lays out a chunk as length, type, data, and the CRC of type and data. */
327
+ function createChunk(type, data) {
328
+ const chunk = new Uint8Array(12 + data.length);
329
+ const view = new DataView(chunk.buffer);
330
+ view.setUint32(0, data.length);
331
+ for (let i = 0; i < 4; i++) chunk[4 + i] = type.charCodeAt(i);
332
+ chunk.set(data, 8);
333
+ view.setUint32(8 + data.length, crc32(chunk.subarray(4, 8 + data.length)));
334
+ return chunk;
335
+ }
336
+ function crc32(bytes) {
337
+ crcTable ??= createCRCTable();
338
+ let crc = 4294967295;
339
+ for (const byte of bytes) crc = crcTable[(crc ^ byte) & 255] ^ crc >>> 8;
340
+ return (crc ^ 4294967295) >>> 0;
341
+ }
342
+ function createCRCTable() {
343
+ const table = /* @__PURE__ */ new Uint32Array(256);
344
+ for (let n = 0; n < 256; n++) {
345
+ let crc = n;
346
+ for (let k = 0; k < 8; k++) crc = crc & 1 ? 3988292384 ^ crc >>> 1 : crc >>> 1;
347
+ table[n] = crc;
348
+ }
349
+ return table;
350
+ }
351
+ // src/image.ts
352
+ /**
353
+ * Extracts the images painted on a page – image XObjects, inline images, and
354
+ * image masks – as RGBA pixels. Image masks come out opaque black where they
355
+ * paint and transparent elsewhere, since their color is the fill color at the
356
+ * time of painting. A 1×1 image mask that paints its pixel, which PDF.js
357
+ * turns into a solid fill, is skipped.
358
+ *
359
+ * @remarks
360
+ * A caller-supplied document proxy created with `isOffscreenCanvasSupported`
361
+ * or `isImageDecoderSupported` (both on by default outside of Node.js) hands
362
+ * some images out as bitmaps instead of pixels, which are skipped.
363
+ */
364
+ async function extractImages(data, pageNumber, options = {}) {
213
365
  return await withDocument(data, async (pdf) => {
214
366
  if (pageNumber < 1 || pageNumber > pdf.numPages) throw new Error(`Invalid page number. Must be between 1 and ${pdf.numPages}.`);
215
367
  const page = await pdf.getPage(pageNumber);
216
- const operatorList = await page.getOperatorList();
217
- const { OPS } = await getResolvedPDFJS();
368
+ const [operatorList, optionalContentConfig] = await Promise.all([page.getOperatorList(), pdf.getOptionalContentConfig()]);
369
+ const { ImageKind, OPS } = await getResolvedPDFJS();
218
370
  const images = [];
219
- for (let i = 0; i < operatorList.fnArray.length; i++) {
220
- if (operatorList.fnArray[i] !== OPS.paintImageXObject) continue;
221
- const imageKey = operatorList.argsArray[i][0];
222
- const image = await new Promise((resolve) => (imageKey.startsWith("g_") ? page.commonObjs : page.objs).get(imageKey, resolve));
223
- if (!image || !image.data || !image.width || !image.height) continue;
224
- const { width, height, data } = image;
225
- const calculatedChannels = data.length / (width * height);
226
- if (![
227
- 1,
228
- 3,
229
- 4
230
- ].includes(calculatedChannels)) continue;
231
- const channels = calculatedChannels;
371
+ for (const { fn, args, transform, isVisible } of walkOperatorList(operatorList, OPS, optionalContentConfig)) {
372
+ if (!isVisible) continue;
373
+ let key = null;
374
+ let image;
375
+ if (fn === OPS.paintImageXObject) {
376
+ key = args[0];
377
+ image = await getPageObject(page, key);
378
+ } else if (fn === OPS.paintInlineImageXObject) image = args[0];
379
+ else if (fn === OPS.paintImageMaskXObject) {
380
+ key = args[0].data;
381
+ image = await getPageObject(page, key);
382
+ } else continue;
383
+ if (!image) continue;
384
+ const pixels = toRGBA(image, fn === OPS.paintImageMaskXObject, ImageKind);
385
+ if (!pixels) continue;
232
386
  images.push({
233
- data,
234
- width,
235
- height,
236
- channels,
237
- key: imageKey
387
+ data: options.format === "png" ? await encodePNG(pixels, image.width, image.height) : pixels,
388
+ width: image.width,
389
+ height: image.height,
390
+ key,
391
+ bounds: getUnitSquareBounds(transform)
238
392
  });
239
393
  }
240
394
  return images;
395
+ }, {
396
+ isOffscreenCanvasSupported: false,
397
+ isImageDecoderSupported: false
241
398
  });
242
399
  }
243
- async function renderPageAsImage$1(data, pageNumber, options = {}) {
244
- const CanvasFactory = await createIsomorphicCanvasFactory(options.canvasImport);
400
+ async function renderPageAsImage(data, pageNumber, options = {}) {
401
+ await prepareCanvasEnvironment(options.canvasImport);
245
402
  return await withDocument(data, async (pdf) => {
246
403
  if (pageNumber < 1 || pageNumber > pdf.numPages) throw new Error(`Invalid page number. Must be between 1 and ${pdf.numPages}.`);
247
404
  const page = await pdf.getPage(pageNumber);
248
405
  const defaultViewport = page.getViewport({ scale: 1 });
249
- let scale = options.scale || 1;
250
- if (options.width) scale = options.width / defaultViewport.width;
251
- else if (options.height) scale = options.height / defaultViewport.height;
252
- const viewport = page.getViewport({ scale: Math.max(0, scale) });
253
- const canvasFactory = new CanvasFactory();
254
- const drawingContext = canvasFactory.create(viewport.width, viewport.height);
406
+ let scale = options.scale ?? 1;
407
+ if (options.width !== void 0) scale = options.width / defaultViewport.width;
408
+ else if (options.height !== void 0) scale = options.height / defaultViewport.height;
409
+ const viewport = page.getViewport({ scale });
410
+ const canvasFactory = pdf.canvasFactory;
411
+ const canvasAndContext = canvasFactory.create(viewport.width, viewport.height);
255
412
  try {
413
+ const { canvas } = canvasAndContext;
256
414
  await page.render({
257
- canvas: drawingContext.canvas,
258
- canvasContext: drawingContext.context,
415
+ canvas,
259
416
  viewport
260
417
  }).promise;
261
- const { canvas } = drawingContext;
262
- if (options.toDataURL) return canvas.toDataURL();
418
+ const { format = "png", quality } = options;
419
+ const mimeType = `image/${format}`;
420
+ if (options.toDataURL) {
421
+ const dataURL = canvas.toDataURL(mimeType, quality);
422
+ assertEncodedType(dataURL.slice(5, dataURL.indexOf(";")), mimeType);
423
+ return dataURL;
424
+ }
263
425
  if ("encode" in canvas) {
264
- const buffer = await canvas.encode("png");
265
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
426
+ const buffer = format === "png" ? await canvas.encode(format) : await canvas.encode(format, quality === void 0 ? void 0 : quality * 100);
427
+ return new Uint8Array(buffer);
266
428
  }
267
429
  const blob = await new Promise((resolve) => {
268
- canvas.toBlob(resolve);
430
+ canvas.toBlob(resolve, mimeType, quality);
269
431
  });
270
- if (!blob) throw new Error("Failed to encode canvas to a PNG blob.");
271
- return await blob.arrayBuffer();
432
+ if (!blob) throw new Error(`Failed to encode canvas as ${mimeType}.`);
433
+ assertEncodedType(blob.type, mimeType);
434
+ return new Uint8Array(await blob.arrayBuffer());
272
435
  } finally {
273
- canvasFactory.destroy(drawingContext);
436
+ canvasFactory.destroy(canvasAndContext);
437
+ }
438
+ });
439
+ }
440
+ function getPageObject(page, objectId) {
441
+ const objects = objectId.startsWith("g_") ? page.commonObjs : page.objs;
442
+ return new Promise((resolve) => objects.get(objectId, resolve));
443
+ }
444
+ /**
445
+ * Converts PDF.js image data into a fresh RGBA buffer, so the result never
446
+ * aliases a buffer PDF.js keeps cached.
447
+ */
448
+ function toRGBA(image, isMask, imageKind) {
449
+ const { data, width, height, kind } = image;
450
+ if (!data) return;
451
+ const rgba = new Uint8Array(width * height * 4);
452
+ if (kind === imageKind.RGBA_32BPP) {
453
+ rgba.set(data.subarray(0, rgba.length));
454
+ return rgba;
455
+ }
456
+ if (kind === imageKind.RGB_24BPP) {
457
+ for (let source = 0, target = 0; target < rgba.length; source += 3, target += 4) {
458
+ rgba[target] = data[source];
459
+ rgba[target + 1] = data[source + 1];
460
+ rgba[target + 2] = data[source + 2];
461
+ rgba[target + 3] = 255;
462
+ }
463
+ return rgba;
464
+ }
465
+ if (!isMask && kind !== imageKind.GRAYSCALE_1BPP) return;
466
+ const bytesPerRow = Math.ceil(width / 8);
467
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
468
+ const bit = data[y * bytesPerRow + (x >> 3)] >> 7 - (x & 7) & 1;
469
+ const target = (y * width + x) * 4;
470
+ if (isMask) rgba[target + 3] = bit === 0 ? 255 : 0;
471
+ else {
472
+ rgba.fill(bit === 0 ? 0 : 255, target, target + 3);
473
+ rgba[target + 3] = 255;
274
474
  }
275
- }, { CanvasFactory });
475
+ }
476
+ return rgba;
276
477
  }
277
- async function createIsomorphicCanvasFactory(canvasImport) {
278
- if (isBrowser) return DOMCanvasFactory;
478
+ async function prepareCanvasEnvironment(canvasImport) {
279
479
  if (isNode) {
280
480
  if (!canvasImport) throw new Error("Parameter \"canvasImport\" is required in Node.js environment.");
281
481
  await resolveCanvasModule(canvasImport);
282
482
  injectCanvasConstructors();
283
- return NodeCanvasFactory;
483
+ return;
484
+ }
485
+ if (typeof document === "undefined") throw new Error("Unsupported environment for canvas creation.");
486
+ }
487
+ function assertEncodedType(encodedType, mimeType) {
488
+ if (encodedType !== mimeType) throw new Error(`This environment can't encode ${mimeType}, only ${encodedType}.`);
489
+ }
490
+ // src/inspect.ts
491
+ const WHITESPACE_PATTERN = /\s/g;
492
+ /**
493
+ * Measures the text and images of every page, such as to tell scanned pages
494
+ * from born-digital ones. Where that line lies is left to the caller.
495
+ */
496
+ async function inspectPages(data) {
497
+ return await withDocument(data, async (pdf) => {
498
+ const { OPS } = await getResolvedPDFJS();
499
+ const optionalContentConfig = await pdf.getOptionalContentConfig();
500
+ const shouldReleasePages = !isPDFDocumentProxy(data);
501
+ const pages = [];
502
+ for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) pages.push(await inspectPage(pdf, pageNumber, OPS, optionalContentConfig, shouldReleasePages));
503
+ return {
504
+ totalPages: pdf.numPages,
505
+ pages
506
+ };
507
+ });
508
+ }
509
+ async function inspectPage(document, pageNumber, ops, optionalContentConfig, shouldReleasePage) {
510
+ const page = await document.getPage(pageNumber);
511
+ const [textContent, operatorList] = await Promise.all([page.getTextContent(), page.getOperatorList()]);
512
+ const textLength = textContent.items.reduce((sum, item) => sum + ("str" in item ? countCharacters(item.str) : 0), 0);
513
+ let invisibleTextLength = 0;
514
+ const imageBounds = [];
515
+ for (const { fn, args, transform, textRenderingMode, isVisible } of walkOperatorList(operatorList, ops, optionalContentConfig)) if (fn === ops.showText && (!isVisible || textRenderingMode === 3 || textRenderingMode === 7)) {
516
+ for (const glyph of args[0]) if (typeof glyph === "object" && glyph?.unicode) invisibleTextLength += countCharacters(glyph.unicode);
517
+ } else if (isVisible && (fn === ops.paintImageXObject || fn === ops.paintInlineImageXObject || fn === ops.paintImageMaskXObject)) imageBounds.push(getUnitSquareBounds(transform));
518
+ if (shouldReleasePage) page.cleanup();
519
+ return {
520
+ textLength,
521
+ invisibleTextLength,
522
+ imageCount: imageBounds.length,
523
+ imageCoverage: getCoverage(imageBounds, page.view)
524
+ };
525
+ }
526
+ function countCharacters(text) {
527
+ return Array.from(text.replace(WHITESPACE_PATTERN, "")).length;
528
+ }
529
+ /**
530
+ * Computes the fraction of a view box the union of boxes covers, exactly: cuts
531
+ * the view box into vertical slabs at every box edge and merges the vertical
532
+ * extents of the boxes spanning each slab.
533
+ */
534
+ function getCoverage(boxes, view) {
535
+ const [viewX0, viewY0, viewX1, viewY1] = view;
536
+ const viewArea = (viewX1 - viewX0) * (viewY1 - viewY0);
537
+ if (viewArea <= 0) return 0;
538
+ const clippedBoxes = boxes.map((box) => ({
539
+ x0: Math.max(box.x, viewX0),
540
+ x1: Math.min(box.x + box.width, viewX1),
541
+ y0: Math.max(box.y, viewY0),
542
+ y1: Math.min(box.y + box.height, viewY1)
543
+ })).filter((box) => box.x0 < box.x1 && box.y0 < box.y1);
544
+ const edges = [...new Set(clippedBoxes.flatMap((box) => [box.x0, box.x1]))].sort((a, b) => a - b);
545
+ let area = 0;
546
+ for (let i = 0; i < edges.length - 1; i++) {
547
+ const left = edges[i];
548
+ const right = edges[i + 1];
549
+ const spans = clippedBoxes.filter((box) => box.x0 <= left && box.x1 >= right).sort((a, b) => a.y0 - b.y0);
550
+ let coveredHeight = 0;
551
+ let coveredTop = -Infinity;
552
+ for (const { y0, y1 } of spans) {
553
+ const start = Math.max(y0, coveredTop);
554
+ if (y1 > start) {
555
+ coveredHeight += y1 - start;
556
+ coveredTop = y1;
557
+ }
558
+ }
559
+ area += coveredHeight * (right - left);
284
560
  }
285
- throw new Error("Unsupported environment for canvas creation.");
561
+ return area / viewArea;
286
562
  }
287
- //#endregion
288
- //#region src/links.ts
289
- async function extractLinks$1(data) {
563
+ // src/links.ts
564
+ async function extractLinks(data) {
290
565
  return await withDocument(data, async (pdf) => {
291
- const pageLinks = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageLinks(pdf, i + 1)));
566
+ const links = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageLinks(pdf, i + 1)));
292
567
  return {
293
568
  totalPages: pdf.numPages,
294
- links: pageLinks.flat()
569
+ links
295
570
  };
296
571
  });
297
572
  }
@@ -301,8 +576,7 @@ async function getPageLinks(document, pageNumber) {
301
576
  for (const annotation of annotations) if (annotation.subtype === "Link" && annotation.url) links.push(annotation.url);
302
577
  return links;
303
578
  }
304
- //#endregion
305
- //#region src/meta.ts
579
+ // src/meta.ts
306
580
  const XMP_DATE_PROPERTIES = [
307
581
  "xmp:createdate",
308
582
  "xmp:modifydate",
@@ -311,7 +585,7 @@ const XMP_DATE_PROPERTIES = [
311
585
  "xap:modifydate",
312
586
  "xap:metadatadate"
313
587
  ];
314
- async function getMeta$1(data, options = {}) {
588
+ async function getMeta(data, options = {}) {
315
589
  return await withDocument(data, async (pdf) => {
316
590
  const meta = await pdf.getMetadata();
317
591
  const info = { ...meta.info };
@@ -330,18 +604,16 @@ async function getMeta$1(data, options = {}) {
330
604
  }
331
605
  return {
332
606
  info,
333
- metadata: metadata || {}
607
+ metadata: metadata ?? null
334
608
  };
335
609
  });
336
610
  }
337
611
  function parseISODateString(isoDateString) {
338
- if (!isoDateString) return;
339
612
  const parsedDate = Date.parse(isoDateString);
340
- if (!Number.isNaN(parsedDate)) return new Date(parsedDate);
613
+ return Number.isNaN(parsedDate) ? null : new Date(parsedDate);
341
614
  }
342
- //#endregion
343
- //#region src/text.ts
344
- async function extractTextItems$1(data) {
615
+ // src/text.ts
616
+ async function extractTextItems(data) {
345
617
  return await withDocument(data, async (pdf) => {
346
618
  const items = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageTextItems(pdf, i + 1)));
347
619
  return {
@@ -368,7 +640,7 @@ async function getPageTextItems(document, pageNumber) {
368
640
  };
369
641
  });
370
642
  }
371
- async function extractText$1(data, options = {}) {
643
+ async function extractText(data, options = {}) {
372
644
  const { mergePages = false } = options;
373
645
  return await withDocument(data, async (pdf) => {
374
646
  const texts = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageText(pdf, i + 1)));
@@ -388,50 +660,4 @@ async function getPageText(document, pageNumber) {
388
660
  function normalizeMergedText(texts) {
389
661
  return texts.join("\n").replace(/[^\S\n]+/g, " ").replace(/ ?\n ?/g, "\n").replace(/\n{3,}/g, "\n\n");
390
662
  }
391
- //#endregion
392
- //#region src/config.ts
393
- /**
394
- * Sets the PDF.js build every other method uses – call it before any of them.
395
- * Without it, the serverless build is used.
396
- *
397
- * @example
398
- * // In Node.js, the legacy build of `pdfjs-dist` (install it first)
399
- * import { definePDFJSModule } from 'unpdf'
400
- *
401
- * await definePDFJSModule(() => import('pdfjs-dist/legacy/build/pdf.mjs'))
402
- */
403
- async function definePDFJSModule(pdfjs) {
404
- await resolvePDFJSImport(pdfjs, { reload: true });
405
- }
406
- /** @deprecated Use `definePDFJSModule` instead. Will be removed in v2. */
407
- async function configureUnPDF(options) {
408
- await resolvePDFJSImport(options.pdfjs, { reload: true });
409
- }
410
- //#endregion
411
- //#region src/index.ts
412
- const getMeta = async (...args) => {
413
- await resolvePDFJSImport();
414
- return await getMeta$1(...args);
415
- };
416
- const extractText = async (...args) => {
417
- await resolvePDFJSImport();
418
- return await extractText$1(...args);
419
- };
420
- const extractTextItems = async (...args) => {
421
- await resolvePDFJSImport();
422
- return await extractTextItems$1(...args);
423
- };
424
- const extractImages = async (...args) => {
425
- await resolvePDFJSImport();
426
- return await extractImages$1(...args);
427
- };
428
- const renderPageAsImage = async (...args) => {
429
- await resolvePDFJSImport();
430
- return await renderPageAsImage$1(...args);
431
- };
432
- const extractLinks = async (...args) => {
433
- await resolvePDFJSImport();
434
- return await extractLinks$1(...args);
435
- };
436
- //#endregion
437
- export { configureUnPDF, createIsomorphicCanvasFactory, definePDFJSModule, extractImages, extractLinks, extractText, extractTextItems, getDocumentProxy, getMeta, getResolvedPDFJS, renderPageAsImage, resolvePDFJSImport };
663
+ export { definePDFJSModule, extractImages, extractLinks, extractText, extractTextItems, getDocumentProxy, getMeta, getResolvedPDFJS, inspectPages, renderPageAsImage };