pdfnative 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -74,8 +74,26 @@ interface RadialGradientPaint {
74
74
  readonly stops: readonly ColorStop[];
75
75
  readonly extend: GradientExtend;
76
76
  }
77
+ /**
78
+ * A sweep (conic/angular) gradient fill (COLR PaintSweepGradient).
79
+ *
80
+ * PDF has no native conic shading, so the renderer approximates it as a fan
81
+ * of flat-colour triangular wedges clipped to the glyph outline — pure path
82
+ * operators, no shading resource. Angles are in counter-clockwise degrees
83
+ * from the positive x-axis.
84
+ *
85
+ * @since 1.4.0
86
+ */
87
+ interface SweepGradientPaint {
88
+ readonly kind: 'sweep';
89
+ readonly center: readonly [number, number];
90
+ readonly startAngle: number;
91
+ readonly endAngle: number;
92
+ readonly stops: readonly ColorStop[];
93
+ readonly extend: GradientExtend;
94
+ }
77
95
  /** A paint used to fill a colour-glyph layer. */
78
- type ColorPaint = SolidPaint | LinearGradientPaint | RadialGradientPaint;
96
+ type ColorPaint = SolidPaint | LinearGradientPaint | RadialGradientPaint | SweepGradientPaint;
79
97
  /** A single colour-glyph layer: a base outline filled by a paint. */
