pdfium-native 0.7.0 → 0.9.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +324 -4
  3. package/dist/document.d.ts +43 -2
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +49 -6
  6. package/dist/document.js.map +1 -1
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +9 -0
  9. package/dist/errors.js.map +1 -1
  10. package/dist/index.d.ts +60 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +55 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/page.d.ts +35 -1
  15. package/dist/page.d.ts.map +1 -1
  16. package/dist/page.js +51 -0
  17. package/dist/page.js.map +1 -1
  18. package/dist/types.d.ts +255 -0
  19. package/dist/types.d.ts.map +1 -1
  20. package/dist/validate.d.ts +14 -0
  21. package/dist/validate.d.ts.map +1 -0
  22. package/dist/validate.js +16 -0
  23. package/dist/validate.js.map +1 -0
  24. package/lib/document.ts +80 -7
  25. package/lib/errors.ts +10 -0
  26. package/lib/index.ts +159 -0
  27. package/lib/page.ts +80 -0
  28. package/lib/types.ts +280 -0
  29. package/lib/validate.ts +15 -0
  30. package/package.json +1 -1
  31. package/scripts/generate-fixtures.mjs +310 -0
  32. package/scripts/prebuilds.json +10 -10
  33. package/src/annotations_worker.h +111 -0
  34. package/src/assemble_worker.h +235 -0
  35. package/src/attachments_worker.h +44 -45
  36. package/src/attachments_write_worker.h +158 -0
  37. package/src/characters_worker.h +197 -0
  38. package/src/destinations_worker.h +160 -0
  39. package/src/document.h +86 -0
  40. package/src/document_io.h +78 -0
  41. package/src/flatten_worker.h +133 -0
  42. package/src/javascript_worker.h +105 -0
  43. package/src/napi_helpers.h +55 -0
  44. package/src/page.h +82 -0
  45. package/src/pdfium_addon.cc +310 -0
  46. package/src/signatures_worker.h +248 -0
  47. package/src/split_merge_worker.h +2 -93
  48. package/src/structtree_worker.h +164 -0
