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/lib/types.ts CHANGED
@@ -140,6 +140,92 @@ export interface OtherPageObject extends BasePageObject {
140
140
 
141
141
  export type PageObject = TextPageObject | ImagePageObject | OtherPageObject;
142
142
 
143
+ /**
144
+ * A single character on a page, with the geometry `getText()` discards.
145
+ */
146
+ export interface TextCharacter {
147
+ /** 0-based index of this character in the page's text. */
148
+ index: number;
149
+ /**
150
+ * The character itself. Empty string when the glyph has no Unicode mapping —
151
+ * check `hasUnicodeMapError` before trusting it.
152
+ */
153
+ char: string;
154
+ /** Unicode code point, or 0 if the glyph has no mapping. */
155
+ unicode: number;
156
+ /**
157
+ * Tight bounding box in page points, hugging the glyph's ink. Absent if
158
+ * PDFium cannot determine it.
159
+ */
160
+ bounds?: PageObjectBounds;
161
+ /** X coordinate of the baseline origin in page points. Absent if unavailable. */
162
+ x?: number;
163
+ /** Y coordinate of the baseline origin in page points. Absent if unavailable. */
164
+ y?: number;
165
+ /** Font size in points (the typographic "em" size). */
166
+ fontSize: number;
167
+ /** PostScript name of the font (e.g. 'Helvetica-Bold'). Empty string if unavailable. */
168
+ fontName: string;
169
+ /** Raw PDF font descriptor flags bitmask (see PDF spec Table 123). */
170
+ fontFlags: number;
171
+ /** Font weight (e.g. 400 = normal, 700 = bold). Absent if unavailable. */
172
+ fontWeight?: number;
173
+ /**
174
+ * Rotation of the character in radians, normalized to `[0, 2π)`. 0 for
175
+ * upright text.
176
+ *
177
+ * Note the direction: PDFium derives this as `atan2(c, a)` from the text
178
+ * matrix, so it runs *clockwise*. Text rotated 45° counterclockwise on the
179
+ * page reports ≈ 5.4978 (2π − π/4), not ≈ 0.7854.
180
+ */
181
+ angle: number;
182
+ /**
183
+ * Whether PDFium synthesized this character rather than reading it from the
184
+ * content stream — line breaks between text runs, and spaces inferred from
185
+ * glyph spacing. Synthesized characters carry no real font, so `fontName` is
186
+ * empty, `fontSize` is 1 and `fontWeight` is absent. Useful when mapping text
187
+ * offsets back to the original PDF.
188
+ */
189
+ isGenerated: boolean;
190
+ /** Whether this character is a hyphen (relevant when de-hyphenating lines). */
191
+ isHyphen: boolean;
192
+ /** Whether the glyph has no reliable Unicode mapping, making `char` unreliable. */
193
+ hasUnicodeMapError: boolean;
194
+ }
195
+
196
+ /**
197
+ * A node in a tagged PDF's structure tree — the logical document outline
198
+ * (headings, paragraphs, tables, figures) behind the visual layout, which is
199
+ * what screen readers follow.
200
+ */
201
+ export interface StructElement {
202
+ /** Structure type (/S), e.g. 'H1', 'P', 'Table', 'Figure'. */
203
+ type: string;
204
+ /** Object type (/Type), normally 'StructElem'. Absent if not set. */
205
+ objType?: string;
206
+ /** Human-readable title (/T). Absent if not set. */
207
+ title?: string;
208
+ /** Alternate text (/Alt) — the accessibility description. Absent if not set. */
209
+ altText?: string;
210
+ /** Replacement text (/ActualText) for content whose glyphs differ from its meaning. */
211
+ actualText?: string;
212
+ /** Element identifier (/ID). Absent if not set. */
213
+ id?: string;
214
+ /** Language override (/Lang) for this subtree, e.g. 'de-DE'. Absent if not set. */
215
+ lang?: string;
216
+ /** Marked-content ID tying this element to page content. Absent if the element has none. */
217
+ markedContentId?: number;
218
+ /** Child elements. Absent when the element has no element children. */
219
+ children?: StructElement[];
220
+ }
221
+
222
+ export interface GetCharactersOptions {
223
+ /** First character index to return (default: 0). */
224
+ start?: number;
225
+ /** How many characters to return (default: all remaining). */
226
+ count?: number;
227
+ }
228
+
143
229
  export interface SearchOptions {
144
230
  /** Match case when searching (default: false). */
145
231
  caseSensitive?: boolean;
@@ -224,8 +310,19 @@ export interface QuadPoints {
224
310
  }
225
311
 
226
312
  export interface Annotation {
313
+ /**
314
+ * 0-based index of this annotation on the page. Pass it to
315
+ * {@link NativePage.getAnnotationAttachment} to read a file-attachment
316
+ * annotation's embedded bytes.
317
+ */
318
+ index: number;
227
319
  /** Annotation subtype (e.g. 'highlight', 'text', 'link'). */
228
320
  type: AnnotationType;
321
+ /**
322
+ * For `'fileattachment'` annotations: the embedded file's name
323
+ * (e.g. 'report.pdf'). Absent for other annotation types.
324
+ */
325
+ fileName?: string;
229
326
  /** Bounding box in page coordinates, if available. */
230
327
  bounds?: PageObjectBounds;
231
328
  /** Text contents of the annotation. */
@@ -402,6 +499,96 @@ export interface GetAttachmentOptions {
402
499
  output?: string;
403
500
  }
404
501
 
502
+ /**
503
+ * A digital signature as declared by the PDF.
504
+ *
505
+ * These values come straight from the signature dictionary — nothing here is
506
+ * cryptographically verified. A present, well-formed signature says only that
507
+ * the document *claims* to be signed.
508
+ */
509
+ export interface Signature {
510
+ /** 0-based index of the signature in the document's AcroForm field list. */
511
+ index: number;
512
+ /**
513
+ * Encoding of the signature value (/SubFilter), e.g. 'adbe.pkcs7.detached'
514
+ * or 'ETSI.CAdES.detached'. Empty string if the PDF omits it.
515
+ */
516
+ subFilter: string;
517
+ /** Reason given for signing (/Reason). Absent if not set. */
518
+ reason?: string;
519
+ /**
520
+ * Time of signing (/M) as a PDF date string (e.g. "D:20250101120000+01'00'").
521
+ * Absent if not set. For PKCS#7 signatures the authoritative time is usually
522
+ * inside the signature blob instead; use this only as a fallback.
523
+ */
524
+ time?: string;
525
+ /**
526
+ * Certification level for a DocMDP signature: 1 = no changes allowed,
527
+ * 2 = form fill-in and signing allowed, 3 = additionally annotations allowed.
528
+ * Absent for an ordinary (non-certifying) signature.
529
+ */
530
+ docMdpPermission?: 1 | 2 | 3;
531
+ /**
532
+ * The /ByteRange array covered by the signature digest: a flat list of
533
+ * (offset, length) pairs, exactly as stored in the PDF. A signature covers
534
+ * the whole file when the last pair ends at the file size — anything less
535
+ * means content was appended after signing.
536
+ */
537
+ byteRange: number[];
538
+ /**
539
+ * Size in bytes of the signature value (/Contents). Read the bytes
540
+ * themselves with {@link PDFiumDocument.getSignatureContents}.
541
+ */
542
+ contentsLength: number;
543
+ }
544
+
545
+ export interface GetSignatureContentsOptions {
546
+ /** Write the signature bytes to this file path instead of returning a Buffer. */
547
+ output?: string;
548
+ }
549
+
550
+ /**
551
+ * A document-level JavaScript action — a script a viewer runs when the
552
+ * document opens.
553
+ */
554
+ export interface JavaScriptAction {
555
+ /** 0-based index in the document's /Names /JavaScript tree. */
556
+ index: number;
557
+ /** Entry name in the JavaScript name tree. Empty string if unnamed. */
558
+ name: string;
559
+ /** The script source, returned as inert text. Empty string if unreadable. */
560
+ script: string;
561
+ }
562
+
563
+ /** How a viewer should frame the target page when following a destination. */
564
+ export type DestinationView =
565
+ 'xyz' | 'fit' | 'fitH' | 'fitV' | 'fitR' | 'fitB' | 'fitBH' | 'fitBV' | 'unknown';
566
+
567
+ /**
568
+ * A named destination — an anchor that GoTo actions and external links target
569
+ * by name instead of by page number.
570
+ */
571
+ export interface NamedDestination {
572
+ /** The destination's name, e.g. 'Chapter2'. */
573
+ name: string;
574
+ /** Target page index. Absent if the destination cannot be resolved to a page. */
575
+ pageIndex?: number;
576
+ /** Fit type declared by the destination. */
577
+ view: DestinationView;
578
+ /**
579
+ * Raw view parameters, up to four numbers whose meaning depends on `view` —
580
+ * for example `fitR` carries [left, bottom, right, top] and `fitH` a single
581
+ * top coordinate. Empty for `fit` and `fitB`, which take none.
582
+ */
583
+ viewParams: number[];
584
+ /** Destination X coordinate. Only set for `xyz` destinations that specify one. */
585
+ destX?: number;
586
+ /** Destination Y coordinate. Only set for `xyz` destinations that specify one. */
587
+ destY?: number;
588
+ /** Destination zoom level. Only set for `xyz` destinations that specify one. */
589
+ destZoom?: number;
590
+ }
591
+
405
592
  // native addon bindings (internal)
406
593
  export interface NativePage {
407
594
  readonly number: number;
@@ -414,13 +601,16 @@ export interface NativePage {
414
601
  readonly cropBox?: PageObjectBounds;
415
602
  readonly trimBox?: PageObjectBounds;
416
603
  getText(): Promise<string>;
604
+ getCharacters(start?: number, count?: number): Promise<TextCharacter[]>;
417
605
  render(options?: PageRenderOptions): Promise<Buffer | void>;
418
606
  getObject(index: number): Promise<PageObject>;
419
607
  renderImage(index: number, options?: ImageRenderOptions): Promise<Buffer | void>;
420
608
  getLinks(): Promise<Link[]>;
421
609
  search(text: string, options?: SearchOptions): Promise<SearchMatch[]>;
422
610
  getAnnotations(): Promise<Annotation[]>;
611
+ getAnnotationAttachment(index: number, outputPath?: string): Promise<Buffer | undefined>;
423
612
  getFormFields(): Promise<FormField[]>;
613
+ getStructTree(): Promise<StructElement[]>;
424
614
  close(): void;
425
615
  }
426
616
 
@@ -431,6 +621,10 @@ export interface NativeDocument {
431
621
  getBookmarks(): Promise<Bookmark[]>;
432
622
  getAttachments(): Promise<Attachment[]>;
433
623
  getAttachment(index: number, outputPath?: string): Promise<Buffer | undefined>;
624
+ getSignatures(): Promise<Signature[]>;
625
+ getSignatureContents(index: number, outputPath?: string): Promise<Buffer | undefined>;
626
+ getJavaScriptActions(): Promise<JavaScriptAction[]>;
627
+ getNamedDestinations(): Promise<NamedDestination[]>;
434
628
  destroy(): void;
435
629
  }
436
630
 
@@ -453,6 +647,77 @@ export interface MergeDocumentsOptions {
453
647
  output?: string;
454
648
  }
455
649
 
650
+ export interface AssemblePagesOptions {
651
+ /** Write to this file path instead of returning a Buffer. */
652
+ output?: string;
653
+ /** Password for the source PDF (if encrypted). */
654
+ password?: string;
655
+ }
656
+
657
+ /**
658
+ * A file to embed with {@link addAttachments}.
659
+ *
660
+ * There is deliberately no `mimeType` or `description` field. The MIME type is
661
+ * `/Subtype` on the embedded-file stream and the description is `/Desc` on the
662
+ * filespec dictionary; PDFium's write API reaches neither in the bundled build,
663
+ * and accepting those values only to drop them silently would be worse than not
664
+ * offering them. Note this is an asymmetry with reading: `Attachment.mimeType`
665
+ * is reported when a PDF already carries it.
666
+ */
667
+ export interface AttachmentInput {
668
+ /**
669
+ * File name to store in the /EmbeddedFiles name tree, e.g. 'report.xml'.
670
+ * Must be non-empty and not already present in the document.
671
+ */
672
+ name: string;
673
+ /** File contents. */
674
+ data: Buffer;
675
+ /**
676
+ * Creation date as a PDF date string, e.g. 'D:20250101120000Z'. Defaults to
677
+ * the current time, so set it explicitly for reproducible output.
678
+ */
679
+ creationDate?: string;
680
+ /** Modification date as a PDF date string. */
681
+ modDate?: string;
682
+ }
683
+
684
+ export interface AddAttachmentsOptions {
685
+ /** Write to this file path instead of returning a Buffer. */
686
+ output?: string;
687
+ /** Password for the source PDF (if encrypted). */
688
+ password?: string;
689
+ }
690
+
691
+ export interface FlattenDocumentOptions {
692
+ /**
693
+ * Which appearance to bake in: `'display'` (default) or `'print'`. They
694
+ * differ for annotations whose appearance dictionary distinguishes the two —
695
+ * a watermark marked print-only, for instance.
696
+ */
697
+ usage?: 'display' | 'print';
698
+ /** Only flatten these page indices. Defaults to every page. */
699
+ pages?: number[];
700
+ /** Write to this file path instead of returning a Buffer. */
701
+ output?: string;
702
+ /** Password for the source PDF (if encrypted). */
703
+ password?: string;
704
+ }
705
+
706
+ export interface NUpPagesOptions {
707
+ /** Number of source pages placed side by side across each output page. */
708
+ columns: number;
709
+ /** Number of source pages stacked down each output page. */
710
+ rows: number;
711
+ /** Output page width in points. Defaults to the width of the first source page. */
712
+ width?: number;
713
+ /** Output page height in points. Defaults to the height of the first source page. */
714
+ height?: number;
715
+ /** Write to this file path instead of returning a Buffer. */
716
+ output?: string;
717
+ /** Password for the source PDF (if encrypted). */
718
+ password?: string;
719
+ }
720
+
456
721
  export interface NativeAddon {
457
722
  loadDocument(input: Buffer | string, password?: string): Promise<NativeDocument>;
458
723
  splitDocument(
@@ -464,4 +729,19 @@ export interface NativeAddon {
464
729
  inputs: Array<Buffer | string | { input: Buffer | string; password?: string }>,
465
730
  options?: { output?: string },
466
731
  ): Promise<Buffer | undefined>;
732
+ assemblePages(
733
+ input: Buffer | string,
734
+ pages: number[],
735
+ options?: AssemblePagesOptions,
736
+ ): Promise<Buffer | undefined>;
737
+ nUpPages(input: Buffer | string, options: NUpPagesOptions): Promise<Buffer | undefined>;
738
+ addAttachments(
739
+ input: Buffer | string,
740
+ attachments: AttachmentInput[],
741
+ options?: AddAttachmentsOptions,
742
+ ): Promise<Buffer | undefined>;
743
+ flattenDocument(
744
+ input: Buffer | string,
745
+ options?: FlattenDocumentOptions,
746
+ ): Promise<Buffer | undefined>;
467
747
  }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Returns whether `index` is safe to pass to the native layer, which coerces
3
+ * arguments with ToInt32 (N-API `Int32Value`).
4
+ *
5
+ * `Number.isInteger` alone is insufficient: it is `true` for any integer up to
6
+ * 2^53, but ToInt32 truncates to the low 32 bits, so a value such as
7
+ * `2**32 + 1` would wrap to `1` and silently address a *different* — valid —
8
+ * entry with no error. Restricting to the signed 32-bit range means any value
9
+ * that passes is returned unchanged by ToInt32. In-range negatives are allowed
10
+ * through on purpose, so the native bounds check reports them as "out of
11
+ * range" (preserving that error contract).
12
+ */
13
+ export function isNativeIndex(index: number): boolean {
14
+ return Number.isInteger(index) && index >= -0x80000000 && index <= 0x7fffffff;
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pdfium-native",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Native Node.js bindings for PDFium",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -493,6 +493,310 @@ async function createEInvoicePdf() {
493
493
  return doc.save();
494
494
  }
495
495
 
496
+ // --- Tagged PDF with a real structure tree ---
497
+ // tagged.pdf only sets /MarkInfo, which is enough for metadata.isTagged but
498
+ // leaves nothing for getStructTree() to read. PDFium needs more than a
499
+ // /StructTreeRoot: CPDF_StructTree::LoadPageTree bails unless the root has a
500
+ // /ParentTree AND the page has /StructParents, then it looks up that key,
501
+ // expects an array of leaf element dicts, and walks /P upwards to rebuild the
502
+ // tree. All of that is assembled by hand below.
503
+ //
504
+ // The page content deliberately carries no BDC/EMC marked-content operators:
505
+ // PDFium reads the structure purely from the dictionaries, so the /K marked
506
+ // content IDs are enough to exercise the API.
507
+ async function createStructTreePdf() {
508
+ const doc = await PDFDocument.create();
509
+ const font = await doc.embedFont(StandardFonts.Helvetica);
510
+ const page = doc.addPage([300, 400]);
511
+ page.drawText('Main heading', { x: 50, y: 340, size: 18, font });
512
+ page.drawText('A paragraph of body text.', { x: 50, y: 300, size: 11, font });
513
+
514
+ const { PDFName, PDFString, PDFNumber } = await import('pdf-lib');
515
+
516
+ const structTreeRoot = doc.context.obj({ Type: 'StructTreeRoot' });
517
+ const structTreeRootRef = doc.context.register(structTreeRoot);
518
+
519
+ const documentElem = doc.context.obj({
520
+ Type: 'StructElem',
521
+ S: 'Document',
522
+ P: structTreeRootRef,
523
+ Lang: PDFString.of('en-US'),
524
+ });
525
+ const documentRef = doc.context.register(documentElem);
526
+
527
+ const child = (props) =>
528
+ doc.context.register(
529
+ doc.context.obj({
530
+ Type: 'StructElem',
531
+ P: documentRef,
532
+ Pg: page.ref,
533
+ ...props,
534
+ }),
535
+ );
536
+
537
+ const headingRef = child({ S: 'H1', T: PDFString.of('Main heading'), K: 0 });
538
+ const paragraphRef = child({ S: 'P', K: 1, Lang: PDFString.of('de-DE') });
539
+ const figureRef = child({
540
+ S: 'Figure',
541
+ K: 2,
542
+ Alt: PDFString.of('A red square'),
543
+ ActualText: PDFString.of('Figure 1'),
544
+ ID: PDFString.of('fig1'),
545
+ });
546
+
547
+ documentElem.set(PDFName.of('K'), doc.context.obj([headingRef, paragraphRef, figureRef]));
548
+ structTreeRoot.set(PDFName.of('K'), doc.context.obj([documentRef]));
549
+
550
+ // ParentTree: key 0 -> the leaf elements whose content sits on this page.
551
+ // PDFium walks each one's /P chain back up to the root.
552
+ structTreeRoot.set(
553
+ PDFName.of('ParentTree'),
554
+ doc.context.obj({
555
+ Nums: [0, [headingRef, paragraphRef, figureRef]],
556
+ }),
557
+ );
558
+
559
+ page.node.set(PDFName.of('StructParents'), PDFNumber.of(0));
560
+ doc.catalog.set(PDFName.of('StructTreeRoot'), structTreeRootRef);
561
+ doc.catalog.set(PDFName.of('MarkInfo'), doc.context.obj({ Marked: true }));
562
+
563
+ return doc.save();
564
+ }
565
+
566
+ // --- PDF with document-level JavaScript and named destinations ---
567
+ // pdf-lib builds neither, so both name trees are written by hand. The
568
+ // destinations deliberately use both storage forms PDFium understands: the
569
+ // modern /Names /Dests name tree and the legacy /Dests catalog dictionary.
570
+ const OPEN_ACTION_JS = 'app.alert("Opened");';
571
+ const HELPER_JS = 'function helper() { return 42; }';
572
+
573
+ async function createNavigationPdf() {
574
+ const doc = await PDFDocument.create();
575
+ const font = await doc.embedFont(StandardFonts.Helvetica);
576
+ const pages = [];
577
+ for (let i = 1; i <= 3; i++) {
578
+ const page = doc.addPage([300, 400]);
579
+ page.drawText(`Section ${i}`, { x: 50, y: 300, size: 20, font });
580
+ pages.push(page);
581
+ }
582
+
583
+ const { PDFName, PDFString } = await import('pdf-lib');
584
+
585
+ // document-level JavaScript, as a /Names /JavaScript name tree
586
+ const jsAction = (script) =>
587
+ doc.context.register(doc.context.obj({ S: 'JavaScript', JS: PDFString.of(script) }));
588
+
589
+ const javaScriptTree = doc.context.obj({
590
+ Names: [
591
+ PDFString.of('OpenAction'),
592
+ jsAction(OPEN_ACTION_JS),
593
+ PDFString.of('Helper'),
594
+ jsAction(HELPER_JS),
595
+ ],
596
+ });
597
+
598
+ // named destinations in the /Names /Dests name tree. Name-tree entries must
599
+ // be sorted by name, which is why these read Alpha/Beta rather than
600
+ // Section1/Section2.
601
+ const destsTree = doc.context.obj({
602
+ Names: [
603
+ PDFString.of('Alpha'),
604
+ [pages[0].ref, 'XYZ', 50, 700, 2],
605
+ PDFString.of('Beta'),
606
+ [pages[1].ref, 'Fit'],
607
+ ],
608
+ });
609
+
610
+ doc.catalog.set(
611
+ PDFName.of('Names'),
612
+ doc.context.obj({ JavaScript: javaScriptTree, Dests: destsTree }),
613
+ );
614
+
615
+ // legacy form: a plain /Dests dictionary on the catalog
616
+ doc.catalog.set(PDFName.of('Dests'), doc.context.obj({ Legacy: [pages[2].ref, 'FitH', 250] }));
617
+
618
+ return doc.save();
619
+ }
620
+
621
+ // --- Four-page PDF whose pages identify themselves ---
622
+ // Each page carries its own number as text, so assembly tests can verify
623
+ // order, selection and duplication by reading the pages back.
624
+ async function createFourPagePdf() {
625
+ const doc = await PDFDocument.create();
626
+ const font = await doc.embedFont(StandardFonts.Helvetica);
627
+ for (let i = 1; i <= 4; i++) {
628
+ const page = doc.addPage([300, 400]);
629
+ page.drawText(`Page ${i}`, { x: 50, y: 300, size: 24, font });
630
+ }
631
+ return doc.save();
632
+ }
633
+
634
+ // --- PDF exercising positioned text extraction ---
635
+ // Three runs on one page, each drawn at a known baseline origin: two font
636
+ // sizes, a regular/bold font switch, and a 45-degree rotated run. That is
637
+ // enough to pin down every geometry field getCharacters() reports without
638
+ // depending on glyph outlines.
639
+ async function createPositionedTextPdf() {
640
+ const doc = await PDFDocument.create();
641
+ const page = doc.addPage([400, 300]);
642
+ const regular = await doc.embedFont(StandardFonts.Helvetica);
643
+ const bold = await doc.embedFont(StandardFonts.HelveticaBold);
644
+
645
+ page.drawText('AB', { x: 50, y: 250, size: 24, font: regular });
646
+ page.drawText('CD', { x: 50, y: 200, size: 12, font: bold });
647
+ page.drawText('EF', { x: 200, y: 100, size: 18, font: regular, rotate: degrees(45) });
648
+
649
+ return doc.save();
650
+ }
651
+
652
+ // --- PDF with two AcroForm signature fields ---
653
+ // PDFium finds signatures by walking Catalog -> /AcroForm -> /Fields and
654
+ // keeping the entries whose /FT is /Sig, so the fields have to be built by
655
+ // hand — pdf-lib cannot create signature fields.
656
+ //
657
+ // The /Contents blobs and /ByteRange offsets below are FAKE: they are fixed
658
+ // byte patterns, not a real PKCS#7 structure, and the offsets do not describe
659
+ // this file. That is deliberate and sufficient, because PDFium performs no
660
+ // cryptographic verification — it hands back whatever the dictionary says. The
661
+ // fixture proves the extraction path, never signature validity.
662
+ const SIG_CONTENTS_HEX = '308006092a864886f70d010702a0803080020101';
663
+ const CERT_SIG_CONTENTS_HEX = '3082010a0282010100c0ffee';
664
+
665
+ async function createSignedPdf() {
666
+ const doc = await PDFDocument.create();
667
+ const page = doc.addPage([612, 792]);
668
+ const font = await doc.embedFont(StandardFonts.Helvetica);
669
+ page.drawText('Signed document', { x: 50, y: 700, size: 16, font });
670
+
671
+ const { PDFName, PDFString, PDFHexString } = await import('pdf-lib');
672
+
673
+ // ordinary approval signature — no /Reference, so no DocMDP permission
674
+ const sigValueRef = doc.context.register(
675
+ doc.context.obj({
676
+ Type: 'Sig',
677
+ Filter: 'Adobe.PPKLite',
678
+ SubFilter: 'adbe.pkcs7.detached',
679
+ ByteRange: [0, 840, 1560, 1234],
680
+ Contents: PDFHexString.of(SIG_CONTENTS_HEX),
681
+ Reason: PDFString.of('I approve this document'),
682
+ M: PDFString.of("D:20250101120000+01'00'"),
683
+ Name: PDFString.of('Test Signer'),
684
+ }),
685
+ );
686
+
687
+ const sigFieldRef = doc.context.register(
688
+ doc.context.obj({
689
+ FT: 'Sig',
690
+ T: PDFString.of('Signature1'),
691
+ V: sigValueRef,
692
+ Type: 'Annot',
693
+ Subtype: 'Widget',
694
+ Rect: [50, 600, 250, 650],
695
+ F: 4,
696
+ P: page.ref,
697
+ }),
698
+ );
699
+
700
+ // certification signature — /Reference -> /DocMDP -> /TransformParams /P 2
701
+ const certValueRef = doc.context.register(
702
+ doc.context.obj({
703
+ Type: 'Sig',
704
+ Filter: 'Adobe.PPKLite',
705
+ SubFilter: 'ETSI.CAdES.detached',
706
+ ByteRange: [0, 200, 900, 300],
707
+ Contents: PDFHexString.of(CERT_SIG_CONTENTS_HEX),
708
+ M: PDFString.of('D:20250202093000Z'),
709
+ Reference: [
710
+ {
711
+ Type: 'SigRef',
712
+ TransformMethod: 'DocMDP',
713
+ TransformParams: { Type: 'TransformParams', P: 2, V: '1.2' },
714
+ },
715
+ ],
716
+ }),
717
+ );
718
+
719
+ const certFieldRef = doc.context.register(
720
+ doc.context.obj({
721
+ FT: 'Sig',
722
+ T: PDFString.of('Certification'),
723
+ V: certValueRef,
724
+ Type: 'Annot',
725
+ Subtype: 'Widget',
726
+ Rect: [50, 520, 250, 570],
727
+ F: 4,
728
+ P: page.ref,
729
+ }),
730
+ );
731
+
732
+ doc.catalog.set(
733
+ PDFName.of('AcroForm'),
734
+ doc.context.obj({ Fields: [sigFieldRef, certFieldRef], SigFlags: 3 }),
735
+ );
736
+ page.node.set(PDFName.of('Annots'), doc.context.obj([sigFieldRef, certFieldRef]));
737
+
738
+ // pdf-lib would otherwise re-read the AcroForm to regenerate widget
739
+ // appearances, which these hand-built signature fields do not need
740
+ return doc.save({ updateFieldAppearances: false });
741
+ }
742
+
743
+ // --- PDF with a page-level FileAttachment annotation ---
744
+ // PDFium exposes "paperclip" file attachments as /FileAttachment annotations
745
+ // whose embedded file lives on the annotation itself, NOT in the
746
+ // /EmbeddedFiles name tree (that is the document-level attachment API). A plain
747
+ // Text annotation precedes it so tests can exercise stable annotation indices
748
+ // and the "not a file attachment" error path.
749
+ const ATTACHMENT_REPORT_TXT = 'Quarterly report attachment.\nSecond line.\n';
750
+
751
+ async function createFileAttachmentAnnotationPdf() {
752
+ const doc = await PDFDocument.create();
753
+ const page = doc.addPage([612, 792]);
754
+ const font = await doc.embedFont(StandardFonts.Helvetica);
755
+ page.drawText('Page with a file-attachment annotation', { x: 50, y: 700, size: 14, font });
756
+
757
+ const { PDFName, PDFString } = await import('pdf-lib');
758
+
759
+ const fileBytes = Buffer.from(ATTACHMENT_REPORT_TXT, 'utf8');
760
+
761
+ // embedded file stream (FlateDecode, so extraction proves a lossless decode)
762
+ const embeddedFile = doc.context.flateStream(fileBytes, {
763
+ Type: 'EmbeddedFile',
764
+ Subtype: 'text/plain',
765
+ Params: { Size: fileBytes.length },
766
+ });
767
+ const embeddedFileRef = doc.context.register(embeddedFile);
768
+
769
+ const fileSpec = doc.context.obj({
770
+ Type: 'Filespec',
771
+ F: PDFString.of('report.txt'),
772
+ UF: PDFString.of('report.txt'),
773
+ EF: doc.context.obj({ F: embeddedFileRef }),
774
+ });
775
+ const fileSpecRef = doc.context.register(fileSpec);
776
+
777
+ // Text annotation first → the FileAttachment annotation lands at index 1
778
+ const textAnnot = doc.context.obj({
779
+ Type: 'Annot',
780
+ Subtype: 'Text',
781
+ Rect: [50, 600, 70, 620],
782
+ Contents: PDFString.of('Just a sticky note'),
783
+ });
784
+ const textAnnotRef = doc.context.register(textAnnot);
785
+
786
+ const fileAnnot = doc.context.obj({
787
+ Type: 'Annot',
788
+ Subtype: 'FileAttachment',
789
+ Rect: [100, 600, 120, 620],
790
+ Contents: PDFString.of('See attached report'),
791
+ FS: fileSpecRef,
792
+ Name: 'Paperclip',
793
+ });
794
+ const fileAnnotRef = doc.context.register(fileAnnot);
795
+
796
+ page.node.set(PDFName.of('Annots'), doc.context.obj([textAnnotRef, fileAnnotRef]));
797
+ return doc.save();
798
+ }
799
+
496
800
  // --- PDF with form fields ---
497
801
  async function createFormFieldsPdf() {
498
802
  const doc = await PDFDocument.create();
@@ -568,6 +872,12 @@ const fixtures = [
568
872
  ['border-annotations.pdf', createBorderAnnotationPdf],
569
873
  ['form-fields.pdf', createFormFieldsPdf],
570
874
  ['einvoice-zugferd.pdf', createEInvoicePdf],
875
+ ['file-attachment-annotation.pdf', createFileAttachmentAnnotationPdf],
876
+ ['signed.pdf', createSignedPdf],
877
+ ['positioned-text.pdf', createPositionedTextPdf],
878
+ ['four-page.pdf', createFourPagePdf],
879
+ ['navigation.pdf', createNavigationPdf],
880
+ ['struct-tree.pdf', createStructTreePdf],
571
881
  ];
572
882
 
573
883
  for (const [name, generator] of fixtures) {