80
98
  interface ColorLayer {
81
99
  /** Glyph id of the base outline (in the font's `glyf` table). */
@@ -89,6 +107,17 @@ interface ColorLayer {
89
107
  * absent.
90
108
  */
91
109
  readonly transform?: readonly [number, number, number, number, number, number];
110
+ /**
111
+ * Optional PDF blend mode name (`/BM`) for this layer, flattened from a
112
+ * COLRv1 `PaintComposite` whose composite mode maps to a separable or
113
+ * non-separable PDF blend mode (e.g. `Multiply`, `Screen`, `Overlay`,
114
+ * `Darken`, `Lighten`, `Difference`, `Hue`, `Luminosity`). Absent =
115
+ * `Normal`. Porter-Duff structural modes (Clear/Src/Dest/Xor) are not
116
+ * mapped — those glyphs fall back to the monochrome font instead.
117
+ *
118
+ * @since 1.4.0
119
+ */
120
+ readonly blendMode?: string;
92
121
  }
93
122
  /** A resolved colour glyph: ordered layers painted back-to-front. */
94
123
  interface ColorGlyph {
@@ -265,6 +294,14 @@ interface ColumnDef {
265
294
  * @since 1.2.0
266
295
  */
267
296
  readonly kind?: 'amount';
297
+ /**
298
+ * Vertical alignment of this column's cell content within the row band
299
+ * (`'top'` | `'middle'` | `'bottom'`). Overrides the table-level
300
+ * `TableBlock.cellVAlign`. When omitted, the historic baseline placement is
301
+ * preserved (byte-identical to pre-1.4.0).
302
+ * @since 1.4.0
303
+ */
304
+ readonly vAlign?: 'top' | 'middle' | 'bottom';
268
305
  }
269
306
  /**
270
307
  * Options for generating a PDF in a Web Worker via `generatePDFInWorker()`.
@@ -439,6 +476,157 @@ interface PdfLayoutOptions {
439
476
  * @since 1.3.0
440
477
  */
441
478
  readonly creationDate?: Date;
479
+ /**
480
+ * How a conforming viewer should present the document when it is first
481
+ * opened: initial page layout, page mode (bookmark/thumbnail panel, full
482
+ * screen…), window fit/centering, UI-chrome visibility, and whether the
483
+ * window title shows the document title. Maps to catalog `/PageLayout`,
484
+ * `/PageMode`, and the `/ViewerPreferences` dictionary (ISO 32000-1 §12.2).
485
+ *
486
+ * Purely presentational, PDF/A-safe, and fully optional. When the document
487
+ * also has an outline, an explicit `pageMode` here overrides the outline's
488
+ * default `/UseOutlines`.
489
+ *
490
+ * Default: `undefined` (viewer default presentation).
491
+ *
492
+ * @since 1.4.0
493
+ */
494
+ readonly viewerPreferences?: ViewerPreferences;
495
+ /**
496
+ * Draw a diagnostic layout overlay on every page to visualise how the
497
+ * document builder placed content. Purely a development aid — leave it
498
+ * off (the default) for production output.
499
+ *
500
+ * - `false` / omitted: no overlay (default — output is byte-identical).
501
+ * - `true`: draw all overlay layers (margin box, block content bounds,
502
+ * and table cell outlines).
503
+ * - object: enable individual layers selectively.
504
+ *
505
+ * The overlay is drawn with thin, semi-transparent-free stroked rectangles
506
+ * in distinct colours and never alters text placement, so a document built
507
+ * with `debug` on has identical content geometry to one built with it off —
508
+ * only extra guide rectangles are added.
509
+ *
510
+ * @since 1.5.0
511
+ */
512
+ readonly debug?: boolean | LayoutDebugOptions;
513
+ }
514
+ /**
515
+ * Fine-grained control over the {@link PdfLayoutOptions.debug} overlay layers.
516
+ * Every layer defaults to `false`; pass `debug: true` to enable them all.
517
+ *
518
+ * @since 1.5.0
519
+ */
520
+ interface LayoutDebugOptions {
521
+ /** Draw the page content box (page rect inset by the margins). */
522
+ readonly showMargins?: boolean;
523
+ /** Draw a rectangle around each block's laid-out content bounds. */
524
+ readonly showContentBounds?: boolean;
525
+ /** Draw cell outlines for every table cell. */
526
+ readonly showCells?: boolean;
527
+ }
528
+ /**
529
+ * Viewer presentation preferences (ISO 32000-1 §12.2, Table 150 + §7.7.2).
530
+ *
531
+ * Every field is optional; omitted fields leave the viewer's default behaviour
532
+ * unchanged. Purely presentational and PDF/A-safe.
533
+ *
534
+ * @since 1.4.0
535
+ */
536
+ interface ViewerPreferences {
537
+ /**
538
+ * Initial page layout (catalog `/PageLayout`):
539
+ * - `'singlePage'`: one page at a time
540
+ * - `'oneColumn'`: continuous single column
541
+ * - `'twoColumnLeft'` / `'twoColumnRight'`: continuous two columns, odd pages on the left/right
542
+ * - `'twoPageLeft'` / `'twoPageRight'`: two pages at a time, odd pages on the left/right
543
+ */
544
+ readonly pageLayout?: 'singlePage' | 'oneColumn' | 'twoColumnLeft' | 'twoColumnRight' | 'twoPageLeft' | 'twoPageRight';
545
+ /**
546
+ * Initial page mode (catalog `/PageMode`):
547
+ * - `'useNone'`: neither bookmarks nor thumbnails visible
548
+ * - `'useOutlines'`: bookmark panel open
549
+ * - `'useThumbs'`: thumbnail panel open
550
+ * - `'fullScreen'`: full-screen, no menu/panel
551
+ * - `'useOC'`: optional-content (layers) panel
552
+ * - `'useAttachments'`: attachments panel
553
+ */
554
+ readonly pageMode?: 'useNone' | 'useOutlines' | 'useThumbs' | 'fullScreen' | 'useOC' | 'useAttachments';
555
+ /** Hide the viewer's tool bars. */
556
+ readonly hideToolbar?: boolean;
557
+ /** Hide the viewer's menu bar. */
558
+ readonly hideMenubar?: boolean;
559
+ /** Hide UI elements (scrollbars, navigation controls), leaving only the page. */
560
+ readonly hideWindowUI?: boolean;
561
+ /** Resize the document window to fit the first displayed page. */
562
+ readonly fitWindow?: boolean;
563
+ /** Centre the document window on the screen. */
564
+ readonly centerWindow?: boolean;
565
+ /** Show the document title (from `/Info /Title`) in the window title bar. */
566
+ readonly displayDocTitle?: boolean;
567
+ /** Page mode to use when exiting full-screen (`/NonFullScreenPageMode`). */
568
+ readonly nonFullScreenPageMode?: 'useNone' | 'useOutlines' | 'useThumbs' | 'useOC';
569
+ /** Predominant reading order: left-to-right (default) or right-to-left. */
570
+ readonly direction?: 'l2r' | 'r2l';
571
+ /** Page-scaling default for the Print dialog (`/PrintScaling`). */
572
+ readonly printScaling?: 'none' | 'appDefault';
573
+ }
574
+ /**
575
+ * One block's laid-out footprint, as reported by {@link inspectDocumentLayout}.
576
+ * Coordinates are in PDF user space (origin bottom-left, points), matching the
577
+ * document builder: `top` is the y-coordinate of the block's upper edge and
578
+ * `height` extends downward from it.
579
+ *
580
+ * @since 1.5.0
581
+ */
582
+ interface InspectedBlock {
583
+ /** The originating block's `type` (e.g. `'heading'`, `'paragraph'`, `'table'`). */
584
+ readonly type: string;
585
+ /** 0-based index of the page this block was placed on. */
586
+ readonly page: number;
587
+ /** X-coordinate of the block's left edge (points). */
588
+ readonly x: number;
589
+ /** Y-coordinate of the block's top edge (points, y increases upward). */
590
+ readonly top: number;
591
+ /** Content width available to the block (points). */
592
+ readonly width: number;
593
+ /** Estimated block height (points). */
594
+ readonly height: number;
595
+ }
596
+ /** One page's worth of {@link InspectedBlock}s. @since 1.5.0 */
597
+ interface InspectedPage {
598
+ /** 0-based page index. */
599
+ readonly index: number;
600
+ /** Blocks placed on this page, in render order. */
601
+ readonly blocks: readonly InspectedBlock[];
602
+ }
603
+ /**
604
+ * Deterministic, read-only description of how {@link inspectDocumentLayout}
605
+ * expects the document builder to paginate and place a set of blocks. Useful
606
+ * for debugging layout, writing layout assertions in tests, or building
607
+ * higher-level tooling — it never renders a PDF.
608
+ *
609
+ * The result mirrors the builder's pagination using the same measurement
610
+ * primitives; treat the per-block geometry as a faithful estimate.
611
+ *
612
+ * @since 1.5.0
613
+ */
614
+ interface LayoutInspection {
615
+ /** Page width in points. */
616
+ readonly pageWidth: number;
617
+ /** Page height in points. */
618
+ readonly pageHeight: number;
619
+ /** Page margins `{ t, r, b, l }` in points. */
620
+ readonly margins: {
621
+ readonly t: number;
622
+ readonly r: number;
623
+ readonly b: number;
624
+ readonly l: number;
625
+ };
626
+ /** Total number of pages the blocks paginate into. */
627
+ readonly totalPages: number;
628
+ /** Per-page block placement. */
629
+ readonly pages: readonly InspectedPage[];
442
630
  }
443
631
  /**
444
632
  * Relationship of an embedded file to the PDF document (ISO 19005-3 §6.8).
@@ -806,7 +994,7 @@ declare function parseSvgPath(d: string): SvgSegment[];
806
994
  * @param options - Fill, stroke, viewBox options
807
995
  * @returns PDF content stream operators string
808
996
  */
809
- declare function renderSvg(data: string, x: number, y: number, w: number, h: number, options?: SvgRenderOptions): string;
997
+ declare function renderSvg(data: string, x: number, y: number, w: number, h: number, options?: SvgRenderOptions, enc?: EncodingContext): string;
810
998
 
811
999
  /**
812
1000
  * pdfnative — AcroForm Interactive Fields (ISO 32000-1 §12.7)
@@ -892,6 +1080,31 @@ declare function buildAppearanceStreamDict(w: number, h: number, streamLength: n
892
1080
  */
893
1081
  declare function buildRadioGroupParent(name: string, selectedValue: string, childObjNums: readonly number[], readOnly: boolean, required: boolean): string;
894
1082
 
1083
+ /**
1084
+ * pdfnative — Page Labels (ISO 32000-1 §12.4.2)
1085
+ * ==============================================
1086
+ * Builds the `/PageLabels` number tree placed in the document catalog.
1087
+ * Page labels control the page numbering shown in a viewer's page-number
1088
+ * box and thumbnails (e.g. roman-numeral front matter `i, ii, iii`,
1089
+ * decimal body `1, 2, 3`, prefixed appendices `A-1, A-2`).
1090
+ *
1091
+ * The builder is **pure** and emits an inline dictionary string — page
1092
+ * labels require no indirect objects. Output is PDF/A-safe.
1093
+ */
1094
+ /** Page-numbering style for a {@link PageLabelRange}. */
1095
+ type PageLabelStyle = 'decimal' | 'roman' | 'Roman' | 'alpha' | 'Alpha' | 'none';
1096
+ /** A contiguous run of pages sharing a numbering scheme. */
1097
+ interface PageLabelRange {
1098
+ /** 0-based index of the first page in this range. */
1099
+ readonly startPage: number;
1100
+ /** Numbering style. Omit or use `'none'` for prefix-only labels. */
1101
+ readonly style?: PageLabelStyle;
1102
+ /** Optional label prefix (e.g. `'A-'`). */
1103
+ readonly prefix?: string;
1104
+ /** First numeric value in the range (default `1`). */
1105
+ readonly start?: number;
1106
+ }
1107
+
895
1108
  /**
896
1109
  * pdfnative — Document Content Model Types
897
1110
  * ==========================================
@@ -1007,14 +1220,77 @@ interface TableBlock {
1007
1220
  * @since 1.2.0
1008
1221
  */
1009
1222
  readonly cellPadding?: number;
1223
+ /**
1224
+ * Draw borders around each header/data cell. When omitted, no cell borders
1225
+ * are drawn (byte-identical to pre-1.4.0 — the table keeps only its header
1226
+ * underline and row separators). See {@link CellBorders}.
1227
+ *
1228
+ * @since 1.4.0
1229
+ */
1230
+ readonly cellBorders?: CellBorders;
1231
+ /**
1232
+ * Vertical alignment of cell content within the row band: `'top'`,
1233
+ * `'middle'`, or `'bottom'`. A per-column {@link ColumnDef.vAlign} overrides
1234
+ * this. When omitted, the historic baseline placement is preserved exactly
1235
+ * (byte-identical to pre-1.4.0).
1236
+ *
1237
+ * @since 1.4.0
1238
+ */
1239
+ readonly cellVAlign?: 'top' | 'middle' | 'bottom';
1240
+ }
1241
+ /**
1242
+ * Per-cell border configuration for a {@link TableBlock}. All sides are off by
1243
+ * default; enable individual sides or use `all: true`. Pure vector strokes
1244
+ * (`re`/`l`/`S`), so output stays PDF/A-safe.
1245
+ *
1246
+ * @since 1.4.0
1247
+ */
1248
+ interface CellBorders {
1249
+ /** Draw the top edge of each cell. */
1250
+ readonly top?: boolean;
1251
+ /** Draw the right edge of each cell. */
1252
+ readonly right?: boolean;
1253
+ /** Draw the bottom edge of each cell. */
1254
+ readonly bottom?: boolean;
1255
+ /** Draw the left edge of each cell. */
1256
+ readonly left?: boolean;
1257
+ /** Draw all four edges (shorthand; overrides the individual side flags). */
1258
+ readonly all?: boolean;
1259
+ /** Stroke colour. Default: `'0.8 0.8 0.8'` (light grey). */
1260
+ readonly color?: PdfColor;
1261
+ /** Stroke width in points. Default: `0.5`. */
1262
+ readonly width?: number;
1263
+ /** Stroke style. Default: `'solid'`. */
1264
+ readonly style?: 'solid' | 'dashed' | 'dotted';
1010
1265
  }
1011
1266
  /** List block — bullet or numbered items. */
1012
1267
  interface ListBlock {
1013
1268
  readonly type: 'list';
1014
- readonly items: readonly string[];
1269
+ /**
1270
+ * List entries. Each entry is either a plain string (leaf item) or a
1271
+ * {@link ListItem} object that can carry its own nested sub-list, enabling
1272
+ * hierarchical (multi-level) bullet/numbered lists. Plain strings and
1273
+ * nested objects may be freely mixed. Passing only strings is byte-identical
1274
+ * to the pre-1.4.0 flat-list behaviour.
1275
+ */
1276
+ readonly items: readonly (string | ListItem)[];
1015
1277
  readonly style: 'bullet' | 'numbered';
1016
1278
  readonly fontSize?: number;
1017
1279
  }