package/CHANGELOG.md CHANGED
@@ -6,6 +6,45 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.9.0] - 2026-08-07
10
+
11
+ ### Added
12
+
13
+ - Digital signature inspection on `PDFiumDocument`: `getSignatures()` lists every signature with its encoding (`/SubFilter`), reason, signing time, DocMDP certification level and the `/ByteRange` its digest covers, and `getSignatureContents(index, options?)` returns the raw PKCS#1 / PKCS#7 blob as a `Buffer` (or writes it to `options.output`). Wraps PDFium's `fpdf_signature.h`. Nothing is cryptographically verified — PDFium performs no verification, so these report what the signature dictionary declares; pass the blob and `byteRange` to a crypto library to actually validate. This closes the gap where `metadata.signatureCount` could detect signatures but nothing could inspect them.
14
+ - Positioned text extraction on `PDFiumPage`: `getCharacters(options?)` returns every character with its tight bounding box, baseline origin, font name/size/weight/flags and rotation. Character indices line up with `getText()` and `search()` results, so a match maps straight back to page coordinates. `options.start` / `options.count` page through dense pages instead of materialising tens of thousands of objects. Two PDFium behaviours are surfaced rather than hidden: `isGenerated` marks the line breaks and spaces PDFium synthesizes between text runs (they carry no real font), and `angle` runs clockwise — text rotated 45° counterclockwise reports `2π − π/4`, not `π/4`.
15
+ - `assemblePages(input, pages, options?)` builds a new PDF from selected source pages, in the order given. Unlike `splitDocument`, which only cuts a document into consecutive runs, the index list is taken literally: pages may be reordered, omitted, or repeated.
16
+ - `nUpPages(input, options)` imposes `columns × rows` source pages onto each output sheet. The sheet defaults to the size of the first source page, so a 2×2 n-up of A4 lands on A4.
17
+ - `getJavaScriptActions()` on `PDFiumDocument` lists the document-level scripts a viewer runs on open, for inspection and triage of untrusted files. Nothing is executed — the bundled PDFium is built with V8 disabled, so scripts are returned as inert text.
18
+ - `getNamedDestinations()` on `PDFiumDocument` lists the anchors that GoTo actions and external links target by name, resolving each to a page index, fit type and view parameters. Reads both the modern `/Names /Dests` name tree and the legacy `/Dests` catalog dictionary.
19
+ - `addAttachments(input, attachments, options?)` embeds files into a copy of a document — the library's first write path. **It cannot produce a conformant PDF/A-3 e-invoice:** PDFium's write API reaches only the file name, the bytes and the `/Params` dates, not `/Subtype` (MIME type), `/Desc`, `/AFRelationship`, the catalog `/AF` array, an OutputIntent or XMP. `AttachmentInput` therefore has no `mimeType` or `description` field rather than accepting those values and dropping them silently. Reading e-invoices back remains fully supported.
20
+ - `getStructTree()` on `PDFiumPage` returns the tagged-PDF structure tree — the logical outline (headings, paragraphs, tables, figures) that screen readers follow — with alternate text, actual text, per-element language and marked content IDs. `metadata.isTagged` already reported whether a document had one; now it can be read. Recursion is capped like the bookmark walker so a cyclic document cannot overflow the stack.
21
+ - `flattenDocument(input, options?)` merges annotations and form widgets into the page content and removes them, with per-page selection and the display/print appearance distinction. It bakes in the appearance streams a document already carries rather than regenerating them, which is correct for any PDF whose widgets have valid `/AP` entries; a form flagged `/NeedAppearances` is the uncovered case.
22
+ - New exported types: `Signature`, `GetSignatureContentsOptions`, `TextCharacter`, `GetCharactersOptions`, `AssemblePagesOptions`, `NUpPagesOptions`, `JavaScriptAction`, `NamedDestination`, `DestinationView`, `AttachmentInput`, `AddAttachmentsOptions`, `StructElement`, `FlattenDocumentOptions`.
23
+
24
+ ### Documented
25
+
26
+ - A README "Not supported" section now states the deliberate gaps up front: interactive form filling (PDFium's `FPDF_FORMFILLINFO` is a UI event-loop API that does not map onto a stateless promise library, and writing `/V` directly yields PDFs whose appearance contradicts their value), producing PDF/A-3 e-invoices, signature verification, XMP metadata and JavaScript execution.
27
+ - `getAttachment()` notes a PDFium reading quirk: an embedded file that decodes to _zero_ bytes comes back as its raw compressed stream, because PDFium treats "decoded to empty" as a decode failure and falls back to the undecoded bytes.
28
+
29
+ ### Fixed
30
+
31
+ - Native error messages containing a colon are no longer truncated. `parseNativeError` treated everything before the first colon as an error code, so `splitDocument`'s `"Split index out of range: 5"` reached the caller as code `"Split index out of range"` with message `" 5"` — the useful half discarded. Only the fixed set of PDFium error codes (`FILE`, `FORMAT`, `PASSWORD`, `SECURITY`, `PAGE`, `UNKNOWN`) is stripped now; every other message is passed through whole. This affected `splitDocument`, `mergeDocuments` and any file-output path since 0.5.0.
32
+
33
+ ### Changed
34
+
35
+ - Internal: `VectorFileWrite`, `SaveDocument` and `LoadDoc` moved from `split_merge_worker.h` into a shared `document_io.h`, and the byte-writing helper moved from `attachments_worker.h` into `napi_helpers.h` as `WriteBytesToFile`. No public API change.
36
+
37
+ ## [0.8.0] - 2026-08-06
38
+
39
+ ### Added
40
+
41
+ - File-attachment annotation extraction on `PDFiumPage`: `getAnnotationAttachment(index, options?)` reads the embedded file of a page-level `/FileAttachment` (paperclip) annotation as a `Buffer` (or writes it to `options.output`), wrapping PDFium's `FPDFAnnot_GetFileAttachment` / `FPDFAttachment_GetFile`. This complements the document-level `getAttachment()`: file-attachment annotations live on a page, not in the `/EmbeddedFiles` name tree, so the two cover the two distinct ways PDFium exposes attached files.
42
+ - `Annotation` objects now include `index` (the 0-based page annotation index, used to address `getAnnotationAttachment`) and, for `'fileattachment'` annotations, `fileName` (the embedded file's name).
43
+
44
+ ### Fixed
45
+
46
+ - `document.getAttachment(index)` (added in 0.7.0) and `page.getAnnotationAttachment(index)` now reject indices outside the signed 32-bit range instead of letting them through. The previous `Number.isInteger` guard missed large integers (e.g. `2**32 + 1`), which the native `ToInt32` coercion would silently wrap onto a valid — but different — entry, resolving with the wrong file instead of erroring. Both indices are now validated with a shared 32-bit-aware check.
47
+
9
48
  ## [0.7.0] - 2026-08-05
10
49
 
11
50
  ### Added
@@ -293,7 +332,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
293
332
  - GitHub Actions publish workflow with test gate
294
333
  - TypeScript type declarations for JS consumers
295
334
 
296
- [Unreleased]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.7.0...HEAD
335
+ [Unreleased]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.9.0...HEAD
336
+ [0.9.0]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.8.0...v0.9.0
337
+ [0.8.0]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.7.0...v0.8.0
297
338
  [0.7.0]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.6.1...v0.7.0
298
339
  [0.6.1]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.6.0...v0.6.1
299
340
  [0.6.0]: https://github.com/xonaman/nodejs-pdfium-native/compare/v0.5.6...v0.6.0
package/README.md CHANGED
@@ -49,8 +49,12 @@ doc.destroy();
49
49
  - 🖼️ Generate thumbnails and previews for uploaded PDFs
50
50
  - 📄 Extract searchable text from documents at scale
51
51
  - ⚙️ Build server-side PDF processing pipelines
52
- - ✂️ Split PDFs by page range or merge multiple PDFs into one
52
+ - ✂️ Split, merge, reorder, or impose PDFs — including n-up handout layouts
53
53
  - 🔗 Read annotations, bookmarks, links, and form fields from existing PDFs
54
+ - 📐 Map extracted text back to page coordinates for redaction or layout analysis
55
+ - ✍️ Inspect digital signatures and document-level JavaScript before trusting a file
56
+ - ♿ Audit tagged-PDF structure and alternate text for accessibility
57
+ - 🗄️ Flatten filled forms for archiving
54
58
 
55
59
  ### 📊 How it compares
56
60
 
@@ -58,14 +62,17 @@ doc.destroy();
58
62
  | --------------- | -------------------- | ------------------- | ----------------- |
59
63
  | Engine | PDFium (C++ addon) | PDFium (WASM) | pdf.js (JS) |
60
64
  | Rendering | ✅ JPEG/PNG built-in | ⚠️ Raw bitmap (BYO) | ⚠️ Canvas/browser |
61
- | Text extraction | ✅ | ❌ | ✅ |
65
+ | Text extraction | ✅ Plain + per-char | ❌ | ✅ |
62
66
  | Search | ✅ With rects | ❌ | ⚠️ Manual |
63
- | Split / Merge | ✅ | ❌ | ❌ |
67
+ | Split / Merge | ✅ + reorder / n-up | ❌ | ❌ |
68
+ | Signatures | ✅ Metadata + blob | ❌ | ⚠️ Partial |
69
+ | Struct tree | ✅ | ❌ | ✅ |
70
+ | Flatten | ✅ | ❌ | ❌ |
64
71
  | Annotations | ✅ | ❌ | ⚠️ Partial |
65
72
  | Bookmarks | ✅ | ❌ | ✅ |
66
73
  | Links | ✅ | ❌ | ✅ |
67
74
  | Form fields | ✅ | ❌ | ✅ |
68
- | Attachments | ✅ Embedded files | ❌ | ✅ |
75
+ | Attachments | ✅ Files + annots | ❌ | ✅ |
69
76
  | Async I/O | ✅ libuv workers | ❌ Sync | ❌ Main thread |
70
77
  | Platforms | macOS/Linux/Windows | Any (WASM) | Any |
71
78
 
@@ -79,9 +86,14 @@ doc.destroy();
79
86
  - [loadDocument](#loaddocumentinput-password)
80
87
  - [splitDocument](#splitdocumentinput-splitat-options)
81
88
  - [mergeDocuments](#mergedocumentsinputs-options)
89
+ - [assemblePages](#assemblepagesinput-pages-options)
90
+ - [nUpPages](#nuppagesinput-options)
91
+ - [addAttachments](#addattachmentsinput-attachments-options)
92
+ - [flattenDocument](#flattendocumentinput-options)
82
93
  - [PDFiumDocument](#pdfiumdocument)
83
94
  - [PDFiumPage](#pdfiumpage)
84
95
  - [DocumentMetadata](#documentmetadata)
96
+ - [Not supported](#-not-supported)
85
97
  - [Concurrency](#️-concurrency)
86
98
  - [Memory Management](#-memory-management)
87
99
  - [License](#-license)
@@ -177,6 +189,126 @@ await mergeDocuments(['a.pdf', 'b.pdf'], { output: 'merged.pdf' });
177
189
 
178
190
  ---
179
191
 
192
+ ### `assemblePages(input, pages, options?)`
193
+
194
+ Builds a new PDF from selected pages of `input`, in the order given. Returns `Promise<Buffer>`, or `Promise<void>` when `options.output` is set.
195
+
196
+ Where [`splitDocument`](#splitdocumentinput-splitat-options) only cuts a document into consecutive runs, the index list here is taken literally: pages may be reordered, left out, or repeated.
197
+
198
+ ```typescript
199
+ import { assemblePages } from 'pdfium-native';
200
+
201
+ // reverse a four-page document
202
+ const reversed = await assemblePages('doc.pdf', [3, 2, 1, 0]);
203
+
204
+ // pull out one page
205
+ await assemblePages('doc.pdf', [2], { output: 'page3.pdf' });
206
+
207
+ // repeat a page — e.g. a cover sheet before each section
208
+ const buf = await assemblePages('doc.pdf', [0, 1, 0, 2]);
209
+ ```
210
+
211
+ | Option | Type | Default | Description |
212
+ | ---------- | -------- | ------- | ------------------------------------------------------ |
213
+ | `output` | `string` | — | Write to this file path instead of returning a Buffer. |
214
+ | `password` | `string` | — | Password for the source PDF, if encrypted. |
215
+
216
+ Rejects if any index is outside `0 … pageCount - 1`, naming the offending index.
217
+
218
+ ---
219
+
220
+ ### `nUpPages(input, options)`
221
+
222
+ Imposes `columns × rows` source pages onto each page of a new document — the classic "n-up" layout for handouts and proof sheets. Returns `Promise<Buffer>`, or `Promise<void>` when `options.output` is set.
223
+
224
+ ```typescript
225
+ import { nUpPages } from 'pdfium-native';
226
+
227
+ // four source pages per sheet, sheet size taken from the first source page
228
+ const handout = await nUpPages('slides.pdf', { columns: 2, rows: 2 });
229
+
230
+ // two-up on landscape A4
231
+ await nUpPages('doc.pdf', {
232
+ columns: 2,
233
+ rows: 1,
234
+ width: 842,
235
+ height: 595,
236
+ output: 'twoup.pdf',
237
+ });
238
+ ```
239
+
240
+ | Option | Type | Default | Description |
241
+ | ---------- | -------- | ----------------- | ------------------------------------------------------ |
242
+ | `columns` | `number` | — (required) | Source pages placed side by side across each sheet. |
243
+ | `rows` | `number` | — (required) | Source pages stacked down each sheet. |
244
+ | `width` | `number` | first source page | Output sheet width in points. |
245
+ | `height` | `number` | first source page | Output sheet height in points. |
246
+ | `output` | `string` | — | Write to this file path instead of returning a Buffer. |
247
+ | `password` | `string` | — | Password for the source PDF, if encrypted. |
248
+
249
+ The sheet defaults to the size of the first source page, so a 2×2 n-up of A4 pages lands on A4 with each source page scaled to a quarter. Partial sheets are allowed: 4 pages at 3 per sheet produce 2 sheets.
250
+
251
+ ---
252
+
253
+ ### `addAttachments(input, attachments, options?)`
254
+
255
+ Embeds files into a copy of `input`. Returns `Promise<Buffer>`, or `Promise<void>` when `options.output` is set.
256
+
257
+ > **This does not produce a conformant PDF/A-3 e-invoice.** PDFium's write API reaches only the file name, the bytes and the `/Params` dates. It cannot set the MIME type (`/Subtype`), the description (`/Desc`), the `/AFRelationship` that marks an attachment as the invoice source, the catalog `/AF` array, an OutputIntent, or the XMP metadata — all of which ZUGFeRD, Factur-X and XRechnung require. Use a PDF/A toolchain to _produce_ e-invoices. _Reading_ them is fully supported by [`getAttachments()`](#getattachments).
258
+
259
+ ```typescript
260
+ import { addAttachments } from 'pdfium-native';
261
+
262
+ const pdf = await addAttachments('report.pdf', [
263
+ { name: 'data.csv', data: csvBuffer },
264
+ { name: 'notes.txt', data: Buffer.from('...'), creationDate: 'D:20250101120000Z' },
265
+ ]);
266
+ ```
267
+
268
+ ```typescript
269
+ interface AttachmentInput {
270
+ name: string; // must be non-empty and not already in the document
271
+ data: Buffer;
272
+ creationDate?: string; // PDF date string; defaults to now
273
+ modDate?: string;
274
+ }
275
+ ```
276
+
277
+ | Option | Type | Default | Description |
278
+ | ---------- | -------- | ------- | ------------------------------------------------------ |
279
+ | `output` | `string` | — | Write to this file path instead of returning a Buffer. |
280
+ | `password` | `string` | — | Password for the source PDF, if encrypted. |
281
+
282
+ Rejects on an empty or duplicate file name.
283
+
284
+ ---
285
+
286
+ ### `flattenDocument(input, options?)`
287
+
288
+ Merges annotations and form widgets into the page content and removes them. Returns `Promise<Buffer>`, or `Promise<void>` when `options.output` is set.
289
+
290
+ The result renders identically in every viewer but is no longer interactive — which is the point when archiving, or handing a filled form to a system that ignores annotations.
291
+
292
+ ```typescript
293
+ import { flattenDocument } from 'pdfium-native';
294
+
295
+ const archived = await flattenDocument('filled-form.pdf');
296
+
297
+ // print appearances, first page only
298
+ await flattenDocument('doc.pdf', { usage: 'print', pages: [0], output: 'out.pdf' });
299
+ ```
300
+
301
+ | Option | Type | Default | Description |
302
+ | ---------- | ---------- | ----------- | ------------------------------------------------------- |
303
+ | `usage` | `string` | `'display'` | `'display'` or `'print'` — which appearance to bake in. |
304
+ | `pages` | `number[]` | all pages | Only flatten these page indices. |
305
+ | `output` | `string` | — | Write to this file path instead of returning a Buffer. |
306
+ | `password` | `string` | — | Password for the source PDF, if encrypted. |
307
+
308
+ This bakes in the appearance streams the document already carries rather than regenerating them. That is correct for any PDF whose widgets have valid `/AP` entries — what every mainstream producer writes. A form flagged `/NeedAppearances`, which asks the viewer to regenerate appearances itself, is the case this cannot help with. Interactive form _filling_ is not supported; see [Not supported](#-not-supported).
309
+
310
+ ---
311
+
180
312
  ### PDFiumDocument
181
313
 
182
314
  | Property | Type | Description |
@@ -257,6 +389,90 @@ doc.destroy();
257
389
 
258
390
  Rejects if `index` is out of range (`0 … attachmentCount - 1`). `metadata.attachmentCount` gives the count without loading anything.
259
391
 
392
+ #### `getSignatures()`
393
+
394
+ Lists every digital signature in the document. Returns `Promise<Signature[]>`.
395
+
396
+ Nothing here is cryptographically verified — PDFium does not do that. These values are what the signature dictionary _declares_, so a well-formed entry proves only that the document claims to be signed.
397
+
398
+ ```typescript
399
+ interface Signature {
400
+ index: number; // 0-based index in the AcroForm field list
401
+ subFilter: string; // encoding, e.g. 'adbe.pkcs7.detached', 'ETSI.CAdES.detached'
402
+ reason?: string; // /Reason, if given
403
+ time?: string; // /M as a PDF date string, e.g. "D:20250101120000+01'00'"
404
+ docMdpPermission?: 1 | 2 | 3; // certification level; absent for ordinary signatures
405
+ byteRange: number[]; // flat (offset, length) pairs covered by the digest
406
+ contentsLength: number; // size of /Contents in bytes
407
+ }
408
+ ```
409
+
410
+ ```typescript
411
+ const doc = await loadDocument('contract.pdf');
412
+
413
+ for (const sig of await doc.getSignatures()) {
414
+ // A signature covers the whole file only if its last range ends at the file
415
+ // size. Anything less means content was appended after signing.
416
+ const end = sig.byteRange.at(-2)! + sig.byteRange.at(-1)!;
417
+ console.log(sig.subFilter, sig.reason, 'covers', end, 'bytes');
418
+ }
419
+ ```
420
+
421
+ `metadata.signatureCount` gives the count without listing anything.
422
+
423
+ #### `getSignatureContents(index, options?)`
424
+
425
+ Reads the raw `/Contents` bytes of the signature at `index` — a DER-encoded PKCS#1 or PKCS#7 binary. Returns `Promise<Buffer>`, or `Promise<void>` when `options.output` is a file path.
426
+
427
+ Pass this, together with the `byteRange` from `getSignatures()`, to a crypto library to actually validate the signature.
428
+
429
+ #### `getJavaScriptActions()`
430
+
431
+ Lists the document-level scripts a viewer runs when the document opens. Returns `Promise<JavaScriptAction[]>`.
432
+
433
+ Nothing is executed — the bundled PDFium is built with V8 disabled, so scripts come back as inert text. This is for inspection and triage.
434
+
435
+ ```typescript
436
+ interface JavaScriptAction {
437
+ index: number;
438
+ name: string; // entry name in the /Names /JavaScript tree
439
+ script: string; // the script source, as text
440
+ }
441
+ ```
442
+
443
+ ```typescript
444
+ const doc = await loadDocument('untrusted.pdf');
445
+ const scripts = await doc.getJavaScriptActions();
446
+ if (scripts.length > 0) {
447
+ console.warn(`${scripts.length} document-open script(s) — review before rendering`);
448
+ }
449
+ ```
450
+
451
+ #### `getNamedDestinations()`
452
+
453
+ Lists the document's named destinations — the anchors that GoTo actions and external links target by name rather than by page number. Returns `Promise<NamedDestination[]>`.
454
+
455
+ Both storage forms are read: the modern `/Names /Dests` name tree and the legacy `/Dests` catalog dictionary.
456
+
457
+ ```typescript
458
+ interface NamedDestination {
459
+ name: string; // e.g. 'Chapter2'
460
+ pageIndex?: number; // resolved target page
461
+ view: 'xyz' | 'fit' | 'fitH' | 'fitV' | 'fitR' | 'fitB' | 'fitBH' | 'fitBV' | 'unknown';
462
+ viewParams: number[]; // up to 4 numbers; meaning depends on `view`
463
+ destX?: number; // 'xyz' destinations only
464
+ destY?: number;
465
+ destZoom?: number;
466
+ }
467
+ ```
468
+
469
+ ```typescript
470
+ // Resolve "document.pdf#Chapter2" to a page index without walking every link.
471
+ const doc = await loadDocument('document.pdf');
472
+ const target = (await doc.getNamedDestinations()).find((d) => d.name === 'Chapter2');
473
+ console.log(target?.pageIndex);
474
+ ```
475
+
260
476
  #### `destroy()`
261
477
 
262
478
  Closes the document and frees all native resources. Must be called when done.
@@ -281,6 +497,77 @@ Closes the document and frees all native resources. Must be called when done.
281
497
 
282
498
  Extracts all text from the page. Returns `Promise<string>`.
283
499
 
500
+ #### `getCharacters(options?)`
501
+
502
+ Extracts every character with the geometry `getText()` throws away — bounding box, baseline origin, font and rotation. Returns `Promise<TextCharacter[]>`.
503
+
504
+ Character indices line up with `getText()` and with [`search()`](#searchtext-options) results, so a match maps straight back to page coordinates.
505
+
506
+ ```typescript
507
+ interface TextCharacter {
508
+ index: number; // 0-based, matches the offset in getText()
509
+ char: string; // '' when the glyph has no Unicode mapping
510
+ unicode: number;
511
+ bounds?: PageObjectBounds; // tight box around the glyph's ink
512
+ x?: number; // baseline origin
513
+ y?: number;
514
+ fontSize: number;
515
+ fontName: string; // e.g. 'Helvetica-Bold'
516
+ fontFlags: number;
517
+ fontWeight?: number;
518
+ angle: number; // radians, [0, 2π) — see the note below
519
+ isGenerated: boolean;
520
+ isHyphen: boolean;
521
+ hasUnicodeMapError: boolean;
522
+ }
523
+ ```
524
+
525
+ ```typescript
526
+ const page = await doc.getPage(0);
527
+
528
+ // Where on the page is the total?
529
+ const chars = await page.getCharacters();
530
+ const [match] = await page.search('Total');
531
+ const box = chars[match.charIndex].bounds;
532
+
533
+ // Dense pages can hold tens of thousands of characters — page through instead
534
+ // of materialising all of them at once.
535
+ const firstThousand = await page.getCharacters({ start: 0, count: 1000 });
536
+ ```
537
+
538
+ Two PDFium behaviours worth knowing:
539
+
540
+ - **`isGenerated`** marks characters PDFium synthesized rather than read from the content stream — line breaks between text runs, and spaces inferred from glyph spacing. They carry no real font, so `fontName` is `''`, `fontSize` is `1` and `fontWeight` is absent.
541
+ - **`angle` runs clockwise.** PDFium derives it as `atan2(c, a)` from the text matrix, so text rotated 45° _counterclockwise_ on the page reports ≈ `5.4978` (2π − π/4), not ≈ `0.7854`.
542
+
543
+ #### `getStructTree()`
544
+
545
+ Returns the tagged-PDF structure tree for this page — the logical outline (headings, paragraphs, tables, figures) that screen readers follow, and where alternate text lives. Returns `Promise<StructElement[]>`.
546
+
547
+ The tree is per-page: these are the elements whose content is on this page, not the whole document's tree. Returns an empty array for an untagged page; `metadata.isTagged` says up front whether there is anything to find.
548
+
549
+ ```typescript
550
+ interface StructElement {
551
+ type: string; // /S, e.g. 'H1', 'P', 'Table', 'Figure'
552
+ objType?: string; // /Type, normally 'StructElem'
553
+ title?: string; // /T
554
+ altText?: string; // /Alt — the accessibility description
555
+ actualText?: string; // /ActualText
556
+ id?: string; // /ID
557
+ lang?: string; // /Lang override for this subtree
558
+ markedContentId?: number;
559
+ children?: StructElement[];
560
+ }
561
+ ```
562
+
563
+ ```typescript
564
+ // Accessibility check: which figures are missing alternate text?
565
+ const walk = (nodes: StructElement[]): StructElement[] =>
566
+ nodes.flatMap((n) => [n, ...walk(n.children ?? [])]);
567
+
568
+ const missing = walk(await page.getStructTree()).filter((n) => n.type === 'Figure' && !n.altText);
569
+ ```
570
+
284
571
  #### `render(options?)`
285
572
 
286
573
  Renders the page to an encoded image. Returns `Promise<Buffer>`, or `Promise<void>` when `output` is specified.
@@ -390,7 +677,9 @@ Returns all annotations on the page. Returns `Promise<Annotation[]>`.
390
677
 
391
678
  ```typescript
392
679
  interface Annotation {
680
+ index: number; // 0-based annotation index on the page
393
681
  type: 'text' | 'link' | 'highlight' | 'underline' | 'strikeout' | /* ... */ 'unknown';
682
+ fileName?: string; // embedded file name (fileattachment annotations only)
394
683
  bounds?: { left; bottom; right; top };
395
684
  contents: string;
396
685
  color: { r; g; b; a } | null;
@@ -405,6 +694,25 @@ interface Annotation {
405
694
  }
406
695
  ```
407
696
 
697
+ #### `getAnnotationAttachment(index, options?)`
698
+
699
+ Reads the embedded file of the `'fileattachment'` (paperclip) annotation at `index` — the annotation's `index` from [`getAnnotations()`](#getannotations). Returns a `Promise<Buffer>`, or writes to a file and returns `Promise<void>` when `output` is given.
700
+
701
+ This is the **page-level** counterpart to the document-level [`getAttachment(index)`](#getattachmentindex-options): file-attachment annotations live on a page, not in the `/EmbeddedFiles` name tree, so ZUGFeRD / Factur-X e-invoice XML (a document-level embedded file) is read with `document.getAttachment`, not this method.
702
+
703
+ Rejects if the annotation at `index` is not a file attachment or carries no embedded file.
704
+
705
+ ```typescript
706
+ const annotations = await page.getAnnotations();
707
+ for (const annot of annotations) {
708
+ if (annot.type === 'fileattachment') {
709
+ const bytes = await page.getAnnotationAttachment(annot.index); // Buffer of exact embedded bytes
710
+ // ...or write straight to disk:
711
+ await page.getAnnotationAttachment(annot.index, { output: annot.fileName ?? 'attachment.bin' });
712
+ }
713
+ }
714
+ ```
715
+
408
716
  #### `getFormFields()`
409
717
 
410
718
  Returns all form fields on the page. Returns `Promise<FormField[]>`.
@@ -482,6 +790,18 @@ interface DocumentMetadata {
482
790
 
483
791
  ---
484
792
 
793
+ ## 🚧 Not supported
794
+
795
+ Deliberate gaps, so you know where the edges are before you hit them:
796
+
797
+ - **Interactive form filling.** Setting field values programmatically is not offered. PDFium's `FPDF_FORMFILLINFO` is a UI event-loop API — timers, focus tracking, invalidation callbacks — with no meaningful mapping onto a stateless promise-based library, and the shortcut of writing `/V` directly yields PDFs whose rendered appearance contradicts their stored value. Reading fields ([`getFormFields()`](#getformfields)) and [flattening](#flattendocumentinput-options) them are supported.
798
+ - **Producing PDF/A-3 e-invoices.** [`addAttachments()`](#addattachmentsinput-attachments-options) embeds files but cannot set `/Subtype`, `/AFRelationship`, the catalog `/AF` array, an OutputIntent or XMP — all required by ZUGFeRD, Factur-X and XRechnung. Reading such invoices is fully supported.
799
+ - **Signature verification.** [`getSignatures()`](#getsignatures) reports what the signature dictionary declares; PDFium performs no cryptography. Pass the blob from [`getSignatureContents()`](#getsignaturecontentsindex-options) and its `byteRange` to a crypto library to actually validate.
800
+ - **XMP metadata.** Not reachable through PDFium's public API at all.
801
+ - **Executing JavaScript.** The bundled PDFium is built with V8 disabled. [`getJavaScriptActions()`](#getjavascriptactions) returns scripts as inert text.
802
+
803
+ One PDFium reading quirk worth knowing: an embedded file that decodes to _zero_ bytes comes back from [`getAttachment()`](#getattachmentindex-options) as its raw compressed stream, because PDFium treats "decoded to empty" as a decode failure and falls back to the undecoded bytes.
804
+
485
805
  ## ⚙️ Concurrency
486
806
 
487
807
  ### `concurrency(value?): number`
@@ -1,5 +1,5 @@
1
1
  import { PDFiumPage } from './page.js';
2
- import type { Attachment, Bookmark, DocumentMetadata, GetAttachmentOptions, NativeDocument } from './types.js';
2
+ import type { Attachment, Bookmark, DocumentMetadata, GetAttachmentOptions, GetSignatureContentsOptions, JavaScriptAction, NamedDestination, NativeDocument, Signature } from './types.js';
3
3
  /**
4
4
  * A loaded PDF document.
5
5
  */
@@ -32,7 +32,48 @@ export declare class PDFiumDocument {
32
32
  getAttachment(index: number, options: GetAttachmentOptions & {
33
33
  output: string;
34
34
  }): Promise<void>;
35
- /** Reads the raw bytes of the attachment at `index`. */
35
+ /**
36
+ * Reads the raw bytes of the attachment at `index`.
37
+ *
38
+ * One PDFium quirk to know about: an embedded file that decodes to *zero*
39
+ * bytes comes back as its raw compressed stream instead of as an empty
40
+ * buffer. PDFium treats "decoded to empty" as a decode failure and falls back
41
+ * to the undecoded bytes, so a zero-length FlateDecode attachment yields the
42
+ * 8-byte zlib envelope rather than nothing.
43
+ */
36
44
  getAttachment(index: number, options?: GetAttachmentOptions): Promise<Buffer>;
45
+ /**
46
+ * Returns metadata for every digital signature in the document — encoding,
47
+ * reason, signing time, certification level and the byte ranges the digest
48
+ * covers.
49
+ *
50
+ * Nothing is cryptographically verified: this reports what the PDF declares
51
+ * about itself. To actually validate a signature, read its blob with
52
+ * {@link getSignatureContents} and check it against `byteRange`.
53
+ */
54
+ getSignatures(): Promise<Signature[]>;
55
+ /** Writes the signature's /Contents bytes at `index` to a file path. */
56
+ getSignatureContents(index: number, options: GetSignatureContentsOptions & {
57
+ output: string;
58
+ }): Promise<void>;
59
+ /** Reads the raw /Contents bytes (PKCS#1 / PKCS#7 DER) of the signature at `index`. */
60
+ getSignatureContents(index: number, options?: GetSignatureContentsOptions): Promise<Buffer>;
61
+ /**
62
+ * Returns the document-level JavaScript actions — the scripts a viewer runs
63
+ * when the document opens.
64
+ *
65
+ * Useful for inspection and triage: a PDF from an untrusted source that
66
+ * carries document-open JavaScript is worth checking before rendering.
67
+ * Nothing here is executed; the scripts come back as inert text.
68
+ */
69
+ getJavaScriptActions(): Promise<JavaScriptAction[]>;
70
+ /**
71
+ * Returns the document's named destinations — the anchors that GoTo actions
72
+ * and external links target by name rather than by page number.
73
+ *
74
+ * This resolves a name like `Chapter2` to a concrete page index without
75
+ * walking every link on every page.
76
+ */
77
+ getNamedDestinations(): Promise<NamedDestination[]>;
37
78
  }
38
79
  //# sourceMappingURL=document.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../lib/document.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,KAAK,EACV,UAAU,EACV,QAAQ,EACR,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,EACf,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,qBAAa,cAAc;IAOb,OAAO,CAAC,MAAM;IAN1B,6BAA6B;IAC7B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,sDAAsD;IACtD,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IAEpC,gBAAgB;gBACI,MAAM,EAAE,cAAc;IAK1C,oCAAoC;IAC9B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAIjD,4EAA4E;IACrE,KAAK,IAAI,cAAc,CAAC,UAAU,CAAC;IAM1C,mDAAmD;IACnD,OAAO,IAAI,IAAI;IAIf,yCAAyC;IACzC,YAAY,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;IAInC;;;;;;;OAOG;IACH,cAAc,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;IAIvC,uDAAuD;IACvD,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,oB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AE,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC;IAe7E;;;;;;;;OAQG;IACH,aAAa,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAIrC,wEAAwE;IACxE,oBAAoB,CAClB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,2BAA2B,GAAG;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,GACxD,OAAO,CAAC,IAAI,CAAC;IAChB,uFAAuF;IACvF,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,2BAA2B,GAAG,OAAO,CAAC,MAAM,CAAC;IAe3F;;;;;;;OAOG;IACH,oBAAoB,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAInD;;;;;;OAMG;IACH,oBAAoB,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;CAGpD"}
package/dist/document.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { withConcurrency } from './concurrency.js';
2
2
  import { PDFiumPage } from './page.js';
3
+ import { isNativeIndex } from './validate.js';
3
4
  /**
4
5
  * A loaded PDF document.
5
6
  */
@@ -45,14 +46,56 @@ export class PDFiumDocument {
45
46
  return withConcurrency(() => this.native.getAttachments());
46
47
  }
47
48
  getAttachment(index, options) {
48
- // Guard non-integer indices here: the native layer coerces with ToInt32, so
49
- // a NaN/Infinity/fractional index (e.g. from `Number(userInput)`) would
50
- // otherwise silently alias onto a valid attachment and return the wrong
51
- // embedded file. Integer out-of-range is still handled natively.
52
- if (!Number.isInteger(index)) {
53
- return Promise.reject(new RangeError(`Attachment index must be an integer, got ${index}`));
49
+ // Reject indices the native ToInt32 coercion would silently alter (see
50
+ // isNativeIndex): a NaN/Infinity/fractional index (e.g. from
51
+ // `Number(userInput)`), or one outside the 32-bit range, must not wrap onto
52
+ // a valid, different attachment and return the wrong embedded file. In-range
53
+ // integer out-of-range is still reported natively.
54
+ if (!isNativeIndex(index)) {
55
+ return Promise.reject(new RangeError(`Attachment index must be a 32-bit integer, got ${index}`));
54
56
  }
55
57
  return withConcurrency(() => this.native.getAttachment(index, options?.output));
56
58
  }
59
+ /**
60
+ * Returns metadata for every digital signature in the document — encoding,
61
+ * reason, signing time, certification level and the byte ranges the digest
62
+ * covers.
63
+ *
64
+ * Nothing is cryptographically verified: this reports what the PDF declares
65
+ * about itself. To actually validate a signature, read its blob with
66
+ * {@link getSignatureContents} and check it against `byteRange`.
67
+ */
68
+ getSignatures() {
69
+ return withConcurrency(() => this.native.getSignatures());
70
+ }
71
+ getSignatureContents(index, options) {
72
+ // Same 32-bit guard as getAttachment: a fractional or out-of-range index
73
+ // must not ToInt32-wrap onto a different, valid signature.
74
+ if (!isNativeIndex(index)) {
75
+ return Promise.reject(new RangeError(`Signature index must be a 32-bit integer, got ${index}`));
76
+ }
77
+ return withConcurrency(() => this.native.getSignatureContents(index, options?.output));
78
+ }
79
+ /**
80
+ * Returns the document-level JavaScript actions — the scripts a viewer runs
81
+ * when the document opens.
82
+ *
83
+ * Useful for inspection and triage: a PDF from an untrusted source that
84
+ * carries document-open JavaScript is worth checking before rendering.
85
+ * Nothing here is executed; the scripts come back as inert text.
86
+ */
87
+ getJavaScriptActions() {
88
+ return withConcurrency(() => this.native.getJavaScriptActions());
89
+ }
90
+ /**
91
+ * Returns the document's named destinations — the anchors that GoTo actions
92
+ * and external links target by name rather than by page number.
93
+ *
94
+ * This resolves a name like `Chapter2` to a concrete page index without
95
+ * walking every link on every page.
96
+ */
97
+ getNamedDestinations() {
98
+ return withConcurrency(() => this.native.getNamedDestinations());
99
+ }
57
100
  }
58
101
  //# sourceMappingURL=document.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"document.js","sourceRoot":"","sources":["../lib/document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AASvC;;GAEG;AACH,MAAM,OAAO,cAAc;IAOL;IANpB,6BAA6B;IACpB,SAA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AAoB,EAAE,CAAC,CAAC;IACnE,CAAC;IAED;;;;;;OAMG;IACH,oBAAoB;QAClB,OAAO,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,oBAAoB,EAAE,CAAC,CAAC;IACnE,CAAC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../lib/errors.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,qBAAa,WAAY,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;gBACV,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAK1C;AAED,sDAAsD;AACtD,qBAAa,eAAgB,SAAQ,WAAW;gBAClC,OAAO,EAAE,MAAM;CAI5B;AAED,gEAAgE;AAChE,qBAAa,iBAAkB,SAAQ,WAAW;gBACpC,OAAO,EAAE,MAAM;CAI5B;AAED,uDAAuD;AACvD,qBAAa,mBAAoB,SAAQ,WAAW;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAED,+DAA+D;AAC/D,qBAAa,mBAAoB,SAAQ,WAAW;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,CAoB1D"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../lib/errors.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,qBAAa,WAAY,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;gBACV,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAK1C;AAED,sDAAsD;AACtD,qBAAa,eAAgB,SAAQ,WAAW;gBAClC,OAAO,EAAE,MAAM;CAI5B;AAED,gEAAgE;AAChE,qBAAa,iBAAkB,SAAQ,WAAW;gBACpC,OAAO,EAAE,MAAM;CAI5B;AAED,uDAAuD;AACvD,qBAAa,mBAAoB,SAAQ,WAAW;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAED,+DAA+D;AAC/D,qBAAa,mBAAoB,SAAQ,WAAW;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAUD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,CAsB1D"}
package/dist/errors.js CHANGED
@@ -35,12 +35,21 @@ export class PDFiumSecurityError extends PDFiumError {
35
35
  this.name = 'PDFiumSecurityError';
36
36
  }
37
37
  }
38
+ // The native layer tags PDFium's own failures with a "CODE:message" envelope
39
+ // (see GetPdfiumErrorMessage in src/napi_helpers.h). Everything else a worker
40
+ // reports is free text that routinely contains a colon of its own — "Page index
41
+ // out of range: 4", "Parent directory does not exist: /tmp/x" — so only a
42
+ // recognized code may be stripped off. Treating any prefix as a code would eat
43
+ // the useful half of those messages.
44
+ const NATIVE_ERROR_CODES = new Set(['FILE', 'FORMAT', 'PASSWORD', 'SECURITY', 'PAGE', 'UNKNOWN']);
38
45
  export function parseNativeError(err) {
39
46
  const msg = err instanceof Error ? err.message : String(err);
40
47
  const colonIdx = msg.indexOf(':');
41
48
  if (colonIdx === -1)
42
49
  return new PDFiumError('UNKNOWN', msg);
43
50
  const code = msg.slice(0, colonIdx);
51
+ if (!NATIVE_ERROR_CODES.has(code))
52
+ return new PDFiumError('UNKNOWN', msg);
44
53
  const text = msg.slice(colonIdx + 1);
45
54
  switch (code) {
46
55
  case 'FILE':
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../lib/errors.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC3B,IAAI,CAAS;IACtB,YAAY,IAAY,EAAE,OAAe;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,sDAAsD;AACtD,MAAM,OAAO,eAAgB,SAAQ,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