1280
+ /**
1281
+ * A single hierarchical list entry: text plus an optional nested sub-list.
1282
+ * Used by {@link ListBlock} to build multi-level outlines (bullets within
1283
+ * bullets, numbered sub-items, …). Sub-items inherit the parent list's
1284
+ * `style`; numbered sub-lists restart their numbering at 1.
1285
+ *
1286
+ * @since 1.4.0
1287
+ */
1288
+ interface ListItem {
1289
+ /** The item's text content. */
1290
+ readonly text: string;
1291
+ /** Optional nested child entries (recursive). */
1292
+ readonly items?: readonly (string | ListItem)[];
1293
+ }
1018
1294
  /** Spacer block — vertical whitespace. */
1019
1295
  interface SpacerBlock {
1020
1296
  readonly type: 'spacer';
@@ -1131,6 +1407,38 @@ interface DocumentMetadata {
1131
1407
  readonly subject?: string;
1132
1408
  readonly keywords?: string;
1133
1409
  }
1410
+ /**
1411
+ * A document outline (bookmark) entry — ISO 32000-1 §12.3.3.
1412
+ *
1413
+ * Outline items form a navigable tree shown in a viewer's bookmarks
1414
+ * panel. Each item points at a 0-based page index and may nest children.
1415
+ * Bookmarks are purely navigational and PDF/A-safe.
1416
+ *
1417
+ * @since 1.4.0
1418
+ */
1419
+ interface OutlineItem {
1420
+ /** Bookmark label (UTF-16BE encoded automatically). */
1421
+ readonly title: string;
1422
+ /** 0-based destination page index. */
1423
+ readonly pageIndex: number;
1424
+ /** Destination Y coordinate in points (default: top of page). */
1425
+ readonly y?: number;
1426
+ /** Render the label bold (`/F` flag bit 2). */
1427
+ readonly bold?: boolean;
1428
+ /** Render the label italic (`/F` flag bit 1). */
1429
+ readonly italic?: boolean;
1430
+ /** Label colour (`/C`). Accepts hex, RGB tuple, or PDF operator string. */
1431
+ readonly color?: PdfColor;
1432
+ /**
1433
+ * Initial expansion state. `true` (default) renders the bookmark expanded
1434
+ * (positive `/Count`); `false` renders it collapsed (negative `/Count`),
1435
+ * hiding its children until the reader expands it. Only meaningful when the
1436
+ * item has `children`.
1437
+ */
1438
+ readonly open?: boolean;
1439
+ /** Nested child bookmarks. */
1440
+ readonly children?: readonly OutlineItem[];
1441
+ }
1134
1442
  /**
1135
1443
  * Parameters for the free-form document PDF builder.
1136
1444
  *
@@ -1154,6 +1462,26 @@ interface DocumentParams {
1154
1462
  readonly fontEntries?: readonly FontEntry[];
1155
1463
  readonly metadata?: DocumentMetadata;
1156
1464
  readonly layout?: Partial<PdfLayoutOptions>;
1465
+ /**
1466
+ * Document outline / bookmarks (ISO 32000-1 §12.3.3).
1467
+ *
1468
+ * - An array of {@link OutlineItem}s builds an explicit bookmark tree.
1469
+ * - The literal `'auto'` derives a flat outline from every `heading`
1470
+ * block in document order, using each heading's page and position.
1471
+ *
1472
+ * Adds `/Outlines` + `/PageMode /UseOutlines` to the catalog. PDF/A-safe.
1473
+ *
1474
+ * @since 1.4.0
1475
+ */
1476
+ readonly outline?: readonly OutlineItem[] | 'auto';
1477
+ /**
1478
+ * Page labels (ISO 32000-1 §12.4.2) — controls the page numbering shown
1479
+ * in a viewer's page box and thumbnails (e.g. roman front matter then
1480
+ * decimal body). Emitted as an inline `/PageLabels` number tree. PDF/A-safe.
1481
+ *
1482
+ * @since 1.4.0
1483
+ */
1484
+ readonly pageLabels?: readonly PageLabelRange[];
1157
1485
  }
1158
1486
 
1159
1487
  /**
@@ -1487,6 +1815,133 @@ declare function buildDocumentPDF(params: DocumentParams, layoutOptions?: Partia
1487
1815
  */
1488
1816
  declare function buildDocumentPDFBytes(params: DocumentParams, layoutOptions?: Partial<PdfLayoutOptions>): Uint8Array;
1489
1817
 
1818
+ /**
1819
+ * pdfnative — Layout Inspection (development / tooling aid)
1820
+ * ========================================================
1821
+ * `inspectDocumentLayout()` reports, without rendering a PDF, how the document
1822
+ * builder is expected to paginate a set of blocks and where each block lands.
1823
+ * It reuses the exact same measurement primitives as the builder
1824
+ * (`estimateBlockHeight`, `planTable`, the layout constants), so the reported
1825
+ * geometry is a faithful estimate of the real output.
1826
+ *
1827
+ * This is read-only and deterministic — ideal for debugging layout issues,
1828
+ * writing layout assertions in tests, or driving higher-level tooling.
1829
+ *
1830
+ * @since 1.5.0
1831
+ */
1832
+
1833
+ /**
1834
+ * Inspect how {@link DocumentParams.blocks} will paginate and where each block
1835
+ * is placed, without building a PDF.
1836
+ *
1837
+ * @param params The same document params passed to `buildDocumentPDF`.
1838
+ * @param layoutOptions Optional layout overrides (page size, margins, tagged
1839
+ * mode, header template…). `params.layout` is used when
1840
+ * omitted, matching the builder.
1841
+ * @returns A deterministic {@link LayoutInspection}.
1842
+ */
1843
+ declare function inspectDocumentLayout(params: DocumentParams, layoutOptions?: Partial<PdfLayoutOptions>): LayoutInspection;
1844
+
1845
+ /**
1846
+ * pdfnative — Markup & Drawing Annotations (ISO 32000-1 §12.5)
1847
+ * ============================================================
1848
+ * Typed builders for the common non-link annotation types: text (sticky
1849
+ * note), the text-markup family (highlight / underline / strike-out /
1850
+ * squiggly), the drawing family (square / circle / line), and free text.
1851
+ *
1852
+ * Each builder emits a single self-contained indirect object. Annotations
1853
+ * are referenced from a page's `/Annots` array — use the parser's
1854
+ * `PdfModifier.addAnnotation()` to attach one to an existing document, or
1855
+ * emit the object directly when assembling a PDF.
1856
+ *
1857
+ * Security: `/Contents` and `/T` are encoded via `encodePdfTextString`
1858
+ * (PDFDocEncoding literal or UTF-16BE hex), so arbitrary user text — including
1859
+ * newlines and non-Latin scripts — is safely escaped.
1860
+ *
1861
+ * @since 1.5.0
1862
+ */
1863
+
1864
+ /** Rectangle `[x1, y1, x2, y2]` in PDF user space (points). */
1865
+ type AnnotationRect = readonly [number, number, number, number];
1866
+ /** Fields shared by every markup / drawing annotation. */
1867
+ interface AnnotationBase {
1868
+ /** Annotation rectangle `[x1, y1, x2, y2]`. */
1869
+ readonly rect: AnnotationRect;
1870
+ /** Text content / note body (`/Contents`). Safely encoded. */
1871
+ readonly contents?: string;
1872
+ /** Annotation colour (`/C`) — border/line/icon colour. */
1873
+ readonly color?: PdfColor;
1874
+ /** Constant opacity `/CA` in `[0, 1]`. */
1875
+ readonly opacity?: number;
1876
+ /** Author / title (`/T`). */
1877
+ readonly title?: string;
1878
+ /** Modification date string, e.g. `D:20260705120000Z` (`/M`). */
1879
+ readonly modified?: string;
1880
+ /** Annotation flags bitfield (`/F`). Default `4` (Print). */
1881
+ readonly flags?: number;
1882
+ }
1883
+ /** Sticky-note text annotation (`/Subtype /Text`). */
1884
+ interface TextAnnotation extends AnnotationBase {
1885
+ readonly type: 'text';
1886
+ /** Whether the note pop-up is initially open (`/Open`). */
1887
+ readonly open?: boolean;
1888
+ /** Icon name (`/Name`): `Note`, `Comment`, `Key`, `Help`, `Insert`, … */
1889
+ readonly icon?: string;
1890
+ }
1891
+ /** Text-markup annotation (highlight / underline / strike-out / squiggly). */
1892
+ interface TextMarkupAnnotation extends AnnotationBase {
1893
+ readonly type: 'highlight' | 'underline' | 'strikeout' | 'squiggly';
1894
+ /**
1895
+ * Quadrilateral points (`/QuadPoints`), 8 numbers per marked region:
1896
+ * `x1 y1 x2 y2 x3 y3 x4 y4` (upper-left, upper-right, lower-left,
1897
+ * lower-right). When omitted, the `rect` corners are used.
1898
+ */
1899
+ readonly quadPoints?: readonly number[];
1900
+ }
1901
+ /** Rectangle / ellipse drawing annotation. */
1902
+ interface ShapeAnnotation extends AnnotationBase {
1903
+ readonly type: 'square' | 'circle';
1904
+ /** Interior fill colour (`/IC`). */
1905
+ readonly interiorColor?: PdfColor;
1906
+ /** Border width in points (`/BS /W`). Default `1`. */
1907
+ readonly borderWidth?: number;
1908
+ }
1909
+ /** Straight-line annotation (`/Subtype /Line`). */
1910
+ interface LineAnnotation extends AnnotationBase {
1911
+ readonly type: 'line';
1912
+ /** Line start point `[x, y]`. */
1913
+ readonly start: readonly [number, number];
1914
+ /** Line end point `[x, y]`. */
1915
+ readonly end: readonly [number, number];
1916
+ /** Line width in points (`/BS /W`). Default `1`. */
1917
+ readonly borderWidth?: number;
1918
+ }
1919
+ /** Free-text (typewriter) annotation (`/Subtype /FreeText`). */
1920
+ interface FreeTextAnnotation extends AnnotationBase {
1921
+ readonly type: 'freetext';
1922
+ /** Font size in points for the default appearance (`/DA`). Default `12`. */
1923
+ readonly fontSize?: number;
1924
+ }
1925
+ /** Any builder-supported annotation. */
1926
+ type MarkupAnnotation = TextAnnotation | TextMarkupAnnotation | ShapeAnnotation | LineAnnotation | FreeTextAnnotation;
1927
+ /**
1928
+ * Build a markup / drawing annotation as a PDF indirect object.
1929
+ *
1930
+ * @param annot The typed annotation description.
1931
+ * @param objNum Object number to assign.
1932
+ * @returns `"<objNum> 0 obj … endobj"` string.
1933
+ */
1934
+ declare function buildAnnotation(annot: MarkupAnnotation, objNum: number): string;
1935
+ /**
1936
+ * Build just the annotation dictionary (`<< … >>`), without the
1937
+ * `obj`/`endobj` wrapper. Use this with the parser's
1938
+ * `PdfModifier.addAnnotation()` to attach an annotation to an existing page.
1939
+ *
1940
+ * @param annot The typed annotation description.
1941
+ * @returns The annotation dictionary string.
1942
+ */
1943
+ declare function buildAnnotationBody(annot: MarkupAnnotation): string;
1944
+
1490
1945
  /**
1491
1946
  * pdfnative — Color Parsing, Validation & Normalization
1492
1947
  * =======================================================
@@ -1808,6 +2263,83 @@ declare function verifyCertSignature(cert: X509Certificate, issuerCert: X509Cert
1808
2263
  */
1809
2264
  declare function isSelfSigned(cert: X509Certificate): boolean;
1810
2265
 
2266
+ /**
2267
+ * pdfnative — Pluggable Signature Crypto Provider
2268
+ * ================================================
2269
+ * pdfnative ships its own pure-TypeScript RSA (PKCS#1 v1.5) and ECDSA (P-256)
2270
+ * implementations so that signing works in any runtime with **zero
2271
+ * dependencies**. Those pure-JS primitives are built on JavaScript `BigInt`
2272
+ * arithmetic, which V8/SpiderMonkey do **not** execute in constant time — see
2273
+ * the timing-side-channel caveat in `SECURITY.md`.
2274
+ *
2275
+ * For high-security, high-frequency server pipelines (a backend signing many
2276
+ * PDFs/s with one key under adversarial timing observation), this module lets
2277
+ * you inject a hardware-backed, **constant-time** signer — Node.js
2278
+ * `node:crypto` or a Web Crypto wrapper — without giving up the zero-dependency
2279
+ * default. The pure-JS path remains the fallback when no provider is set.
2280
+ *
2281
+ * The provider produces the raw CMS signature value over the **DER-encoded
2282
+ * signed attributes** (`tbs`, "to be signed"), matching the requested
2283
+ * algorithm:
2284
+ * - `'rsa-sha256'` → RSASSA-PKCS1-v1_5 signature over `SHA-256(tbs)`.
2285
+ * - `'ecdsa-sha256'`→ a **DER-encoded** ECDSA (P-256) signature over
2286
+ * `SHA-256(tbs)` (i.e. `SEQUENCE { r INTEGER, s INTEGER }`).
2287
+ *
2288
+ * @example Node.js `node:crypto` (constant-time, hardware-backed)
2289
+ * ```ts
2290
+ * import { setCryptoProvider } from 'pdfnative';
2291
+ * import { createSign, createPrivateKey } from 'node:crypto';
2292
+ *
2293
+ * const key = createPrivateKey(pemPrivateKey);
2294
+ * setCryptoProvider({
2295
+ * sign(tbs, algorithm) {
2296
+ * // node:crypto hashes `tbs` internally and returns a DER ECDSA sig.
2297
+ * return new Uint8Array(createSign('sha256').update(tbs).sign(key));
2298
+ * },
2299
+ * });
2300
+ * ```
2301
+ *
2302
+ * @since 1.4.0
2303
+ */
2304
+
2305
+ /**
2306
+ * A pluggable signer that replaces pdfnative's pure-JS RSA/ECDSA math with a
2307
+ * native, constant-time implementation.
2308
+ */
2309
+ interface CryptoProvider {
2310
+ /**
2311
+ * Sign the DER-encoded CMS SignedAttributes (`tbs`) and return the raw
2312
+ * signature value to embed in the CMS `SignerInfo`.
2313
+ *
2314
+ * The implementation MUST hash `tbs` with SHA-256 internally (native
2315
+ * `crypto.sign('sha256', …)` does this for you) and produce a signature
2316
+ * matching `algorithm`:
2317
+ * - `'rsa-sha256'` → RSASSA-PKCS1-v1_5 over `SHA-256(tbs)`.
2318
+ * - `'ecdsa-sha256'` → DER-encoded ECDSA-P256 over `SHA-256(tbs)`.
2319
+ */
2320
+ readonly sign: (tbs: Uint8Array, algorithm: SignatureAlgorithm) => Uint8Array;
2321
+ }
2322
+ /**
2323
+ * Install (or clear) a global signature {@link CryptoProvider}. When set, every
2324
+ * `signPdfBytes()` call that does not pass an explicit per-call provider routes
2325
+ * its signature math through `provider` instead of pdfnative's pure-JS RSA/ECDSA
2326
+ * primitives. Pass `null` to restore the zero-dependency default.
2327
+ *
2328
+ * A per-call `PdfSignOptions.provider` always takes precedence over the global
2329
+ * one set here.
2330
+ *
2331
+ * @param provider The native signer, or `null` to revert to pure-JS.
2332
+ * @since 1.4.0
2333
+ */
2334
+ declare function setCryptoProvider(provider: CryptoProvider | null): void;
2335
+ /**
2336
+ * The currently-installed global {@link CryptoProvider}, or `null` if none.
2337
+ * Primarily for internal dispatch and testing.
2338
+ *
2339
+ * @since 1.4.0
2340
+ */
2341
+ declare function getCryptoProvider(): CryptoProvider | null;
2342
+
1811
2343
  /**
1812
2344
  * pdfnative — CMS SignedData Builder (RFC 5652)
1813
2345
  * ==============================================
@@ -1832,6 +2364,14 @@ interface CmsSignOptions {
1832
2364
  readonly signingTime?: Date;
1833
2365
  /** Signature algorithm. */
1834
2366
  readonly algorithm: SignatureAlgorithm;
2367
+ /**
2368
+ * Optional native signer. When supplied (or when a global provider is set
2369
+ * via {@link setCryptoProvider}), the signature value is produced by the
2370
+ * provider instead of the pure-JS RSA/ECDSA primitives, and `rsaKey` /
2371
+ * `ecKey` are not required.
2372
+ * @since 1.4.0
2373
+ */
2374
+ readonly provider?: CryptoProvider;
1835
2375
  }
1836
2376
  /**
1837
2377
  * Build a CMS SignedData structure for a PDF detached signature.
@@ -1895,6 +2435,15 @@ interface PdfSignOptions extends SigDictMetadata {
1895
2435
  readonly ecKey?: EcPrivateKey;
1896
2436
  /** Algorithm to use. Default: 'rsa-sha256'. */
1897
2437
  readonly algorithm?: SignatureAlgorithm;
2438
+ /**
2439
+ * Optional native signature provider (e.g. `node:crypto` / Web Crypto). When
2440
+ * set — or when a global provider is installed via {@link setCryptoProvider}
2441
+ * — the constant-time native signer replaces pdfnative's pure-JS RSA/ECDSA
2442
+ * math, and `rsaKey` / `ecKey` become optional. A per-call provider takes
2443
+ * precedence over the global one.
2444
+ * @since 1.4.0
2445
+ */
2446
+ readonly provider?: CryptoProvider;
1898
2447
  }
1899
2448
  /**
1900
2449
  * Build a /Sig signature dictionary string for embedding in a PDF.
@@ -2179,6 +2728,37 @@ declare function concatChunks(chunks: readonly Uint8Array[]): Uint8Array;
2179
2728
  * @returns Total byte count
2180
2729
  */
2181
2730
  declare function streamByteLength(stream: AsyncGenerator<Uint8Array>): Promise<number>;
2731
+ /** Result of {@link streamToFile}. */
2732
+ interface StreamToFileResult {
2733
+ /** Total number of bytes written to the file. */
2734
+ readonly bytesWritten: number;
2735
+ /** The path the stream was written to. */
2736
+ readonly path: string;
2737
+ }
2738
+ /**
2739
+ * Write a streaming PDF (any of the `streamPdf`/`buildPDFStream*` generators)
2740
+ * directly to a file on disk in **constant memory**, honouring write
2741
+ * back-pressure. Node.js-only convenience wrapper.
2742
+ *
2743
+ * The dependency on `node:fs` is loaded **dynamically** so this module stays
2744
+ * tree-shakeable and bundler-safe for the browser; calling `streamToFile` in
2745
+ * a non-Node environment throws a descriptive error.
2746
+ *
2747
+ * @example
2748
+ * ```ts
2749
+ * await streamToFile(streamDocumentPdf({ blocks }), './out.pdf');
2750
+ * ```
2751
+ *
2752
+ * @param stream An async generator of PDF byte chunks.
2753
+ * @param filePath Destination path. The caller is responsible for validating
2754
+ * untrusted paths (path traversal, allowed directories).
2755
+ * @param opts Optional `AbortSignal` to cancel mid-write.
2756
+ * @returns Bytes written and the destination path.
2757
+ * @since 1.4.0
2758
+ */
2759
+ declare function streamToFile(stream: AsyncGenerator<Uint8Array>, filePath: string, opts?: {
2760
+ readonly signal?: AbortSignal;
2761
+ }): Promise<StreamToFileResult>;
2182
2762
 
2183
2763
  /**
2184
2764
  * pdfnative — SHA-384, SHA-512, HMAC-SHA256
@@ -2498,6 +3078,47 @@ declare function clearFontCache(): void;
2498
3078
  */
2499
3079
  declare function resetFontRegistry(): void;
2500
3080
 
3081
+ /**
3082
+ * pdfnative — Font Data Validator
3083
+ * ================================
3084
+ * `validateFontData()` performs a read-only structural sanity check on a
3085
+ * {@link FontData} module before it is used for rendering. The bundled font
3086
+ * modules under `pdfnative/fonts/*` are already trusted; this validator exists
3087
+ * for consumers who **build their own** font data (via `tools/build-font-data.cjs`
3088
+ * or by hand) from an untrusted or unfamiliar TTF/OTF.
3089
+ *
3090
+ * It catches the common failure modes — a corrupt/empty base64 payload, a
3091
+ * non-SFNT binary, an empty `cmap`, glyph ids that point outside the metrics,
3092
+ * a malformed `pdfWidthArray`, or non-finite metrics — and reports them as
3093
+ * descriptive errors instead of letting a cryptic `.notdef`/`NaN` failure
3094
+ * surface deep inside the encoding/subsetting pipeline.
3095
+ *
3096
+ * The check is **opt-in and standalone**: it is NOT invoked automatically by
3097
+ * `registerFont()` (that would add cost to every load and risks false-rejecting
3098
+ * edge-valid fonts). Call it yourself when ingesting third-party font data.
3099
+ *
3100
+ * @since 1.4.0
3101
+ */
3102
+ /** Result of {@link validateFontData}. */
3103
+ interface FontValidationResult {
3104
+ /** True when no blocking errors were found. */
3105
+ readonly valid: boolean;
3106
+ /** Blocking structural problems that would break rendering. */
3107
+ readonly errors: readonly string[];
3108
+ /** Non-blocking concerns (suspicious but not necessarily fatal). */
3109
+ readonly warnings: readonly string[];
3110
+ }
3111
+ /**
3112
+ * Structurally validate a {@link FontData} module. Returns `{ valid, errors,
3113
+ * warnings }`; `valid` is `false` when any blocking problem is found. Does not
3114
+ * throw on malformed input — it reports.
3115
+ *
3116
+ * @param data The font data to validate (typically the default export of a
3117
+ * generated `*-data.js` module).
3118
+ * @since 1.4.0
3119
+ */
3120
+ declare function validateFontData(data: unknown): FontValidationResult;
3121
+
2501
3122
  /**
2502
3123
  * pdfnative — Thai Mini-Shaper
2503
3124
  * =============================
@@ -2548,6 +3169,16 @@ declare function isKhmerCodepoint(cp: number): boolean;
2548
3169
  declare function isMyanmarCodepoint(cp: number): boolean;
2549
3170
  /** Check if a codepoint falls in any Devanagari Unicode block. */
2550
3171
  declare function isDevanagariCodepoint(cp: number): boolean;
3172
+ /**
3173
+ * Check if a codepoint should be routed to a mathematical font (e.g. Noto
3174
+ * Sans Math). Covers the Mathematical Operators, Supplemental Mathematical
3175
+ * Operators, Geometric Shapes, and Miscellaneous Mathematical Symbols-A/B
3176
+ * blocks. Deliberately excludes Letterlike Symbols (™ ® ℗ …) and the emoji
3177
+ * Miscellaneous-Symbols/Dingbats ranges so those keep their existing routing.
3178
+ *
3179
+ * @since 1.5.0
3180
+ */
3181
+ declare function isMathCodepoint(cp: number): boolean;
2551
3182
  /** Check if text contains Arabic characters requiring shaping. */
2552
3183
  declare function containsArabic(text: string): boolean;
2553
3184
  /** Check if text contains Hebrew characters. */
@@ -2572,6 +3203,8 @@ declare function containsKhmer(str: string): boolean;
2572
3203
  declare function containsMyanmar(str: string): boolean;
2573
3204
  /** Check whether a string contains any Devanagari characters. */
2574
3205
  declare function containsDevanagari(str: string): boolean;
3206
+ /** Check whether a string contains any mathematical symbols. */
3207
+ declare function containsMath(str: string): boolean;
2575
3208
 
2576
3209
  /**
2577
3210
  * pdfnative — Bengali Mini-Shaper
@@ -3183,13 +3816,15 @@ declare function extractGlyphContours(font: GlyfFont, gid: number, depth?: numbe
3183
3816
  * Supported:
3184
3817
  * - COLR v0 — layered solid fills.
3185
3818
  * - COLR v1 — PaintColrLayers, PaintGlyph, PaintColrGlyph, PaintSolid,
3186
- * PaintLinearGradient, PaintRadialGradient, PaintTransform,
3187
- * PaintTranslate, PaintScale (+ around-center).
3819
+ * PaintLinearGradient, PaintRadialGradient, PaintSweepGradient,
3820
+ * PaintTransform, PaintTranslate, PaintScale (+ around-center),
3821
+ * PaintComposite (blend-mode-mappable composite modes).
3188
3822
  *
3189
- * Unsupported paints (sweep gradients, compositing, variable paints) cause
3190
- * the affected glyph to be skipped so the caller can fall back to the
3191
- * monochrome emoji font. This keeps output correct (never garbled) while
3192
- * covering the overwhelming majority of Noto Color Emoji glyphs.
3823
+ * Unsupported paints (variable paints, Porter-Duff structural composite
3824
+ * modes Clear/Src/Dest/Xor/…) cause the affected glyph to be skipped so the
3825
+ * caller can fall back to the monochrome emoji font. This keeps output
3826
+ * correct (never garbled) while covering the overwhelming majority of
3827
+ * Noto Color Emoji glyphs.
3193
3828
  *
3194
3829
  * Zero external dependency.
3195
3830
  *
@@ -3222,6 +3857,10 @@ declare function parseColrCpal(bytes: Uint8Array): Record<number, ColorGlyph> |
3222
3857
  * - Linear gradients → `/Shading` Type 2 (axial) painted via `sh`,
3223
3858
  * clipped to the glyph outline.
3224
3859
  * - Radial gradients → `/Shading` Type 3, likewise.
3860
+ * - Sweep (conic) gradients → a fan of flat-colour triangular wedges
3861
+ * clipped to the outline (PDF has no native conic shading). (v1.4.0)
3862
+ * - Per-layer blend modes (`/BM`, from COLRv1 `PaintComposite`) via an
3863
+ * ExtGState applied around the layer's fill. (v1.4.0)
3225
3864
  *
3226
3865
  * The Form XObject's user space is font units; the caller scales it onto the
3227
3866
  * page with a `cm` and draws it with `Do`.
@@ -3454,6 +4093,29 @@ declare function getTrailerRef(trailer: PdfDict, key: string): PdfRef | undefine
3454
4093
  * const info = reader.info;
3455
4094
  */
3456
4095
 
4096
+ /**
4097
+ * A page annotation parsed by {@link PdfReader.getAnnotations}. Covers the
4098
+ * common fields across link, text-markup and drawing annotations; the raw
4099
+ * dictionary is available for anything not surfaced here.
4100
+ *
4101
+ * @since 1.5.0
4102
+ */
4103
+ interface ParsedAnnotation {
4104
+ /** Annotation subtype (`/Subtype`), e.g. `'Link'`, `'Highlight'`, `'Text'`. */
4105
+ readonly subtype: string;
4106
+ /** Annotation rectangle `[x1, y1, x2, y2]`, or `null` when malformed. */
4107
+ readonly rect: readonly [number, number, number, number] | null;
4108
+ /** Decoded `/Contents` text (UTF-16BE or PDFDocEncoding), when present. */
4109
+ readonly contents?: string;
4110
+ /** Decoded author / title (`/T`), when present. */
4111
+ readonly title?: string;
4112
+ /** Colour components (`/C`), 0–1, when present. */
4113
+ readonly color?: readonly number[];
4114
+ /** Text-markup quadrilateral points (`/QuadPoints`), when present. */
4115
+ readonly quadPoints?: readonly number[];
4116
+ /** Target URL for URI-action link annotations, when present. */
4117
+ readonly url?: string;
4118
+ }
3457
4119
  interface PdfReader {
3458
4120
  /** Total number of pages in the document. */
3459
4121
  readonly pageCount: number;
@@ -3489,6 +4151,27 @@ interface PdfReader {
3489
4151
  * Get the document info dictionary, if present.
3490
4152
  */
3491
4153
  getInfo(): PdfDict | null;
4154
+ /**
4155
+ * Read the document's `/PageLabels` number tree (ISO 32000-1 §12.4.2)
4156
+ * back into an ordered list of {@link PageLabelRange}s.
4157
+ *
4158
+ * Returns `null` when the catalog has no `/PageLabels` entry.
4159
+ * The result is the round-trip complement of `buildPageLabelsDict`.
4160
+ */
4161
+ getPageLabels(): PageLabelRange[] | null;
4162
+ /**
4163
+ * Read the `/Annots` array of the given page (0-based) and return the
4164
+ * parsed annotations (ISO 32000-1 §12.5). Link, text-markup and drawing
4165
+ * annotations are surfaced with their common fields; use
4166
+ * {@link ParsedAnnotation} for the shape.
4167
+ */
4168
+ getAnnotations(pageIndex: number): ParsedAnnotation[];
4169
+ /**
4170
+ * Get the indirect reference of the page at the given index (0-based),
4171
+ * or `null` when out of range. Useful for incremental modification
4172
+ * (e.g. attaching an annotation via `PdfModifier.addAnnotation`).
4173
+ */
4174
+ getPageRef(pageIndex: number): PdfRef | null;
3492
4175
  /**
3493
4176
  * Get decoded stream data for a stream object.
3494
4177
  * Handles /FlateDecode and /Filter chains.
@@ -3543,6 +4226,20 @@ interface PdfModifier {
3543
4226
  * Returns the new object number.
3544
4227
  */
3545
4228
  addRawObject(body: string): number;
4229
+ /**
4230
+ * Attach an annotation to a page's `/Annots` array via incremental update.
4231
+ *
4232
+ * The annotation dictionary body (`<< /Type /Annot … >>`, without the
4233
+ * `obj`/`endobj` wrapper — as produced by `buildAnnotationBody`) is added
4234
+ * as a new object, and the target page dictionary is rewritten with the
4235
+ * new reference appended to its `/Annots` array (created if absent).
4236
+ *
4237
+ * @param pageIndex 0-based page index.
4238
+ * @param annotationBody The annotation dictionary string.
4239
+ * @returns The new annotation object number.
4240
+ * @throws Error when `pageIndex` is out of range.
4241
+ */
4242
+ addAnnotation(pageIndex: number, annotationBody: string): number;
3546
4243
  /**
3547
4244
  * Get the current value of an object (modified or original).
3548
4245
  */
@@ -3565,6 +4262,99 @@ interface PdfModifier {
3565
4262
  */
3566
4263
  declare function createModifier(reader: PdfReader): PdfModifier;
3567
4264
 
4265
+ /**
4266
+ * pdfnative — Page-Tree Manipulation API (ISO 32000-1 §7.7.3)
4267
+ * ============================================================
4268
+ * Safe, **faithful** page-level document assembly: merge, split, and
4269
+ * extract pages across PDF documents.
4270
+ *
4271
+ * Unlike the incremental modifier (`createModifier`), these operations
4272
+ * **rebuild** a brand-new document from scratch: every kept page and its
4273
+ * transitive object graph (`/Contents`, `/Resources`, fonts, XObjects,
4274
+ * ExtGState, …) is deep-copied into a fresh, contiguous object-number
4275
+ * space, then wired into a new flat `/Pages` tree, `/Catalog`, xref, and
4276
+ * trailer. This avoids production-unsafe in-place surgery (relocating
4277
+ * `/Kids`, rewriting `/Parent` chains, merging resource pools).
4278
+ *
4279
+ * Safety guarantees (documented behaviour):
4280
+ * - **Encrypted sources are rejected** (no Standard Security Handler
4281
+ * writer yet) — throws.
4282
+ * - **Signatures are always removed** — any page-tree edit invalidates a
4283
+ * document signature's `/ByteRange`, so signature/Widget annotations and
4284
+ * the `/AcroForm` are dropped. The `dropSignatures` flag is accepted for
4285
+ * API clarity but the behaviour is unconditional.
4286
+ * - **Annotations** default to URI-`/Link`-only (self-contained). Cross-page
4287
+ * GoTo links and form widgets are dropped to guarantee no dangling
4288
+ * references. `dropAnnotations: true` removes all annotations.
4289
+ * - Output is **not** claimed to be PDF/A — merged OutputIntents / XMP
4290
+ * cannot be reconciled safely.
4291
+ *
4292
+ * @since 1.4.0
4293
+ */
4294
+ /** A contiguous, inclusive page range (0-based). */
4295
+ interface PageRange {
4296
+ /** First page index (0-based, inclusive). */
4297
+ readonly start: number;
4298
+ /** Last page index (0-based, inclusive). Defaults to `start`. */
4299
+ readonly end?: number;
4300
+ }
4301
+ /**
4302
+ * Options for the page-tree manipulation API ({@link mergePdfs},
4303
+ * {@link splitPdf}, {@link extractPages}).
4304
+ */
4305
+ interface MergeOptions {
4306
+ /**
4307
+ * Drop signature fields/widgets. Accepted for clarity; merging always
4308
+ * removes signatures because the operation invalidates `/ByteRange`.
4309
+ */
4310
+ readonly dropSignatures?: boolean;
4311
+ /** Drop **all** annotations (default keeps self-contained URI links). */
4312
+ readonly dropAnnotations?: boolean;
4313
+ /**
4314
+ * Maximum size, in bytes, of the assembled output document. The operation
4315
+ * throws as soon as the copied object graph would exceed this limit — even
4316
+ * mid-copy, before a multi-gigabyte stream is materialised — so a malicious
4317
+ * or accidentally huge source cannot exhaust process memory.
4318
+ *
4319
+ * Defaults to `268435456` (256 MiB). Pass `Infinity` to disable the guard
4320
+ * (not recommended for untrusted input).
4321
+ *
4322
+ * @defaultValue 268435456 (256 MiB)
4323
+ */
4324
+ readonly maxOutputSize?: number;
4325
+ }
4326
+ /**
4327
+ * Concatenate multiple PDF documents into one, preserving page order.
4328
+ *
4329
+ * @param sources 1–50 PDF byte arrays.
4330
+ * @param opts See {@link MergeOptions}.
4331
+ * @returns A new, self-contained PDF.
4332
+ * @throws If `sources` is empty/too large, or any source is encrypted.
4333
+ */
4334
+ declare function mergePdfs(sources: readonly Uint8Array[], opts?: MergeOptions): Uint8Array;
4335
+ /**
4336
+ * Extract a subset of pages from a single document into a new PDF.
4337
+ * Indices may repeat and need not be ordered — output follows the given order.
4338
+ *
4339
+ * @param src Source PDF bytes.
4340
+ * @param pageIndices 0-based page indices to keep.
4341
+ * @param opts See {@link MergeOptions} (e.g. `maxOutputSize`,
4342
+ * `dropAnnotations`).
4343
+ * @throws If `src` is encrypted, indices is empty, or an index is out of range.
4344
+ */
4345
+ declare function extractPages(src: Uint8Array, pageIndices: readonly number[], opts?: MergeOptions): Uint8Array;
4346
+ /**
4347
+ * Split a document into multiple PDFs, one per page range.
4348
+ *
4349
+ * @param src Source PDF bytes.
4350
+ * @param ranges Inclusive 0-based page ranges.
4351
+ * @param opts See {@link MergeOptions} (e.g. `maxOutputSize`,
4352
+ * `dropAnnotations`); applied to every emitted document.
4353
+ * @returns One PDF per range, in order.
4354
+ * @throws If `src` is encrypted, ranges is empty, or a range is invalid.
4355
+ */
4356
+ declare function splitPdf(src: Uint8Array, ranges: readonly PageRange[], opts?: MergeOptions): Uint8Array[];
4357
+
3568
4358
  /**
3569
4359
  * pdfnative — PDF/UA structural validator (ISO 14289-1)
3570
4360
  * ======================================================
@@ -3750,4 +4540,4 @@ declare function createPDF(pdfParams: PdfParams, options?: {
3750
4540
  layoutOptions?: Partial<PdfLayoutOptions>;
3751
4541
  }): Promise<Uint8Array>;
3752
4542
 
3753
- export { type AddSignaturePlaceholderOptions, type Annotation, type Asn1Node, BAL_H, type BarcodeBlock, type BarcodeFormat, type BidiRun, type CmsSignOptions, type ColorGlyph, type ColorGlyphForm, type ColorLayer, type ColorPaint, type ColorStop, type ColumnDef, type Contour, type CpalColor, DEFAULT_COLORS, DEFAULT_COLUMNS, DEFAULT_CW, DEFAULT_FONT_SIZES, DEFAULT_MARGINS, DEFAULT_MAX_BLOCKS, DEFAULT_MAX_INFLATE_OUTPUT, type DocumentBlock, type DocumentMetadata, type DocumentParams, type EcPrivateKey, type EcPublicKey, type EmbeddedFilesResult, type EncodingContext, type EncryptionOptions, FT_H, type FontData, type FontEntry, type FontLoader, type FontMetrics, type FontRun, type FormField, type FormFieldBlock, type FormFieldType, type FormWidgetResult, type GlyfFont, type GradientExtend, HEADER_H, type HeadingBlock, INFO_LN, type ImageBlock, type InternalLink, KNOWN_DECODE_FILTERS, type LinearGradientPaint, type LinkAnnotation, type LinkBlock, type ListBlock, MAX_PARSE_DEPTH, MAX_XREF_CHAIN, type OutlinePoint, type OutlineProvider, PAGE_SIZES, PDF_A_CONFORMANCE_TARGETS, PG_H, PG_W, type PageBreakBlock, type PageTemplate, type ParagraphBlock, type PdfArray as ParsedArray, type PdfDict as ParsedDict, type ParsedImage, type PdfAConfig, type PdfAConformanceTarget, type PdfAttachment, type PdfAttachmentRelationship, type PdfColor, type PdfColors, type PdfIndirectObject, type PdfInfoItem, type PdfLayoutOptions, type PdfModifier, type PdfName, type PdfParams, type PdfReader, type PdfRef, type PdfRgbString, type PdfRgbTuple, type PdfRow, type PdfSignOptions, type PdfStream, type PdfToken, type PdfTokenizer, type PdfUAValidationResult, type PdfValue, type QRErrorLevel, ROW_H, type RadialGradientPaint, type RadioGroupContext, type RsaPrivateKey, type RsaPublicKey, type ShapedGlyph, type SigDictMetadata, type SignatureAlgorithm, type SolidPaint, type SpacerBlock, type StreamOptions, type SvgBlock, type SvgRenderOptions, type SvgSegment, TH_H, TITLE_LN, type TableBlock, type TextRun, type TocBlock, type TokenType, type UseCategory, type UseClassifiedCp, type UseCluster, WORKER_THRESHOLD, WORKER_TIMEOUT_MS, type WatermarkImage, type WatermarkOptions, type WatermarkState, type WatermarkText, type WorkerGenerationOptions, type WorkerInputMessage, type WorkerOutputMessage, type X509Certificate, type X509Name, type XrefEntry, type XrefTable, addSignaturePlaceholder, applyDecodeFilter, buildAcroFormDict, buildAppearanceStreamDict, buildCmsSignedData, buildDocumentPDF, buildDocumentPDFBytes, buildDocumentPDFStream, buildDocumentPDFStreamPageByPage, buildDocumentPDFStreamTrue, buildEmbeddedFiles, buildFormWidget, buildImageOperators, buildImageXObject, buildInternalLinkAnnotation, buildLinkAnnotation, buildPDF, buildPDFBytes, buildPDFStream, buildPDFStreamPageByPage, buildPDFStreamTrue, buildRadioGroupParent, buildSMaskXObject, buildSigDict, buildWatermarkState, chunkBinaryString, classifyClusters, classifyUseCategory, clearFontCache, computeColumnPositions, concatChunks, containsArabic, containsBengali, containsDevanagari, containsEthiopic, containsHebrew, containsKhmer, containsMyanmar, containsRTL, containsSinhala, containsTamil, containsTelugu, containsThai, containsTibetan, contoursToPath, createEncodingContext, createModifier, createPDF, createTokenizer, decodeASCII85, decodeASCIIHex, decodeEcPublicKey, decodeLZW, decodeRunLength, defaultFieldHeight, derBitString, derDecode, derInteger, derOctetString, derOid, derSequence, detectCharLang, detectFallbackLangs, detectImageFormat, dictGet, dictGetArray, dictGetDict, dictGetName, dictGetNum, dictGetRef, downloadBlob, ean13CheckDigit, ecPublicKeyFromPrivate, ecdsaSign, ecdsaVerify, encodeCode128, encodeEcPublicKey, encodePDF417, encodePdfTextString, estimateCmsSize, estimateContentsSize, extractGlyphContours, findStartxref, generateDataMatrix, generatePDFInWorker, generatePDFMainThread, generateQR, getMaxInflateOutputSize, getRegisteredLangs, getTrailerRef, getTrailerValue, hasFontLoader, helveticaBoldWidth, helveticaWidth, hmacSha256, inflateSync, initCrypto, initNodeCompression, initNodeDecompression as initNodeDecompression_parser, isArmenianCodepoint, isArray, isBengaliCodepoint, isCyrillicCodepoint, isDevanagariCodepoint, isDict, isEthiopicCodepoint, isGeorgianCodepoint, isKhmerCodepoint, isLinkAnnotation, isMyanmarCodepoint, isName, isRef, isSelfSigned, isSinhalaCodepoint, isStream, isTamilCodepoint, isTeluguCodepoint, isTibetanCodepoint, isValidPdfRgb, loadFontData, nameValue, needsUnicodeFont, normalizeBidiEmbeddings, normalizeColors, openPdf, parseCertificate, parseColor, parseColrCpal, parseCpal, parseGlyfFont, parseImage, parseIndirectObject, parseJPEG, parsePNG, parseRsaPrivateKey, parseRsaPublicKey, parseSvgPath, parseValue, parseXrefTable, pdfString, registerFont, registerFonts, renderBarcode, renderCode128, renderColorGlyph, renderDataMatrix, renderEAN13, renderPDF417, renderQR, renderSvg, resetFontRegistry, resolveBidiRuns, resolveLayout, resolvePdfAConfig, resolveTemplate, rsaSign, rsaSignHash, rsaVerify, rsaVerifyHash, setDeflateImpl, setInflateImpl, setMaxInflateOutputSize, sha384, sha512, shapeArabicText, shapeBengaliText, shapeDevanagariText, shapeKhmerText, shapeMyanmarText, shapeSinhalaText, shapeTamilText, shapeTeluguText, shapeThaiText, shapeTibetanText, signPdfBytes, slugify, splitTextByFont, streamByteLength, stripBidiControls, toBytes, toWinAnsi, truncate, truncateToWidth, validateAttachments, validateDocumentStreamable, validatePdfUA, validateTableStreamable, validateURL, validateWatermark, verifyCertSignature, wrapText };
4543
+ export { type AddSignaturePlaceholderOptions, type Annotation, type AnnotationBase, type AnnotationRect, type Asn1Node, BAL_H, type BarcodeBlock, type BarcodeFormat, type BidiRun, type CellBorders, type CmsSignOptions, type ColorGlyph, type ColorGlyphForm, type ColorLayer, type ColorPaint, type ColorStop, type ColumnDef, type Contour, type CpalColor, type CryptoProvider, DEFAULT_COLORS, DEFAULT_COLUMNS, DEFAULT_CW, DEFAULT_FONT_SIZES, DEFAULT_MARGINS, DEFAULT_MAX_BLOCKS, DEFAULT_MAX_INFLATE_OUTPUT, type DocumentBlock, type DocumentMetadata, type DocumentParams, type EcPrivateKey, type EcPublicKey, type EmbeddedFilesResult, type EncodingContext, type EncryptionOptions, FT_H, type FontData, type FontEntry, type FontLoader, type FontMetrics, type FontRun, type FontValidationResult, type FormField, type FormFieldBlock, type FormFieldType, type FormWidgetResult, type FreeTextAnnotation, type GlyfFont, type GradientExtend, HEADER_H, type HeadingBlock, INFO_LN, type ImageBlock, type InspectedBlock, type InspectedPage, type InternalLink, KNOWN_DECODE_FILTERS, type LayoutDebugOptions, type LayoutInspection, type LineAnnotation, type LinearGradientPaint, type LinkAnnotation, type LinkBlock, type ListBlock, type ListItem, MAX_PARSE_DEPTH, MAX_XREF_CHAIN, type MarkupAnnotation, type MergeOptions, type OutlineItem, type OutlinePoint, type OutlineProvider, PAGE_SIZES, PDF_A_CONFORMANCE_TARGETS, PG_H, PG_W, type PageBreakBlock, type PageLabelRange, type PageLabelStyle, type PageRange, type PageTemplate, type ParagraphBlock, type ParsedAnnotation, type PdfArray as ParsedArray, type PdfDict as ParsedDict, type ParsedImage, type PdfAConfig, type PdfAConformanceTarget, type PdfAttachment, type PdfAttachmentRelationship, type PdfColor, type PdfColors, type PdfIndirectObject, type PdfInfoItem, type PdfLayoutOptions, type PdfModifier, type PdfName, type PdfParams, type PdfReader, type PdfRef, type PdfRgbString, type PdfRgbTuple, type PdfRow, type PdfSignOptions, type PdfStream, type PdfToken, type PdfTokenizer, type PdfUAValidationResult, type PdfValue, type QRErrorLevel, ROW_H, type RadialGradientPaint, type RadioGroupContext, type RsaPrivateKey, type RsaPublicKey, type ShapeAnnotation, type ShapedGlyph, type SigDictMetadata, type SignatureAlgorithm, type SolidPaint, type SpacerBlock, type StreamOptions, type StreamToFileResult, type SvgBlock, type SvgRenderOptions, type SvgSegment, TH_H, TITLE_LN, type TableBlock, type TextAnnotation, type TextMarkupAnnotation, type TextRun, type TocBlock, type TokenType, type UseCategory, type UseClassifiedCp, type UseCluster, type ViewerPreferences, WORKER_THRESHOLD, WORKER_TIMEOUT_MS, type WatermarkImage, type WatermarkOptions, type WatermarkState, type WatermarkText, type WorkerGenerationOptions, type WorkerInputMessage, type WorkerOutputMessage, type X509Certificate, type X509Name, type XrefEntry, type XrefTable, addSignaturePlaceholder, applyDecodeFilter, buildAcroFormDict, buildAnnotation, buildAnnotationBody, buildAppearanceStreamDict, buildCmsSignedData, buildDocumentPDF, buildDocumentPDFBytes, buildDocumentPDFStream, buildDocumentPDFStreamPageByPage, buildDocumentPDFStreamTrue, buildEmbeddedFiles, buildFormWidget, buildImageOperators, buildImageXObject, buildInternalLinkAnnotation, buildLinkAnnotation, buildPDF, buildPDFBytes, buildPDFStream, buildPDFStreamPageByPage, buildPDFStreamTrue, buildRadioGroupParent, buildSMaskXObject, buildSigDict, buildWatermarkState, chunkBinaryString, classifyClusters, classifyUseCategory, clearFontCache, computeColumnPositions, concatChunks, containsArabic, containsBengali, containsDevanagari, containsEthiopic, containsHebrew, containsKhmer, containsMath, containsMyanmar, containsRTL, containsSinhala, containsTamil, containsTelugu, containsThai, containsTibetan, contoursToPath, createEncodingContext, createModifier, createPDF, createTokenizer, decodeASCII85, decodeASCIIHex, decodeEcPublicKey, decodeLZW, decodeRunLength, defaultFieldHeight, derBitString, derDecode, derInteger, derOctetString, derOid, derSequence, detectCharLang, detectFallbackLangs, detectImageFormat, dictGet, dictGetArray, dictGetDict, dictGetName, dictGetNum, dictGetRef, downloadBlob, ean13CheckDigit, ecPublicKeyFromPrivate, ecdsaSign, ecdsaVerify, encodeCode128, encodeEcPublicKey, encodePDF417, encodePdfTextString, estimateCmsSize, estimateContentsSize, extractGlyphContours, extractPages, findStartxref, generateDataMatrix, generatePDFInWorker, generatePDFMainThread, generateQR, getCryptoProvider, getMaxInflateOutputSize, getRegisteredLangs, getTrailerRef, getTrailerValue, hasFontLoader, helveticaBoldWidth, helveticaWidth, hmacSha256, inflateSync, initCrypto, initNodeCompression, initNodeDecompression as initNodeDecompression_parser, inspectDocumentLayout, isArmenianCodepoint, isArray, isBengaliCodepoint, isCyrillicCodepoint, isDevanagariCodepoint, isDict, isEthiopicCodepoint, isGeorgianCodepoint, isKhmerCodepoint, isLinkAnnotation, isMathCodepoint, isMyanmarCodepoint, isName, isRef, isSelfSigned, isSinhalaCodepoint, isStream, isTamilCodepoint, isTeluguCodepoint, isTibetanCodepoint, isValidPdfRgb, loadFontData, mergePdfs, nameValue, needsUnicodeFont, normalizeBidiEmbeddings, normalizeColors, openPdf, parseCertificate, parseColor, parseColrCpal, parseCpal, parseGlyfFont, parseImage, parseIndirectObject, parseJPEG, parsePNG, parseRsaPrivateKey, parseRsaPublicKey, parseSvgPath, parseValue, parseXrefTable, pdfString, registerFont, registerFonts, renderBarcode, renderCode128, renderColorGlyph, renderDataMatrix, renderEAN13, renderPDF417, renderQR, renderSvg, resetFontRegistry, resolveBidiRuns, resolveLayout, resolvePdfAConfig, resolveTemplate, rsaSign, rsaSignHash, rsaVerify, rsaVerifyHash, setCryptoProvider, setDeflateImpl, setInflateImpl, setMaxInflateOutputSize, sha384, sha512, shapeArabicText, shapeBengaliText, shapeDevanagariText, shapeKhmerText, shapeMyanmarText, shapeSinhalaText, shapeTamilText, shapeTeluguText, shapeThaiText, shapeTibetanText, signPdfBytes, slugify, splitPdf, splitTextByFont, streamByteLength, streamToFile, stripBidiControls, toBytes, toWinAnsi, truncate, truncateToWidth, validateAttachments, validateDocumentStreamable, validateFontData, validatePdfUA, validateTableStreamable, validateURL, validateWatermark, verifyCertSignature, wrapText };