modern-pdf-lib 0.26.0 → 0.28.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 (110) hide show
  1. package/README.md +16 -3
  2. package/dist/{batchOptimize-C1W3O68Q.cjs → batchOptimize-CXC9gNqD.cjs} +55 -55
  3. package/dist/{batchOptimize-BCJEEN8J.mjs → batchOptimize-CjLGD5ie.mjs} +25 -25
  4. package/dist/{bridge-DMEuGtfn.cjs → bridge-ByvzPu5h.cjs} +29 -31
  5. package/dist/{bridge-DaS-gzEd.mjs → bridge-ZD6O6QQa.mjs} +4 -5
  6. package/dist/browser.cjs +245 -154
  7. package/dist/browser.d.cts +166 -166
  8. package/dist/browser.d.cts.map +1 -1
  9. package/dist/browser.d.mts +166 -166
  10. package/dist/browser.d.mts.map +1 -1
  11. package/dist/browser.mjs +15 -19
  12. package/dist/cli/index.cjs +7 -7
  13. package/dist/cli/index.mjs +8 -8
  14. package/dist/{compressionAnalysis-CwknBtqx.mjs → compressionAnalysis-BgKy45pA.mjs} +55 -69
  15. package/dist/{compressionAnalysis-Ch7t-HXn.d.mts → compressionAnalysis-CDOp_vPr.d.mts} +136 -136
  16. package/dist/compressionAnalysis-CDOp_vPr.d.mts.map +1 -0
  17. package/dist/{compressionAnalysis-B-FPzgzw.cjs → compressionAnalysis-Djv-Zvcd.cjs} +85 -99
  18. package/dist/{compressionAnalysis-Dgv1TtHJ.d.cts → compressionAnalysis-UfmonqbM.d.cts} +136 -136
  19. package/dist/compressionAnalysis-UfmonqbM.d.cts.map +1 -0
  20. package/dist/create.cjs +21 -23
  21. package/dist/create.d.cts +2 -2
  22. package/dist/create.d.mts +2 -2
  23. package/dist/create.mjs +3 -5
  24. package/dist/{deduplicateImages-DIon68zB.mjs → deduplicateImages-BTCyAPfJ.mjs} +4 -5
  25. package/dist/{deduplicateImages-cKsnD6Ep.cjs → deduplicateImages-CaGgaqyS.cjs} +14 -15
  26. package/dist/{fieldAppearance-C8PoLFSc.d.mts → fieldAppearance-Df1262CT.d.cts} +44 -44
  27. package/dist/fieldAppearance-Df1262CT.d.cts.map +1 -0
  28. package/dist/{fieldAppearance-CdiGFG5e.d.cts → fieldAppearance-_CZdoUCD.d.mts} +44 -44
  29. package/dist/fieldAppearance-_CZdoUCD.d.mts.map +1 -0
  30. package/dist/fontEmbed-DGiZS0h2.d.cts +677 -0
  31. package/dist/fontEmbed-DGiZS0h2.d.cts.map +1 -0
  32. package/dist/fontEmbed-DtA_riGC.d.mts +677 -0
  33. package/dist/fontEmbed-DtA_riGC.d.mts.map +1 -0
  34. package/dist/forms.cjs +3 -4
  35. package/dist/forms.d.cts +2 -2
  36. package/dist/forms.d.mts +2 -2
  37. package/dist/forms.mjs +2 -3
  38. package/dist/{grayscaleDetect-C6kFF3dk.mjs → grayscaleDetect-6GJrgBRT.mjs} +3 -3
  39. package/dist/{grayscaleDetect-C2m-eEXR.cjs → grayscaleDetect-DAUqxjgR.cjs} +13 -14
  40. package/dist/{imageExtract-zEb1gnkb.cjs → imageExtract-DT50Hp_g.cjs} +13 -14
  41. package/dist/{imageExtract-Dnk_Ssv7.mjs → imageExtract-Dapir-ux.mjs} +3 -4
  42. package/dist/index-C1lZe66f.d.mts +8682 -0
  43. package/dist/index-C1lZe66f.d.mts.map +1 -0
  44. package/dist/index-D1SvXWSI.d.cts +8682 -0
  45. package/dist/index-D1SvXWSI.d.cts.map +1 -0
  46. package/dist/index.cjs +245 -153
  47. package/dist/index.d.cts +7 -7
  48. package/dist/index.d.mts +7 -7
  49. package/dist/index.mjs +14 -17
  50. package/dist/{layout-DQh05VP-.cjs → layout-C4vbTlBW.cjs} +184 -134
  51. package/dist/{layout-CrqeJBMI.mjs → layout-lO4x64kY.mjs} +50 -12
  52. package/dist/{loader-CVB-c_3Z.mjs → loader-B1Ix7ozU.mjs} +248 -12
  53. package/dist/{loader-DYCH3n7d.cjs → loader-DR7H0XOf.cjs} +332 -66
  54. package/dist/parse.cjs +7 -8
  55. package/dist/parse.d.cts +3 -3
  56. package/dist/parse.d.mts +3 -3
  57. package/dist/parse.mjs +6 -7
  58. package/dist/pdfDocument-CH2E4UCc.d.mts +5160 -0
  59. package/dist/pdfDocument-CH2E4UCc.d.mts.map +1 -0
  60. package/dist/{pdfDocument-D9uYNSb-.cjs → pdfDocument-C_7mrBCL.cjs} +22409 -11624
  61. package/dist/pdfDocument-CzOipXnw.d.cts +5160 -0
  62. package/dist/pdfDocument-CzOipXnw.d.cts.map +1 -0
  63. package/dist/{pdfDocument-D7aFSQEY.mjs → pdfDocument-DRbT6HZw.mjs} +10830 -855
  64. package/dist/{pdfForm-BpqDGp29.cjs → pdfForm-BVS_do95.cjs} +112 -107
  65. package/dist/pdfForm-Ca86NDWn.d.cts +897 -0
  66. package/dist/pdfForm-Ca86NDWn.d.cts.map +1 -0
  67. package/dist/pdfForm-Ca86NDWn.d.mts +897 -0
  68. package/dist/pdfForm-Ca86NDWn.d.mts.map +1 -0
  69. package/dist/{pdfForm-C3mC9FoQ.mjs → pdfForm-CfLnlsj-.mjs} +22 -17
  70. package/dist/{pdfObjects-1veop1_d.cjs → pdfObjects-BcPlSI0a.cjs} +62 -53
  71. package/dist/{pdfObjects-uEsWlfzU.mjs → pdfObjects-CB7TEdbW.mjs} +12 -2
  72. package/dist/rolldown-runtime-ak5kbic3.cjs +18 -0
  73. package/dist/{src-lFqJHb1C.cjs → src-C-IDXuvi.cjs} +8692 -1916
  74. package/dist/{src-QZWP21qF.mjs → src-DJaD-bJ2.mjs} +7278 -982
  75. package/dist/{streamDecode-Bj568Nc9.mjs → streamDecode-BamENT3k.mjs} +129 -150
  76. package/dist/{streamDecode-CvgErkFu.cjs → streamDecode-DcaZz309.cjs} +139 -160
  77. package/package.json +25 -22
  78. package/dist/compressionAnalysis-Ch7t-HXn.d.mts.map +0 -1
  79. package/dist/compressionAnalysis-Dgv1TtHJ.d.cts.map +0 -1
  80. package/dist/fflateAdapter-DuNiByKx.mjs +0 -196
  81. package/dist/fflateAdapter-LTAeAhaD.cjs +0 -207
  82. package/dist/fieldAppearance-C8PoLFSc.d.mts.map +0 -1
  83. package/dist/fieldAppearance-CdiGFG5e.d.cts.map +0 -1
  84. package/dist/fontEmbed-3YhUPLFj.d.cts +0 -659
  85. package/dist/fontEmbed-3YhUPLFj.d.cts.map +0 -1
  86. package/dist/fontEmbed-DlVnVCZU.d.mts +0 -659
  87. package/dist/fontEmbed-DlVnVCZU.d.mts.map +0 -1
  88. package/dist/fontSubset-5SLWMmEw.cjs +0 -518
  89. package/dist/fontSubset-BGFDIMmT.mjs +0 -495
  90. package/dist/index-B4S61WjK.d.mts +0 -6507
  91. package/dist/index-B4S61WjK.d.mts.map +0 -1
  92. package/dist/index-xfJP6Ycm.d.cts +0 -6507
  93. package/dist/index-xfJP6Ycm.d.cts.map +0 -1
  94. package/dist/libdeflateWasm-CcA1W04G.mjs +0 -220
  95. package/dist/libdeflateWasm-DLw-I1CY.cjs +0 -237
  96. package/dist/pdfCatalog-Bqq4FiLn.cjs +0 -174
  97. package/dist/pdfCatalog-CnKMAtIo.mjs +0 -139
  98. package/dist/pdfDocument-Bc_vAO74.d.cts +0 -4758
  99. package/dist/pdfDocument-Bc_vAO74.d.cts.map +0 -1
  100. package/dist/pdfDocument-Bi-NoyXv.d.mts +0 -4758
  101. package/dist/pdfDocument-Bi-NoyXv.d.mts.map +0 -1
  102. package/dist/pdfForm-BiyNtYem.d.mts +0 -905
  103. package/dist/pdfForm-BiyNtYem.d.mts.map +0 -1
  104. package/dist/pdfForm-SOXJ72LW.d.cts +0 -905
  105. package/dist/pdfForm-SOXJ72LW.d.cts.map +0 -1
  106. package/dist/pdfPage-BJIE5hc6.mjs +0 -8180
  107. package/dist/pdfPage-C_tjEjj1.cjs +0 -8893
  108. package/dist/pngEmbed-CGi7cym7.mjs +0 -552
  109. package/dist/pngEmbed-CTn9IeNB.cjs +0 -563
  110. package/dist/rolldown-runtime-CKhH4XqG.cjs +0 -24
@@ -1,4758 +0,0 @@
1
- import { C as PdfRef, S as PdfObjectRegistry, T as PdfString, _ as PdfDict, t as PdfForm, w as PdfStream, x as PdfObject } from "./pdfForm-BiyNtYem.mjs";
2
-
3
- //#region src/core/operators/color.d.ts
4
- /**
5
- * @module core/operators/color
6
- *
7
- * PDF colour operators and convenience constructors for typed colour
8
- * values.
9
- *
10
- * Reference: PDF 1.7 spec, §8.6 (Colour Spaces).
11
- */
12
- /** An RGB colour with components in the range `[0, 1]`. */
13
- interface RgbColor {
14
- readonly type: 'rgb';
15
- readonly r: number;
16
- readonly g: number;
17
- readonly b: number;
18
- }
19
- /** A CMYK colour with components in the range `[0, 1]`. */
20
- interface CmykColor {
21
- readonly type: 'cmyk';
22
- readonly c: number;
23
- readonly m: number;
24
- readonly y: number;
25
- readonly k: number;
26
- }
27
- /** A grayscale colour with the component in the range `[0, 1]`. */
28
- interface GrayscaleColor {
29
- readonly type: 'grayscale';
30
- readonly gray: number;
31
- }
32
- /** Union of all supported colour value types. */
33
- type Color = RgbColor | CmykColor | GrayscaleColor;
34
- /**
35
- * Create an RGB colour.
36
- *
37
- * @param r Red component `[0, 1]`.
38
- * @param g Green component `[0, 1]`.
39
- * @param b Blue component `[0, 1]`.
40
- */
41
- declare function rgb(r: number, g: number, b: number): RgbColor;
42
- /**
43
- * Create a CMYK colour.
44
- *
45
- * @param c Cyan component `[0, 1]`.
46
- * @param m Magenta component `[0, 1]`.
47
- * @param y Yellow component `[0, 1]`.
48
- * @param k Black component `[0, 1]`.
49
- */
50
- declare function cmyk(c: number, m: number, y: number, k: number): CmykColor;
51
- /**
52
- * Create a grayscale colour.
53
- *
54
- * @param gray Gray level `[0, 1]` where 0 = black, 1 = white.
55
- */
56
- declare function grayscale(gray: number): GrayscaleColor;
57
- /**
58
- * Set the fill colour in the DeviceRGB colour space (`rg`).
59
- *
60
- * @param r Red `[0, 1]`.
61
- * @param g Green `[0, 1]`.
62
- * @param b Blue `[0, 1]`.
63
- */
64
- declare function setFillColorRgb(r: number, g: number, b: number): string;
65
- /**
66
- * Set the fill colour in the DeviceCMYK colour space (`k`).
67
- */
68
- declare function setFillColorCmyk(c: number, m: number, y: number, k: number): string;
69
- /**
70
- * Set the fill colour in the DeviceGray colour space (`g`).
71
- */
72
- declare function setFillColorGray(gray: number): string;
73
- /**
74
- * Set the stroke colour in the DeviceRGB colour space (`RG`).
75
- */
76
- declare function setStrokeColorRgb(r: number, g: number, b: number): string;
77
- /**
78
- * Set the stroke colour in the DeviceCMYK colour space (`K`).
79
- */
80
- declare function setStrokeColorCmyk(c: number, m: number, y: number, k: number): string;
81
- /**
82
- * Set the stroke colour in the DeviceGray colour space (`G`).
83
- */
84
- declare function setStrokeColorGray(gray: number): string;
85
- /**
86
- * Set the current non-stroking colour space (`cs`).
87
- *
88
- * @param name Colour space name (e.g. `DeviceRGB`, `DeviceCMYK`,
89
- * `DeviceGray`, or a named resource).
90
- */
91
- declare function setColorSpace(name: string): string;
92
- /**
93
- * Set the current stroking colour space (`CS`).
94
- */
95
- declare function setStrokeColorSpace(name: string): string;
96
- /**
97
- * Set the non-stroking colour in the current colour space (`scn`).
98
- *
99
- * @param components One or more colour components.
100
- */
101
- declare function setFillColor(...components: number[]): string;
102
- /**
103
- * Set the stroking colour in the current colour space (`SCN`).
104
- *
105
- * @param components One or more colour components.
106
- */
107
- declare function setStrokeColor(...components: number[]): string;
108
- /**
109
- * Emit the appropriate fill-colour operator for a {@link Color} value.
110
- */
111
- declare function applyFillColor(color: Color): string;
112
- /**
113
- * Emit the appropriate stroke-colour operator for a {@link Color} value.
114
- */
115
- declare function applyStrokeColor(color: Color): string;
116
- /**
117
- * Convert a numeric component array to a typed {@link Color}.
118
- *
119
- * - 1 component → grayscale
120
- * - 3 components → RGB
121
- * - 4 components → CMYK
122
- *
123
- * @param components Array of color component values `[0, 1]`.
124
- * @throws If the array length is not 1, 3, or 4.
125
- */
126
- declare function componentsToColor(components: number[]): Color;
127
- /**
128
- * Convert a typed {@link Color} to a numeric component array.
129
- *
130
- * - Grayscale → `[gray]`
131
- * - RGB → `[r, g, b]`
132
- * - CMYK → `[c, m, y, k]`
133
- */
134
- declare function colorToComponents(color: Color): number[];
135
- /**
136
- * Emit the appropriate fill-colour operator for a {@link Color} value.
137
- *
138
- * Alias for {@link applyFillColor} for pdf-lib API compatibility.
139
- */
140
- declare const setFillingColor: typeof applyFillColor;
141
- /**
142
- * Emit the appropriate stroke-colour operator for a {@link Color} value.
143
- *
144
- * Alias for {@link applyStrokeColor} for pdf-lib API compatibility.
145
- */
146
- declare const setStrokingColor: typeof applyStrokeColor;
147
- //#endregion
148
- //#region src/core/operators/state.d.ts
149
- /**
150
- * @module core/operators/state
151
- *
152
- * PDF graphics-state operators (`q`, `Q`, `cm`) and rotation helpers.
153
- *
154
- * Reference: PDF 1.7 spec, §8.4.2 (Graphics State Operators) and
155
- * §8.3.3 (Common Transformations).
156
- */
157
- /** A rotation / angle value in radians. */
158
- interface Radians {
159
- readonly type: 'radians';
160
- readonly value: number;
161
- }
162
- /** A rotation / angle value in degrees. */
163
- interface Degrees {
164
- readonly type: 'degrees';
165
- readonly value: number;
166
- }
167
- /** Union of angle representations. */
168
- type Angle = Radians | Degrees;
169
- /**
170
- * Create an angle in degrees.
171
- *
172
- * @param deg Angle in degrees (positive = counter-clockwise).
173
- */
174
- declare function degrees(deg: number): Degrees;
175
- /**
176
- * Create an angle in radians.
177
- *
178
- * @param rad Angle in radians (positive = counter-clockwise).
179
- */
180
- declare function radians(rad: number): Radians;
181
- /**
182
- * Save the current graphics state on the graphics state stack (`q`).
183
- */
184
- declare function saveState(): string;
185
- /**
186
- * Restore the most recently saved graphics state (`Q`).
187
- */
188
- declare function restoreState(): string;
189
- /**
190
- * Concatenate the given matrix with the current transformation matrix
191
- * (`cm`).
192
- *
193
- * The six operands define the matrix:
194
- *
195
- * ```
196
- * [ a b 0 ]
197
- * [ c d 0 ]
198
- * [ tx ty 1 ]
199
- * ```
200
- *
201
- * @param a Horizontal scaling / rotation.
202
- * @param b Rotation / skew.
203
- * @param c Rotation / skew.
204
- * @param d Vertical scaling / rotation.
205
- * @param tx Horizontal translation.
206
- * @param ty Vertical translation.
207
- */
208
- declare function concatMatrix(a: number, b: number, c: number, d: number, tx: number, ty: number): string;
209
- /**
210
- * Produce a `cm` operator that applies a **translation**.
211
- *
212
- * @param tx Horizontal distance.
213
- * @param ty Vertical distance.
214
- */
215
- declare function translate(tx: number, ty: number): string;
216
- /**
217
- * Produce a `cm` operator that applies a **uniform scale** about the
218
- * origin.
219
- *
220
- * @param sx Horizontal scale factor.
221
- * @param sy Vertical scale factor.
222
- */
223
- declare function scale(sx: number, sy: number): string;
224
- /**
225
- * Produce a `cm` operator that applies a **rotation** about the origin.
226
- *
227
- * @param angle Rotation angle.
228
- */
229
- declare function rotate(angle: Angle): string;
230
- /**
231
- * Produce a `cm` operator that applies a **skew** (shear).
232
- *
233
- * @param xAngle Skew angle for the x axis.
234
- * @param yAngle Skew angle for the y axis.
235
- */
236
- declare function skew(xAngle: Angle, yAngle: Angle): string;
237
- /**
238
- * Build the six-component matrix array for a rotation about an
239
- * arbitrary centre point `(cx, cy)`.
240
- *
241
- * Useful when you need to compose this with other transformations
242
- * before emitting operators.
243
- *
244
- * @returns `[a, b, c, d, tx, ty]`
245
- */
246
- declare function rotationMatrix(angle: Angle, cx: number, cy: number): [number, number, number, number, number, number];
247
- /**
248
- * Set the graphics state dictionary (`gs`).
249
- *
250
- * The `name` must refer to an entry in the page's `/Resources /ExtGState`
251
- * dictionary.
252
- *
253
- * @param name Graphics-state resource name (e.g. `GS1`).
254
- */
255
- declare function setGraphicsState(name: string): string;
256
- /**
257
- * Convert degrees to radians.
258
- *
259
- * @param deg Angle in degrees.
260
- * @returns Angle in radians.
261
- */
262
- declare function degreesToRadians(deg: number): number;
263
- /**
264
- * Convert radians to degrees.
265
- *
266
- * @param rad Angle in radians.
267
- * @returns Angle in degrees.
268
- */
269
- declare function radiansToDegrees(rad: number): number;
270
- //#endregion
271
- //#region src/core/enums.d.ts
272
- /**
273
- * PDF blend modes (PDF 1.4+, Table 136).
274
- * Applied via ExtGState /BM key.
275
- */
276
- declare const BlendMode: {
277
- readonly Normal: "Normal";
278
- readonly Multiply: "Multiply";
279
- readonly Screen: "Screen";
280
- readonly Overlay: "Overlay";
281
- readonly Darken: "Darken";
282
- readonly Lighten: "Lighten";
283
- readonly ColorDodge: "ColorDodge";
284
- readonly ColorBurn: "ColorBurn";
285
- readonly HardLight: "HardLight";
286
- readonly SoftLight: "SoftLight";
287
- readonly Difference: "Difference";
288
- readonly Exclusion: "Exclusion";
289
- };
290
- /** A PDF blend mode name. */
291
- type BlendMode = (typeof BlendMode)[keyof typeof BlendMode];
292
- /**
293
- * PDF text rendering modes (Table 106).
294
- * Applied via the Tr operator inside a text object.
295
- */
296
- declare const TextRenderingMode: {
297
- readonly Fill: 0;
298
- readonly Outline: 1;
299
- readonly FillAndOutline: 2;
300
- readonly Invisible: 3;
301
- readonly FillAndClip: 4;
302
- readonly OutlineAndClip: 5;
303
- readonly FillAndOutlineAndClip: 6;
304
- readonly Clip: 7;
305
- };
306
- /** A PDF text rendering mode integer (0-7). */
307
- type TextRenderingMode = (typeof TextRenderingMode)[keyof typeof TextRenderingMode];
308
- /**
309
- * PDF line cap styles (Table 54).
310
- * Applied via the J operator.
311
- */
312
- declare const LineCapStyle: {
313
- readonly Butt: 0;
314
- readonly Round: 1;
315
- readonly Projecting: 2;
316
- };
317
- type LineCapStyle = (typeof LineCapStyle)[keyof typeof LineCapStyle];
318
- /**
319
- * PDF line join styles (Table 55).
320
- * Applied via the j operator.
321
- */
322
- declare const LineJoinStyle: {
323
- readonly Miter: 0;
324
- readonly Round: 1;
325
- readonly Bevel: 2;
326
- };
327
- type LineJoinStyle = (typeof LineJoinStyle)[keyof typeof LineJoinStyle];
328
- /**
329
- * Text alignment for form fields and layout operations.
330
- */
331
- declare const TextAlignment: {
332
- readonly Left: 0;
333
- readonly Center: 1;
334
- readonly Right: 2;
335
- };
336
- type TextAlignment = (typeof TextAlignment)[keyof typeof TextAlignment];
337
- /**
338
- * Image alignment for layout operations.
339
- */
340
- declare const ImageAlignment: {
341
- readonly Left: 0;
342
- readonly Center: 1;
343
- readonly Right: 2;
344
- };
345
- type ImageAlignment = (typeof ImageAlignment)[keyof typeof ImageAlignment];
346
- /**
347
- * Preset parsing speeds — maps to objectsPerTick values in LoadPdfOptions.
348
- *
349
- * Lower values keep the main thread more responsive but parse more slowly.
350
- */
351
- declare const ParseSpeeds: {
352
- readonly Fastest: number;
353
- readonly Fast: 500;
354
- readonly Medium: 100;
355
- readonly Slow: 10;
356
- };
357
- type ParseSpeeds = (typeof ParseSpeeds)[keyof typeof ParseSpeeds];
358
- //#endregion
359
- //#region src/accessibility/structureTree.d.ts
360
- /**
361
- * Standard structure types defined by the PDF specification (ISO 32000-1,
362
- * Table 333 through Table 340), plus a `string` catch-all for custom
363
- * structure types.
364
- *
365
- * Groups:
366
- * - **Grouping**: Document, Part, Art, Sect, Div, BlockQuote, Caption,
367
- * TOC, TOCI, Index, NonStruct, Private
368
- * - **Block-level**: P, H, H1..H6
369
- * - **List**: L, LI, Lbl, LBody
370
- * - **Table**: Table, TR, TH, TD, THead, TBody, TFoot
371
- * - **Inline-level**: Span, Quote, Note, Reference, BibEntry, Code,
372
- * Link, Annot
373
- * - **Ruby / Warichu**: Ruby, RB, RT, RP, Warichu, WT, WP
374
- * - **Illustration**: Figure, Formula, Form
375
- */
376
- type StructureType = 'Document' | 'Part' | 'Art' | 'Sect' | 'Div' | 'BlockQuote' | 'Caption' | 'TOC' | 'TOCI' | 'Index' | 'NonStruct' | 'Private' | 'P' | 'H' | 'H1' | 'H2' | 'H3' | 'H4' | 'H5' | 'H6' | 'L' | 'LI' | 'Lbl' | 'LBody' | 'Table' | 'TR' | 'TH' | 'TD' | 'THead' | 'TBody' | 'TFoot' | 'Span' | 'Quote' | 'Note' | 'Reference' | 'BibEntry' | 'Code' | 'Link' | 'Annot' | 'Ruby' | 'RB' | 'RT' | 'RP' | 'Warichu' | 'WT' | 'WP' | 'Figure' | 'Formula' | 'Form' | (string & {});
377
- /**
378
- * Optional attributes for a structure element.
379
- */
380
- interface StructureElementOptions {
381
- /** The element title (a human-readable label). */
382
- title?: string | undefined;
383
- /** Alternative text for the element (required for images by PDF/UA). */
384
- altText?: string | undefined;
385
- /** Replacement text that may be used instead of the element's content. */
386
- actualText?: string | undefined;
387
- /** The natural language for this element (BCP 47, e.g. `"en-US"`). */
388
- language?: string | undefined;
389
- /** An optional unique identifier for the element. */
390
- id?: string | undefined;
391
- }
392
- /**
393
- * Describes a single accessibility issue found during validation.
394
- */
395
- interface AccessibilityIssue {
396
- /** Severity of the issue. */
397
- severity: 'error' | 'warning' | 'info';
398
- /** Machine-readable issue code. */
399
- code: string;
400
- /** Human-readable description of the issue. */
401
- message: string;
402
- /** The structure element related to the issue, if any. */
403
- element?: PdfStructureElement | undefined;
404
- /** The zero-based page index related to the issue, if any. */
405
- pageIndex?: number | undefined;
406
- }
407
- /**
408
- * A single node in the structure tree.
409
- *
410
- * Structure elements form a tree that mirrors the logical reading order
411
- * of the document. Each element has a type (e.g. `"P"`, `"H1"`,
412
- * `"Table"`), optional attributes, and may contain child elements or
413
- * marked-content references (MCIDs) that link to the actual page
414
- * content.
415
- */
416
- declare class PdfStructureElement {
417
- /** The structure type of this element. */
418
- readonly type: StructureType;
419
- /** Child structure elements. */
420
- readonly children: PdfStructureElement[];
421
- /** Optional attributes (alt text, language, title, etc.). */
422
- readonly options: StructureElementOptions;
423
- /** Marked content ID linking this element to page content. */
424
- mcid?: number | undefined;
425
- /** Zero-based page index this element's content appears on. */
426
- pageIndex?: number | undefined;
427
- /** The parent element (undefined for the root). */
428
- parent?: PdfStructureElement | undefined;
429
- /**
430
- * @param type The structure type (e.g. `"P"`, `"H1"`, `"Figure"`).
431
- * @param options Optional attributes for the element.
432
- */
433
- constructor(type: StructureType, options?: StructureElementOptions);
434
- /**
435
- * Add a child element to this node.
436
- *
437
- * @param type The child's structure type.
438
- * @param options Optional attributes for the child.
439
- * @returns The newly created child element.
440
- */
441
- addChild(type: StructureType, options?: StructureElementOptions): PdfStructureElement;
442
- /**
443
- * Remove a direct child element.
444
- *
445
- * @param element The child to remove.
446
- * @throws If the element is not a direct child.
447
- */
448
- removeChild(element: PdfStructureElement): void;
449
- /**
450
- * Recursively collect all elements in the subtree (depth-first,
451
- * including this element).
452
- */
453
- walk(): PdfStructureElement[];
454
- /**
455
- * Find the first descendant (or self) matching the given type.
456
- */
457
- find(type: StructureType): PdfStructureElement | undefined;
458
- /**
459
- * Find all descendants (and self) matching the given type.
460
- */
461
- findAll(type: StructureType): PdfStructureElement[];
462
- /**
463
- * Return the depth of this element in the tree (root = 0).
464
- */
465
- depth(): number;
466
- /**
467
- * Serialize this element to a PDF dictionary.
468
- *
469
- * @param registry Object registry for allocating indirect references.
470
- * @param parentRef Reference to the parent element (or StructTreeRoot).
471
- * @param pageRefs Array of page references indexed by page number.
472
- * @returns An object containing the element's dict and its ref.
473
- */
474
- toDict(registry: PdfObjectRegistry, parentRef: PdfRef, pageRefs: readonly PdfRef[]): {
475
- ref: PdfRef;
476
- dict: PdfDict;
477
- };
478
- }
479
- /**
480
- * The structure tree for a tagged PDF document.
481
- *
482
- * Manages the root `Document` element, assigns marked-content IDs
483
- * (MCIDs), and provides serialization to/from PDF dictionaries.
484
- *
485
- * Usage:
486
- * ```ts
487
- * const tree = doc.createStructureTree();
488
- * const heading = tree.addElement(null, 'H1', { altText: 'Main heading' });
489
- * tree.assignMcid(heading, 0);
490
- *
491
- * const para = tree.addElement(null, 'P');
492
- * tree.assignMcid(para, 0);
493
- * ```
494
- */
495
- declare class PdfStructureTree {
496
- /** The root `Document` structure element. */
497
- readonly root: PdfStructureElement;
498
- /** Next available marked-content ID. */
499
- private nextMcid;
500
- constructor();
501
- /**
502
- * Add an element to the structure tree.
503
- *
504
- * @param parent The parent element, or `null` to add directly under
505
- * the root `Document` element.
506
- * @param type The structure type of the new element.
507
- * @param options Optional attributes for the element.
508
- * @returns The newly created element.
509
- */
510
- addElement(parent: PdfStructureElement | null, type: StructureType, options?: StructureElementOptions): PdfStructureElement;
511
- /**
512
- * Remove an element from the tree.
513
- *
514
- * @param element The element to remove (must not be the root).
515
- * @throws If the element is the root or has no parent.
516
- */
517
- removeElement(element: PdfStructureElement): void;
518
- /**
519
- * Assign a marked-content ID to an element and associate it with a
520
- * page. The MCID links the structure element to the actual content
521
- * on the page (via BMC/BDC operators in the content stream).
522
- *
523
- * @param element The element to assign an MCID to.
524
- * @param pageIndex The zero-based page index the content appears on.
525
- * @returns The assigned MCID.
526
- */
527
- assignMcid(element: PdfStructureElement, pageIndex: number): number;
528
- /**
529
- * Return all elements in the tree (depth-first traversal from root).
530
- */
531
- getAllElements(): PdfStructureElement[];
532
- /**
533
- * Return the current MCID counter value (useful for testing).
534
- */
535
- getNextMcid(): number;
536
- /**
537
- * Serialize the structure tree to a `/StructTreeRoot` dictionary.
538
- *
539
- * The resulting dict is suitable for embedding in the PDF catalog
540
- * as `/StructTreeRoot`.
541
- *
542
- * @param registry Object registry for allocating indirect references.
543
- * @param pageRefs Array of page references indexed by page number.
544
- * @returns An object containing the StructTreeRoot ref and dict.
545
- */
546
- toDict(registry: PdfObjectRegistry, pageRefs: readonly PdfRef[]): {
547
- ref: PdfRef;
548
- dict: PdfDict;
549
- };
550
- /**
551
- * Build the /ParentTree number tree.
552
- *
553
- * The parent tree maps each MCID to the structure element that
554
- * "owns" it. This is implemented as a number tree (a sorted
555
- * array of [key, value] pairs stored in /Nums).
556
- *
557
- * @internal
558
- */
559
- private buildParentTree;
560
- /**
561
- * Build the /IDTree name tree.
562
- *
563
- * Maps element IDs (strings) to their structure element references.
564
- *
565
- * @internal
566
- */
567
- private buildIdTree;
568
- /**
569
- * Reconstruct a structure tree from a `/StructTreeRoot` dictionary.
570
- *
571
- * @param dict The `/StructTreeRoot` dictionary.
572
- * @param resolver A function that resolves indirect references to
573
- * their underlying PDF objects.
574
- * @returns A new {@link PdfStructureTree}.
575
- */
576
- static fromDict(dict: PdfDict, resolver: (ref: PdfRef) => PdfObject | undefined): PdfStructureTree;
577
- /**
578
- * Validate the structure tree for common accessibility issues.
579
- *
580
- * Checks:
581
- * - Heading hierarchy (no skipped levels)
582
- * - Table structure completeness
583
- * - Illustration elements have alt text
584
- * - List structure completeness
585
- *
586
- * @returns An array of {@link AccessibilityIssue} objects.
587
- */
588
- validate(): AccessibilityIssue[];
589
- /**
590
- * Validate heading hierarchy: headings should not skip levels
591
- * (e.g. H1 then H3 without H2).
592
- *
593
- * @internal
594
- */
595
- private validateHeadingHierarchy;
596
- /**
597
- * Validate table structure: Table should contain TR, TR should
598
- * contain TH or TD.
599
- *
600
- * @internal
601
- */
602
- private validateTableStructure;
603
- /**
604
- * Validate that illustration elements (Figure, Formula, Form) have
605
- * alt text.
606
- *
607
- * @internal
608
- */
609
- private validateIllustrationAltText;
610
- /**
611
- * Validate list structure: L should contain LI, LI should contain
612
- * Lbl and/or LBody.
613
- *
614
- * @internal
615
- */
616
- private validateListStructure;
617
- }
618
- //#endregion
619
- //#region src/annotation/pdfAnnotation.d.ts
620
- /**
621
- * All annotation subtypes defined in the PDF specification.
622
- */
623
- type AnnotationType = 'Text' | 'Link' | 'FreeText' | 'Line' | 'Square' | 'Circle' | 'Polygon' | 'PolyLine' | 'Highlight' | 'Underline' | 'Squiggly' | 'StrikeOut' | 'Stamp' | 'Caret' | 'Ink' | 'Popup' | 'FileAttachment' | 'Sound' | 'Movie' | 'Widget' | 'Screen' | 'PrinterMark' | 'TrapNet' | 'Watermark' | 'Redact' | '3D';
624
- /**
625
- * Options for creating a new annotation.
626
- */
627
- interface AnnotationOptions {
628
- /** Annotation rectangle [x1, y1, x2, y2] in default user space. */
629
- rect: [number, number, number, number];
630
- /** Text contents (displayed as tooltip or popup). */
631
- contents?: string | undefined;
632
- /** Author / title of the annotation. */
633
- author?: string | undefined;
634
- /** Last modification date. */
635
- modificationDate?: Date | undefined;
636
- /** Colour in RGB (each component 0-1). */
637
- color?: {
638
- r: number;
639
- g: number;
640
- b: number;
641
- } | undefined;
642
- /** Opacity (0 = transparent, 1 = opaque). */
643
- opacity?: number | undefined;
644
- /** Annotation flags bitmask (PDF spec Table 165). */
645
- flags?: number | undefined;
646
- /** Border specification. */
647
- border?: {
648
- width: number;
649
- style?: 'solid' | 'dashed' | 'beveled' | 'inset' | 'underline' | undefined;
650
- } | undefined;
651
- }
652
- /** Annotation flag bit positions. */
653
- declare const AnnotationFlags: {
654
- readonly Invisible: number;
655
- readonly Hidden: number;
656
- readonly Print: number;
657
- readonly NoZoom: number;
658
- readonly NoRotate: number;
659
- readonly NoView: number;
660
- readonly ReadOnly: number;
661
- readonly Locked: number;
662
- readonly ToggleNoView: number;
663
- readonly LockedContents: number;
664
- };
665
- /**
666
- * Create a PdfAnnotation from an existing dictionary.
667
- *
668
- * @param dict The annotation dictionary.
669
- * @param resolver Optional function to resolve indirect references.
670
- * @returns A PdfAnnotation instance.
671
- */
672
- declare function annotationFromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfAnnotation;
673
- /**
674
- * Build an annotation dictionary from options.
675
- *
676
- * Used internally by subclass factory methods to populate common
677
- * annotation dictionary entries.
678
- *
679
- * @param type The annotation subtype.
680
- * @param options Creation options.
681
- * @returns A populated PdfDict.
682
- */
683
- declare function buildAnnotationDict(type: AnnotationType, options: AnnotationOptions): PdfDict;
684
- /**
685
- * Create a new annotation with the given type and options.
686
- *
687
- * This is a convenience function that creates a generic PdfAnnotation.
688
- * For type-specific annotations, use the subclass `create()` methods.
689
- *
690
- * @param type The annotation subtype.
691
- * @param options Creation options (rect, contents, etc.).
692
- * @returns A new PdfAnnotation instance.
693
- */
694
- declare function createAnnotation(type: AnnotationType, options: AnnotationOptions): PdfAnnotation;
695
- /**
696
- * Base class for all PDF annotations.
697
- *
698
- * Wraps a PdfDict representing the annotation dictionary. Subclasses
699
- * add type-specific getters/setters.
700
- */
701
- declare class PdfAnnotation {
702
- /** The annotation subtype. */
703
- readonly annotationType: AnnotationType;
704
- /** The underlying annotation dictionary. */
705
- protected dict: PdfDict;
706
- constructor(type: AnnotationType, dict: PdfDict);
707
- /** Get the annotation subtype. */
708
- getType(): AnnotationType;
709
- /** Get the annotation rectangle [x1, y1, x2, y2]. */
710
- getRect(): [number, number, number, number];
711
- /** Set the annotation rectangle. */
712
- setRect(rect: [number, number, number, number]): void;
713
- /** Get the text contents (tooltip / popup text). */
714
- getContents(): string | undefined;
715
- /** Set the text contents. */
716
- setContents(contents: string): void;
717
- /** Get the author (PDF /T entry). */
718
- getAuthor(): string | undefined;
719
- /** Set the author. */
720
- setAuthor(author: string): void;
721
- /** Get the annotation colour. */
722
- getColor(): {
723
- r: number;
724
- g: number;
725
- b: number;
726
- } | undefined;
727
- /** Set the annotation colour. */
728
- setColor(color: {
729
- r: number;
730
- g: number;
731
- b: number;
732
- }): void;
733
- /** Get the annotation opacity (0-1). Defaults to 1. */
734
- getOpacity(): number;
735
- /** Set the annotation opacity. */
736
- setOpacity(opacity: number): void;
737
- /** Get the raw flags bitmask. */
738
- private getFlags;
739
- /** Set the raw flags bitmask. */
740
- private setFlags;
741
- /** Check if a specific flag bit is set. */
742
- private hasFlag;
743
- /** Set or clear a specific flag bit. */
744
- private setFlag;
745
- /** Whether the annotation is hidden. */
746
- isHidden(): boolean;
747
- /** Set the hidden flag. */
748
- setHidden(hidden: boolean): void;
749
- /** Whether the annotation should be printed. */
750
- isPrintable(): boolean;
751
- /** Set the print flag. */
752
- setPrintable(printable: boolean): void;
753
- /** Whether the annotation is locked (cannot be moved/resized). */
754
- isLocked(): boolean;
755
- /** Set the locked flag. */
756
- setLocked(locked: boolean): void;
757
- /**
758
- * Convert this annotation to a PdfDict suitable for embedding in a PDF.
759
- *
760
- * @param registry The object registry (used to register sub-objects).
761
- * @returns The annotation dictionary.
762
- */
763
- toDict(registry: PdfObjectRegistry): PdfDict;
764
- /**
765
- * Generate an appearance stream for this annotation.
766
- *
767
- * The base implementation returns `undefined`. Subclasses override
768
- * to produce proper visual appearance.
769
- *
770
- * @returns A PdfStream for the /AP /N entry, or undefined.
771
- */
772
- generateAppearance(): PdfStream | undefined;
773
- /**
774
- * Get the underlying dictionary (for internal use).
775
- * @internal
776
- */
777
- getDict(): PdfDict;
778
- }
779
- //#endregion
780
- //#region src/assets/svg/svgParser.d.ts
781
- /**
782
- * @module assets/svg/svgParser
783
- *
784
- * Parse SVG XML into an intermediate representation of drawing commands.
785
- *
786
- * This parser uses a simple regex / state-machine approach (no DOMParser)
787
- * so that it works in every JavaScript runtime (Node, Deno, Bun,
788
- * Cloudflare Workers, browsers).
789
- *
790
- * Supported SVG elements:
791
- * `<svg>`, `<g>`, `<path>`, `<rect>`, `<circle>`, `<ellipse>`,
792
- * `<line>`, `<polyline>`, `<polygon>`, `<text>` (basic).
793
- *
794
- * Supported path commands:
795
- * M, m, L, l, H, h, V, v, C, c, S, s, Q, q, T, t, A, a, Z, z.
796
- */
797
- /** A single drawing command produced from an SVG element. */
798
- interface SvgDrawCommand {
799
- type: 'moveTo' | 'lineTo' | 'curveTo' | 'quadCurveTo' | 'closePath' | 'rect' | 'circle' | 'ellipse' | 'arc';
800
- params: number[];
801
- }
802
- /** Parsed representation of an SVG element. */
803
- interface SvgElement {
804
- tag: string;
805
- attributes: Record<string, string>;
806
- children: SvgElement[];
807
- commands?: SvgDrawCommand[] | undefined;
808
- fill?: {
809
- r: number;
810
- g: number;
811
- b: number;
812
- a?: number | undefined;
813
- } | undefined;
814
- stroke?: {
815
- r: number;
816
- g: number;
817
- b: number;
818
- a?: number | undefined;
819
- } | undefined;
820
- strokeWidth?: number | undefined;
821
- transform?: [number, number, number, number, number, number] | undefined;
822
- opacity?: number | undefined;
823
- /** `evenodd` or `nonzero` (default). */
824
- fillRule?: 'nonzero' | 'evenodd' | undefined;
825
- /** SVG `stroke-linecap`: butt | round | square. */
826
- strokeLinecap?: 'butt' | 'round' | 'square' | undefined;
827
- /** SVG `stroke-linejoin`: miter | round | bevel. */
828
- strokeLinejoin?: 'miter' | 'round' | 'bevel' | undefined;
829
- /** SVG `stroke-miterlimit`. */
830
- strokeMiterlimit?: number | undefined;
831
- /** SVG `stroke-dasharray` as numeric array. */
832
- strokeDasharray?: number[] | undefined;
833
- /** SVG `stroke-dashoffset`. */
834
- strokeDashoffset?: number | undefined;
835
- /** Text content for `<text>` / `<tspan>` elements. */
836
- textContent?: string | undefined;
837
- /** Font family name. */
838
- fontFamily?: string | undefined;
839
- /** Font size in SVG user units. */
840
- fontSize?: number | undefined;
841
- /** Font weight (e.g. `bold`, `normal`, or numeric). */
842
- fontWeight?: string | undefined;
843
- /** Font style (e.g. `italic`, `normal`). */
844
- fontStyle?: string | undefined;
845
- /** Text anchor: start | middle | end. */
846
- textAnchor?: 'start' | 'middle' | 'end' | undefined;
847
- }
848
- declare function parseSvgColor(colorStr: string): {
849
- r: number;
850
- g: number;
851
- b: number;
852
- a?: number | undefined;
853
- } | undefined;
854
- /**
855
- * Parse an SVG `transform` attribute into a 2D affine matrix.
856
- *
857
- * Returns `[a, b, c, d, e, f]` representing:
858
- * ```
859
- * [ a c e ]
860
- * [ b d f ]
861
- * [ 0 0 1 ]
862
- * ```
863
- *
864
- * Supports: `matrix`, `translate`, `scale`, `rotate`, `skewX`, `skewY`.
865
- * Multiple transforms are composed left-to-right.
866
- */
867
- declare function parseSvgTransform(transformStr: string): [number, number, number, number, number, number];
868
- /**
869
- * Parse an SVG path `d` attribute string into an array of drawing commands.
870
- *
871
- * Supports all SVG path commands (absolute and relative):
872
- * M, L, H, V, C, S, Q, T, A, Z.
873
- */
874
- declare function parseSvgPath(d: string): SvgDrawCommand[];
875
- /**
876
- * Parse an SVG string into an {@link SvgElement} tree.
877
- *
878
- * The returned element represents the root `<svg>` element (or a
879
- * synthetic root if the input contains multiple top-level elements).
880
- */
881
- declare function parseSvg(svgString: string): SvgElement;
882
- //#endregion
883
- //#region src/assets/svg/svgToPdf.d.ts
884
- /** Options for rendering an SVG onto a PDF page. */
885
- interface SvgRenderOptions {
886
- /** Rendered width in PDF points. */
887
- width?: number | undefined;
888
- /** Rendered height in PDF points. */
889
- height?: number | undefined;
890
- /** X offset in PDF points. */
891
- x?: number | undefined;
892
- /** Y offset in PDF points (bottom of the SVG). */
893
- y?: number | undefined;
894
- /** Whether to preserve the aspect ratio of the SVG. */
895
- preserveAspectRatio?: boolean | undefined;
896
- }
897
- /**
898
- * Convert an SVG element tree into PDF content stream operators.
899
- *
900
- * The returned string can be injected directly into a PDF page's
901
- * content stream.
902
- */
903
- declare function svgToPdfOperators(element: SvgElement, options?: SvgRenderOptions): string;
904
- /**
905
- * Draw an SVG string onto a PDF page.
906
- *
907
- * Parses the SVG, converts it to PDF operators, and appends them
908
- * to the page's content stream.
909
- */
910
- declare function drawSvgOnPage(page: PdfPage, svgString: string, options?: SvgRenderOptions): void;
911
- //#endregion
912
- //#region src/layers/optionalContent.d.ts
913
- /**
914
- * Represents a single optional content group (layer) in a PDF.
915
- *
916
- * Each layer has a name and a default visibility state. Content
917
- * can be associated with a layer using the `BDC`/`EMC` marked-content
918
- * operators in the content stream.
919
- */
920
- declare class PdfLayer {
921
- readonly name: string;
922
- private visible;
923
- private ref;
924
- constructor(name: string, visible?: boolean);
925
- /** Check whether this layer is visible by default. */
926
- isVisible(): boolean;
927
- /** Set the default visibility of this layer. */
928
- setVisible(visible: boolean): void;
929
- /** Get the layer name. */
930
- getName(): string;
931
- /**
932
- * Get the indirect reference for this layer's OCG dictionary.
933
- * Only available after `toDict()` has been called.
934
- */
935
- getRef(): PdfRef | undefined;
936
- /**
937
- * Serialize this layer as an OCG dictionary and register it in the
938
- * object registry.
939
- *
940
- * @param registry The PDF object registry.
941
- * @returns The indirect reference to the OCG dictionary.
942
- */
943
- toDict(registry: PdfObjectRegistry): PdfRef;
944
- /**
945
- * Parse a PdfLayer from an OCG dictionary.
946
- *
947
- * @param dict The OCG dictionary.
948
- * @returns A PdfLayer instance.
949
- */
950
- static fromDict(dict: PdfDict): PdfLayer;
951
- }
952
- /**
953
- * Manages a collection of optional content groups (layers) for a PDF
954
- * document.
955
- *
956
- * Provides methods to add, remove, and query layers, and to serialize
957
- * the `/OCProperties` dictionary that goes into the catalog.
958
- */
959
- declare class PdfLayerManager {
960
- private layers;
961
- /**
962
- * Add a new layer.
963
- *
964
- * @param name The display name for the layer.
965
- * @param visible Whether the layer is visible by default.
966
- * @returns The newly created layer.
967
- */
968
- addLayer(name: string, visible?: boolean): PdfLayer;
969
- /**
970
- * Get a layer by name.
971
- *
972
- * @param name The layer name.
973
- * @returns The layer, or `undefined` if not found.
974
- */
975
- getLayer(name: string): PdfLayer | undefined;
976
- /**
977
- * Get all layers.
978
- *
979
- * @returns A copy of the layers array.
980
- */
981
- getLayers(): PdfLayer[];
982
- /**
983
- * Remove a layer by name.
984
- *
985
- * @param name The layer name.
986
- */
987
- removeLayer(name: string): void;
988
- /**
989
- * Build the `/OCProperties` dictionary for the document catalog.
990
- *
991
- * This dictionary describes all optional content groups and their
992
- * default configurations.
993
- *
994
- * @param registry The PDF object registry.
995
- * @returns The `/OCProperties` dictionary (not indirect).
996
- */
997
- toOCProperties(registry: PdfObjectRegistry): PdfDict;
998
- /**
999
- * Parse a PdfLayerManager from an `/OCProperties` dictionary.
1000
- *
1001
- * @param dict The `/OCProperties` dictionary from the catalog.
1002
- * @param resolver A function that resolves indirect references.
1003
- * @returns A PdfLayerManager instance.
1004
- */
1005
- static fromDict(dict: PdfDict, resolver: (ref: PdfRef) => PdfObject): PdfLayerManager;
1006
- }
1007
- /**
1008
- * Generate the PDF operator to begin optional content for a layer.
1009
- *
1010
- * This produces a `BDC` (begin marked-content with properties)
1011
- * operator that activates the given layer.
1012
- *
1013
- * @param layer The layer to activate.
1014
- * @returns The PDF operator string: `/OC /LayerName BDC\n`
1015
- */
1016
- declare function beginLayerContent(layer: PdfLayer): string;
1017
- /**
1018
- * Generate the PDF operator to end optional content.
1019
- *
1020
- * @returns The PDF operator string: `EMC\n`
1021
- */
1022
- declare function endLayerContent(): string;
1023
- //#endregion
1024
- //#region src/core/redaction.d.ts
1025
- /** Options for marking a region for redaction. */
1026
- interface RedactionOptions {
1027
- /** The rectangle to redact: [x, y, width, height]. */
1028
- rect: [number, number, number, number];
1029
- /** Optional text to overlay on the redacted area. */
1030
- overlayText?: string | undefined;
1031
- /** Colour for the redaction rectangle (default: black). */
1032
- color?: {
1033
- r: number;
1034
- g: number;
1035
- b: number;
1036
- } | undefined;
1037
- }
1038
- /** Redaction mark stored on a page. */
1039
- interface RedactionMark {
1040
- rect: [number, number, number, number];
1041
- overlayText?: string | undefined;
1042
- color: {
1043
- r: number;
1044
- g: number;
1045
- b: number;
1046
- };
1047
- }
1048
- /**
1049
- * Mark a rectangular region on a page for redaction.
1050
- *
1051
- * This does not immediately modify the page. Call
1052
- * {@link applyRedactions} to draw the redaction rectangles.
1053
- *
1054
- * @param page The page to mark.
1055
- * @param options The redaction options.
1056
- */
1057
- declare function markForRedaction(page: PdfPage, options: RedactionOptions): void;
1058
- /**
1059
- * Apply all pending redactions across all pages in a document.
1060
- *
1061
- * For each redaction mark, this draws an opaque filled rectangle
1062
- * over the marked region. If overlay text is specified, it is
1063
- * drawn on top of the rectangle in a contrasting colour.
1064
- *
1065
- * @param doc The PDF document.
1066
- */
1067
- declare function applyRedactions(doc: PdfDocument): void;
1068
- /**
1069
- * Get the pending redaction marks for a page.
1070
- *
1071
- * @param page The page to query.
1072
- * @returns An array of redaction marks, or an empty array.
1073
- */
1074
- declare function getRedactionMarks(page: PdfPage): readonly RedactionMark[];
1075
- //#endregion
1076
- //#region src/core/pdfEmbed.d.ts
1077
- /**
1078
- * Handle for a page that has been embedded as a Form XObject.
1079
- *
1080
- * Returned by `PdfDocument.embedPdf()` and `PdfDocument.embedPage()`.
1081
- * Pass it to `PdfPage.drawPage()` to paint the embedded page.
1082
- */
1083
- interface EmbeddedPdfPage {
1084
- /** XObject resource name (e.g. `'XF1'`). */
1085
- readonly name: string;
1086
- /** Indirect reference to the Form XObject in the target registry. */
1087
- readonly ref: PdfRef;
1088
- /** Original page width in points. */
1089
- readonly width: number;
1090
- /** Original page height in points. */
1091
- readonly height: number;
1092
- /**
1093
- * Return the dimensions after applying a uniform scale factor.
1094
- *
1095
- * @param factor Scale factor (e.g. `0.5` for half size).
1096
- */
1097
- scale(factor: number): {
1098
- width: number;
1099
- height: number;
1100
- };
1101
- /**
1102
- * Compute dimensions that fit within the given maximum size while
1103
- * preserving the original aspect ratio.
1104
- *
1105
- * @param maxW Maximum width.
1106
- * @param maxH Maximum height.
1107
- */
1108
- scaleToFit(maxW: number, maxH: number): {
1109
- width: number;
1110
- height: number;
1111
- };
1112
- }
1113
- /**
1114
- * Options for {@link PdfPage.drawPage}.
1115
- */
1116
- interface DrawPageOptions {
1117
- /** X coordinate of the lower-left corner. */
1118
- x?: number | undefined;
1119
- /** Y coordinate of the lower-left corner. */
1120
- y?: number | undefined;
1121
- /** Rendered width (defaults to the embedded page's original width). */
1122
- width?: number | undefined;
1123
- /** Rendered height (defaults to the embedded page's original height). */
1124
- height?: number | undefined;
1125
- /** Rotation angle. */
1126
- rotate?: {
1127
- type: 'degrees' | 'radians';
1128
- value: number;
1129
- } | undefined;
1130
- /** Opacity `[0, 1]`. */
1131
- opacity?: number | undefined;
1132
- /** Blend mode for compositing. */
1133
- blendMode?: BlendMode | undefined;
1134
- /** Horizontal skew angle. */
1135
- xSkew?: {
1136
- type: 'degrees' | 'radians';
1137
- value: number;
1138
- } | undefined;
1139
- /** Vertical skew angle. */
1140
- ySkew?: {
1141
- type: 'degrees' | 'radians';
1142
- value: number;
1143
- } | undefined;
1144
- }
1145
- /**
1146
- * Options for embedding a page as a Form XObject.
1147
- */
1148
- interface EmbedPageOptions {
1149
- /**
1150
- * Clip the embedded page to a sub-region (bounding box).
1151
- * Coordinates are in the source page's coordinate system.
1152
- */
1153
- boundingBox?: {
1154
- x: number;
1155
- y: number;
1156
- width: number;
1157
- height: number;
1158
- } | undefined;
1159
- /**
1160
- * Apply an affine transformation matrix to the Form XObject.
1161
- * The six values correspond to `[a, b, c, d, tx, ty]` in the
1162
- * standard 3x3 PDF transformation matrix.
1163
- */
1164
- transformationMatrix?: [number, number, number, number, number, number] | undefined;
1165
- }
1166
- /**
1167
- * Embed a single page as a Form XObject in the target registry.
1168
- *
1169
- * The page's content stream(s) are decoded and concatenated. The
1170
- * page's resources are deep-cloned into the target registry. The
1171
- * result is a PdfStream of Subtype /Form registered in the target.
1172
- *
1173
- * @param page The source PdfPage to embed.
1174
- * @param sourceRegistry The source document's object registry.
1175
- * @param targetRegistry The target document's object registry.
1176
- * @param xObjectName The resource name to assign (e.g. `'XF1'`).
1177
- * @returns An EmbeddedPdfPage handle.
1178
- */
1179
- declare function embedPageAsFormXObject(page: PdfPage, sourceRegistry: PdfObjectRegistry, targetRegistry: PdfObjectRegistry, xObjectName: string, options?: EmbedPageOptions): EmbeddedPdfPage;
1180
- //#endregion
1181
- //#region src/core/patterns.d.ts
1182
- /**
1183
- * A colour stop in a gradient, specifying the position (0..1) and colour.
1184
- */
1185
- interface ColorStop {
1186
- readonly offset: number;
1187
- readonly color: Color;
1188
- }
1189
- /**
1190
- * Options for creating a linear gradient (axial shading, ShadingType 2).
1191
- */
1192
- interface LinearGradientOptions {
1193
- /** Start X coordinate. */
1194
- readonly x1: number;
1195
- /** Start Y coordinate. */
1196
- readonly y1: number;
1197
- /** End X coordinate. */
1198
- readonly x2: number;
1199
- /** End Y coordinate. */
1200
- readonly y2: number;
1201
- /**
1202
- * Colour stops. Each element is either a bare {@link Color} (positions
1203
- * are distributed evenly) or a {@link ColorStop} with an explicit offset.
1204
- */
1205
- readonly stops: readonly (Color | ColorStop)[];
1206
- /**
1207
- * Whether to extend the gradient beyond the start and end points.
1208
- * Default: `true`.
1209
- */
1210
- readonly extend?: boolean;
1211
- }
1212
- /**
1213
- * Options for creating a radial gradient (radial shading, ShadingType 3).
1214
- */
1215
- interface RadialGradientOptions {
1216
- /** Centre X of the start circle. */
1217
- readonly x0: number;
1218
- /** Centre Y of the start circle. */
1219
- readonly y0: number;
1220
- /** Radius of the start circle. */
1221
- readonly r0: number;
1222
- /** Centre X of the end circle. */
1223
- readonly x1: number;
1224
- /** Centre Y of the end circle. */
1225
- readonly y1: number;
1226
- /** Radius of the end circle. */
1227
- readonly r1: number;
1228
- /**
1229
- * Colour stops (same semantics as {@link LinearGradientOptions.stops}).
1230
- */
1231
- readonly stops: readonly (Color | ColorStop)[];
1232
- /**
1233
- * Whether to extend the gradient beyond the start and end circles.
1234
- * Default: `true`.
1235
- */
1236
- readonly extend?: boolean;
1237
- }
1238
- /**
1239
- * Options for creating a tiling pattern (PatternType 1).
1240
- */
1241
- interface TilingPatternOptions {
1242
- /** Width of one tile in user-space units. */
1243
- readonly width: number;
1244
- /** Height of one tile in user-space units. */
1245
- readonly height: number;
1246
- /**
1247
- * Paint type.
1248
- * - `1` (default) — coloured: the pattern's content stream specifies
1249
- * its own colours.
1250
- * - `2` — uncoloured: colours are supplied when the pattern is painted.
1251
- */
1252
- readonly paintType?: 1 | 2;
1253
- /**
1254
- * Tiling type.
1255
- * - `1` (default) — constant spacing.
1256
- * - `2` — no distortion.
1257
- * - `3` — constant spacing and faster tiling.
1258
- */
1259
- readonly tilingType?: 1 | 2 | 3;
1260
- /** Raw PDF content-stream operators that paint one tile. */
1261
- readonly ops: string;
1262
- }
1263
- /**
1264
- * Descriptor for a gradient fill (linear or radial).
1265
- * This is a lightweight value object — actual PDF objects are created
1266
- * when {@link buildGradientObjects} is called.
1267
- */
1268
- interface GradientFill {
1269
- readonly kind: 'gradient';
1270
- readonly shadingType: 2 | 3;
1271
- readonly coords: readonly number[];
1272
- readonly normalizedStops: readonly NormalizedStop[];
1273
- readonly extend: boolean;
1274
- }
1275
- /**
1276
- * Descriptor for a radial gradient fill.
1277
- * Structurally identical to {@link GradientFill} but with `shadingType: 3`.
1278
- */
1279
- type RadialGradientFill = GradientFill & {
1280
- readonly shadingType: 3;
1281
- };
1282
- /**
1283
- * Descriptor for a tiling pattern fill.
1284
- * This is a lightweight value object — actual PDF objects are created
1285
- * when {@link buildPatternObjects} is called.
1286
- */
1287
- interface PatternFill {
1288
- readonly kind: 'pattern';
1289
- readonly width: number;
1290
- readonly height: number;
1291
- readonly paintType: 1 | 2;
1292
- readonly tilingType: 1 | 2 | 3;
1293
- readonly ops: string;
1294
- }
1295
- /** A normalised colour stop with explicit offset and RGB values. */
1296
- interface NormalizedStop {
1297
- readonly offset: number;
1298
- readonly r: number;
1299
- readonly g: number;
1300
- readonly b: number;
1301
- }
1302
- /**
1303
- * Create a linear (axial) gradient descriptor.
1304
- *
1305
- * The gradient runs from `(x1, y1)` to `(x2, y2)` through the given
1306
- * colour stops. By default the gradient extends beyond its endpoints.
1307
- *
1308
- * @param options Gradient parameters.
1309
- * @returns A {@link GradientFill} descriptor.
1310
- */
1311
- declare function linearGradient(options: LinearGradientOptions): GradientFill;
1312
- /**
1313
- * Create a radial gradient descriptor.
1314
- *
1315
- * The gradient interpolates between two circles: the start circle at
1316
- * `(x0, y0)` with radius `r0` and the end circle at `(x1, y1)` with
1317
- * radius `r1`.
1318
- *
1319
- * @param options Gradient parameters.
1320
- * @returns A {@link GradientFill} descriptor (with `shadingType: 3`).
1321
- */
1322
- declare function radialGradient(options: RadialGradientOptions): GradientFill;
1323
- /**
1324
- * Create a tiling pattern descriptor.
1325
- *
1326
- * @param options Pattern parameters including the tile content stream.
1327
- * @returns A {@link PatternFill} descriptor.
1328
- */
1329
- declare function tilingPattern(options: TilingPatternOptions): PatternFill;
1330
- /**
1331
- * Materialise a {@link GradientFill} descriptor into actual PDF objects
1332
- * in the given registry.
1333
- *
1334
- * @param gradient The gradient descriptor.
1335
- * @param registry The document's object registry.
1336
- * @returns An object with the pattern's indirect reference and a unique
1337
- * resource name.
1338
- */
1339
- declare function buildGradientObjects(gradient: GradientFill, registry: PdfObjectRegistry): {
1340
- patternRef: PdfRef;
1341
- patternName: string;
1342
- };
1343
- /**
1344
- * Materialise a {@link PatternFill} descriptor into actual PDF objects
1345
- * in the given registry.
1346
- *
1347
- * @param pattern The tiling pattern descriptor.
1348
- * @param registry The document's object registry.
1349
- * @returns An object with the pattern's indirect reference and a unique
1350
- * resource name.
1351
- */
1352
- declare function buildPatternObjects(pattern: PatternFill, registry: PdfObjectRegistry): {
1353
- patternRef: PdfRef;
1354
- patternName: string;
1355
- };
1356
- //#endregion
1357
- //#region src/barcode/qr.d.ts
1358
- /** Error correction level. */
1359
- type ErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H';
1360
- /** Options for rendering a QR code to PDF operators. */
1361
- interface QrCodeOptions {
1362
- /** Error correction level. Default: `'M'`. */
1363
- readonly errorCorrection?: ErrorCorrectionLevel;
1364
- /** Size of each module in PDF points. Default: `2`. */
1365
- readonly moduleSize?: number;
1366
- /** Number of quiet-zone modules around the code. Default: `4`. */
1367
- readonly quietZone?: number;
1368
- /** Foreground (dark module) colour. Default: black. */
1369
- readonly color?: Color;
1370
- /** Background colour. Default: white. */
1371
- readonly backgroundColor?: Color;
1372
- }
1373
- /** The result of QR code encoding — a boolean matrix. */
1374
- interface QrCodeMatrix {
1375
- /** Number of modules per side. */
1376
- readonly size: number;
1377
- /** Row-major boolean array. `true` = dark module. */
1378
- readonly modules: readonly boolean[];
1379
- /** QR version (1-40). */
1380
- readonly version: number;
1381
- }
1382
- /**
1383
- * Encode a string as a QR code matrix.
1384
- *
1385
- * @param data The string to encode.
1386
- * @param errorCorrection Error correction level (default: `'M'`).
1387
- * @returns A {@link QrCodeMatrix} with the encoded data.
1388
- */
1389
- declare function encodeQrCode(data: string, errorCorrection?: ErrorCorrectionLevel): QrCodeMatrix;
1390
- /**
1391
- * Convert a {@link QrCodeMatrix} to PDF content-stream operators.
1392
- *
1393
- * The QR code is rendered as filled rectangles (one per dark module),
1394
- * positioned at `(x, y)` in PDF user-space coordinates. The `y`
1395
- * coordinate refers to the **bottom-left** corner of the QR code.
1396
- *
1397
- * @param matrix The QR code matrix from {@link encodeQrCode}.
1398
- * @param x X position in PDF points.
1399
- * @param y Y position in PDF points.
1400
- * @param options Rendering options (module size, quiet zone, colours).
1401
- * @returns A string of PDF content-stream operators.
1402
- */
1403
- declare function qrCodeToOperators(matrix: QrCodeMatrix, x: number, y: number, options?: QrCodeOptions): string;
1404
- //#endregion
1405
- //#region src/layout/table.d.ts
1406
- /** A styled text run within a cell -- allows inline style variation. */
1407
- interface TextRun {
1408
- readonly text: string;
1409
- readonly fontSize?: number;
1410
- readonly color?: Color;
1411
- readonly fontName?: string;
1412
- }
1413
- /** Content that can appear in a cell: plain text, styled text runs, or a nested table. */
1414
- type CellContent = string | TextRun[] | NestedTableContent;
1415
- /** A nested table definition used as cell content. */
1416
- interface NestedTableContent {
1417
- readonly type: 'table';
1418
- readonly table: Omit<DrawTableOptions, 'x' | 'y'>;
1419
- }
1420
- /** Single table cell. */
1421
- interface TableCell {
1422
- readonly content: CellContent;
1423
- readonly colSpan?: number;
1424
- readonly rowSpan?: number;
1425
- readonly backgroundColor?: Color;
1426
- readonly textColor?: Color;
1427
- readonly fontSize?: number;
1428
- readonly align?: 'left' | 'center' | 'right';
1429
- readonly verticalAlign?: 'top' | 'middle' | 'bottom';
1430
- readonly padding?: number | {
1431
- top?: number;
1432
- right?: number;
1433
- bottom?: number;
1434
- left?: number;
1435
- };
1436
- /** Text overflow mode. Default: 'truncate'. */
1437
- readonly overflow?: 'wrap' | 'truncate' | 'ellipsis' | 'shrink';
1438
- }
1439
- /** Table row. */
1440
- interface TableRow {
1441
- readonly cells: readonly (TableCell | string)[];
1442
- readonly height?: number;
1443
- readonly backgroundColor?: Color;
1444
- }
1445
- /** Column definition. */
1446
- interface TableColumn {
1447
- /** Fixed width in points. */
1448
- readonly width?: number;
1449
- /** Percentage of table width (e.g., '30%'). */
1450
- readonly percentage?: string;
1451
- /** Flex weight (like CSS flex-grow). Default: 1 when no width/percentage. */
1452
- readonly flex?: number;
1453
- /** Auto-fit: measure content and use minimum needed width. */
1454
- readonly autoFit?: boolean;
1455
- readonly minWidth?: number;
1456
- readonly maxWidth?: number;
1457
- readonly align?: 'left' | 'center' | 'right';
1458
- }
1459
- /** Full table configuration. */
1460
- interface DrawTableOptions {
1461
- readonly x: number;
1462
- readonly y: number;
1463
- readonly width: number;
1464
- readonly rows: readonly TableRow[];
1465
- readonly columns?: readonly TableColumn[];
1466
- /** PDF font resource name, default 'Helvetica'. */
1467
- readonly fontName?: string;
1468
- /** Default font size in points, default 12. */
1469
- readonly fontSize?: number;
1470
- readonly textColor?: Color;
1471
- readonly borderColor?: Color;
1472
- /** Border line width in points, default 0.5. */
1473
- readonly borderWidth?: number;
1474
- /** Number of header rows (reserved for future page-break support). */
1475
- readonly headerRows?: number;
1476
- /** Default cell padding in points, default 4. */
1477
- readonly padding?: number;
1478
- /** Alternating row background colors [even, odd]. */
1479
- readonly alternateRowColors?: readonly [Color, Color];
1480
- /** Header background color (overrides alternateRowColors for header rows). */
1481
- readonly headerBackgroundColor?: Color;
1482
- /** Header text color. */
1483
- readonly headerTextColor?: Color;
1484
- }
1485
- /** Result of table rendering. */
1486
- interface TableRenderResult {
1487
- readonly width: number;
1488
- readonly height: number;
1489
- readonly rowHeights: readonly number[];
1490
- readonly columnWidths: readonly number[];
1491
- readonly pagesUsed: number;
1492
- }
1493
- /** Content for a single page in a multi-page table render. */
1494
- interface PageContent {
1495
- readonly ops: string;
1496
- readonly pageIndex: number;
1497
- }
1498
- /** Result of multi-page table rendering. */
1499
- interface MultiPageTableResult {
1500
- readonly pages: readonly PageContent[];
1501
- readonly result: TableRenderResult;
1502
- }
1503
- declare function renderTable(options: DrawTableOptions): {
1504
- ops: string;
1505
- result: TableRenderResult;
1506
- };
1507
- /**
1508
- * Render a table across multiple pages, breaking rows when content
1509
- * would exceed the available vertical space.
1510
- *
1511
- * Header rows (specified by `options.headerRows`) are repeated at the
1512
- * top of each new page. Rows are never split across pages.
1513
- */
1514
- declare function renderMultiPageTable(options: DrawTableOptions, bottomMargin?: number): MultiPageTableResult;
1515
- //#endregion
1516
- //#region src/core/pdfPage.d.ts
1517
- /** Pre-defined page sizes as `[width, height]` tuples in PDF points. */
1518
- declare const PageSizes: {
1519
- readonly '4A0': readonly [4767.87, 6740.79];
1520
- readonly '2A0': readonly [3370.39, 4767.87];
1521
- readonly A0: readonly [2383.94, 3370.39];
1522
- readonly A1: readonly [1683.78, 2383.94];
1523
- readonly A2: readonly [1190.55, 1683.78];
1524
- readonly A3: readonly [841.89, 1190.55];
1525
- readonly A4: readonly [595.28, 841.89];
1526
- readonly A5: readonly [419.53, 595.28];
1527
- readonly A6: readonly [297.64, 419.53];
1528
- readonly A7: readonly [209.76, 297.64];
1529
- readonly A8: readonly [147.4, 209.76];
1530
- readonly A9: readonly [104.88, 147.4];
1531
- readonly A10: readonly [73.7, 104.88];
1532
- readonly B0: readonly [2834.65, 4008.19];
1533
- readonly B1: readonly [2004.09, 2834.65];
1534
- readonly B2: readonly [1417.32, 2004.09];
1535
- readonly B3: readonly [1000.63, 1417.32];
1536
- readonly B4: readonly [708.66, 1000.63];
1537
- readonly B5: readonly [498.9, 708.66];
1538
- readonly B6: readonly [354.33, 498.9];
1539
- readonly B7: readonly [249.45, 354.33];
1540
- readonly B8: readonly [175.75, 249.45];
1541
- readonly B9: readonly [124.72, 175.75];
1542
- readonly B10: readonly [87.87, 124.72];
1543
- readonly Letter: readonly [612, 792];
1544
- readonly Legal: readonly [612, 1008];
1545
- readonly Tabloid: readonly [792, 1224];
1546
- readonly Ledger: readonly [1224, 792];
1547
- readonly Executive: readonly [521.86, 756];
1548
- readonly Folio: readonly [612, 936];
1549
- readonly C0: readonly [2599.37, 3676.54];
1550
- readonly C1: readonly [1836.85, 2599.37];
1551
- readonly C2: readonly [1298.27, 1836.85];
1552
- readonly C3: readonly [918.43, 1298.27];
1553
- readonly C4: readonly [649.13, 918.43];
1554
- readonly C5: readonly [459.21, 649.13];
1555
- readonly C6: readonly [323.15, 459.21];
1556
- readonly C7: readonly [229.61, 323.15];
1557
- readonly C8: readonly [161.57, 229.61];
1558
- readonly C9: readonly [113.39, 161.57];
1559
- readonly C10: readonly [79.37, 113.39];
1560
- readonly RA0: readonly [2437.8, 3458.27];
1561
- readonly RA1: readonly [1729.13, 2437.8];
1562
- readonly RA2: readonly [1218.9, 1729.13];
1563
- readonly RA3: readonly [864.57, 1218.9];
1564
- readonly RA4: readonly [609.45, 864.57];
1565
- readonly SRA0: readonly [2551.18, 3628.35];
1566
- readonly SRA1: readonly [1814.17, 2551.18];
1567
- readonly SRA2: readonly [1275.59, 1814.17];
1568
- readonly SRA3: readonly [907.09, 1275.59];
1569
- readonly SRA4: readonly [637.8, 907.09];
1570
- };
1571
- /** Type for a page-size input: a `[width, height]` tuple or `{ width, height }` object. */
1572
- type PageSize = readonly [width: number, height: number] | {
1573
- readonly width: number;
1574
- readonly height: number;
1575
- };
1576
- /** Options for {@link PdfPage.drawText}. */
1577
- interface DrawTextOptions {
1578
- /** X coordinate. */
1579
- x?: number | undefined;
1580
- /** Y coordinate. */
1581
- y?: number | undefined;
1582
- /**
1583
- * Font to use for rendering.
1584
- *
1585
- * Accepts either a {@link FontRef} object (returned by `doc.embedFont()`)
1586
- * or a font resource name string (e.g. `'F1'`).
1587
- *
1588
- * When a `FontRef` is provided, its `name` property is used as the
1589
- * resource name and its CID encoder (if any) is used automatically.
1590
- */
1591
- font?: FontRef | string | undefined;
1592
- /** Font size in points. */
1593
- size?: number | undefined;
1594
- /** Text colour. Defaults to black. */
1595
- color?: Color | undefined;
1596
- /** Rotation angle. */
1597
- rotate?: Angle | undefined;
1598
- /** Line height for multi-line text. */
1599
- lineHeight?: number | undefined;
1600
- /** Opacity `[0, 1]`. */
1601
- opacity?: number | undefined;
1602
- /** Blend mode for compositing. */
1603
- blendMode?: BlendMode | undefined;
1604
- /** Text rendering mode (fill, stroke, invisible, clip, etc.). */
1605
- renderingMode?: TextRenderingMode | undefined;
1606
- /** Horizontal skew angle (italic-like effect). */
1607
- xSkew?: Angle | undefined;
1608
- /** Vertical skew angle. */
1609
- ySkew?: Angle | undefined;
1610
- /**
1611
- * Maximum width in points before text is automatically wrapped.
1612
- *
1613
- * When provided with a {@link FontRef} font (which has `widthOfTextAtSize`),
1614
- * the text is broken at word boundaries to fit within this width.
1615
- * If a single word exceeds `maxWidth`, it is broken at character level.
1616
- *
1617
- * When the font is a plain string (no measurement available), this
1618
- * option is ignored.
1619
- */
1620
- maxWidth?: number | undefined;
1621
- /**
1622
- * Characters at which text may be broken when wrapping.
1623
- *
1624
- * Defaults to `[' ']` (space only). Pass additional characters such as
1625
- * `[' ', '-', '/']` to allow breaks at hyphens, slashes, etc.
1626
- *
1627
- * The break character is kept at the **end** of the preceding line
1628
- * (e.g. `'hello-'` / `'world'`), except for space which is consumed
1629
- * as in the default behaviour.
1630
- */
1631
- wordBreaks?: string[] | undefined;
1632
- }
1633
- /** Options for {@link PdfPage.drawImage}. */
1634
- interface DrawImageOptions {
1635
- /** X coordinate of the lower-left corner. */
1636
- x?: number | undefined;
1637
- /** Y coordinate of the lower-left corner. */
1638
- y?: number | undefined;
1639
- /** Rendered width. */
1640
- width?: number | undefined;
1641
- /** Rendered height. */
1642
- height?: number | undefined;
1643
- /** Rotation angle. */
1644
- rotate?: Angle | undefined;
1645
- /** Opacity `[0, 1]`. */
1646
- opacity?: number | undefined;
1647
- /** Blend mode for compositing. */
1648
- blendMode?: BlendMode | undefined;
1649
- /** Horizontal skew angle. */
1650
- xSkew?: Angle | undefined;
1651
- /** Vertical skew angle. */
1652
- ySkew?: Angle | undefined;
1653
- }
1654
- /** Options for {@link PdfPage.drawRectangle}. */
1655
- interface DrawRectangleOptions {
1656
- /** X coordinate. */
1657
- x?: number | undefined;
1658
- /** Y coordinate. */
1659
- y?: number | undefined;
1660
- /** Rectangle width. */
1661
- width?: number | undefined;
1662
- /** Rectangle height. */
1663
- height?: number | undefined;
1664
- /** Fill colour. Set to `undefined` for no fill. */
1665
- color?: Color | undefined;
1666
- /** Border (stroke) colour. Set to `undefined` for no stroke. */
1667
- borderColor?: Color | undefined;
1668
- /** Border width in points. */
1669
- borderWidth?: number | undefined;
1670
- /** Rotation angle. */
1671
- rotate?: Angle | undefined;
1672
- /** Opacity `[0, 1]`. */
1673
- opacity?: number | undefined;
1674
- /** Blend mode for compositing. */
1675
- blendMode?: BlendMode | undefined;
1676
- /** Horizontal skew angle. */
1677
- xSkew?: Angle | undefined;
1678
- /** Vertical skew angle. */
1679
- ySkew?: Angle | undefined;
1680
- /** Dash pattern for border `[dashLen, gapLen, ...]`. */
1681
- borderDashArray?: number[] | undefined;
1682
- /** Dash phase offset for border. */
1683
- borderDashPhase?: number | undefined;
1684
- /** Line cap style for border (0 = butt, 1 = round, 2 = projecting square). */
1685
- borderLineCap?: 0 | 1 | 2 | undefined;
1686
- /** Border stroke opacity `[0, 1]`, separate from fill opacity. */
1687
- borderOpacity?: number | undefined;
1688
- }
1689
- /** Options for {@link PdfPage.drawLine}. */
1690
- interface DrawLineOptions {
1691
- /** Start point. */
1692
- start: {
1693
- x: number;
1694
- y: number;
1695
- };
1696
- /** End point. */
1697
- end: {
1698
- x: number;
1699
- y: number;
1700
- };
1701
- /** Line colour. */
1702
- color?: Color | undefined;
1703
- /** Line width. */
1704
- thickness?: number | undefined;
1705
- /** Dash pattern `[dashLength, gapLength]`. */
1706
- dashArray?: number[] | undefined;
1707
- /** Dash phase. */
1708
- dashPhase?: number | undefined;
1709
- /** Opacity `[0, 1]`. */
1710
- opacity?: number | undefined;
1711
- /** Blend mode for compositing. */
1712
- blendMode?: BlendMode | undefined;
1713
- }
1714
- /** Options for {@link PdfPage.drawCircle}. */
1715
- interface DrawCircleOptions {
1716
- /** Centre x. */
1717
- x?: number | undefined;
1718
- /** Centre y. */
1719
- y?: number | undefined;
1720
- /** Radius of the circle. */
1721
- radius?: number | undefined;
1722
- /**
1723
- * Radius of the circle.
1724
- * @deprecated Use `radius` instead.
1725
- */
1726
- size?: number | undefined;
1727
- /** Fill colour. */
1728
- color?: Color | undefined;
1729
- /** Border colour. */
1730
- borderColor?: Color | undefined;
1731
- /** Border width. */
1732
- borderWidth?: number | undefined;
1733
- /** Opacity. */
1734
- opacity?: number | undefined;
1735
- /** Blend mode for compositing. */
1736
- blendMode?: BlendMode | undefined;
1737
- /** Dash pattern for border. */
1738
- borderDashArray?: number[] | undefined;
1739
- /** Dash phase offset for border. */
1740
- borderDashPhase?: number | undefined;
1741
- /** Line cap style for border. */
1742
- borderLineCap?: 0 | 1 | 2 | undefined;
1743
- /** Border stroke opacity `[0, 1]`. */
1744
- borderOpacity?: number | undefined;
1745
- }
1746
- /** Options for {@link PdfPage.drawEllipse}. */
1747
- interface DrawEllipseOptions {
1748
- /** Centre x. */
1749
- x?: number | undefined;
1750
- /** Centre y. */
1751
- y?: number | undefined;
1752
- /** Horizontal radius. */
1753
- xScale?: number | undefined;
1754
- /** Vertical radius. */
1755
- yScale?: number | undefined;
1756
- /** Fill colour. */
1757
- color?: Color | undefined;
1758
- /** Border colour. */
1759
- borderColor?: Color | undefined;
1760
- /** Border width. */
1761
- borderWidth?: number | undefined;
1762
- /** Opacity `[0, 1]`. */
1763
- opacity?: number | undefined;
1764
- /** Blend mode for compositing. */
1765
- blendMode?: BlendMode | undefined;
1766
- /** Dash pattern for border. */
1767
- borderDashArray?: number[] | undefined;
1768
- /** Dash phase offset for border. */
1769
- borderDashPhase?: number | undefined;
1770
- /** Line cap style for border. */
1771
- borderLineCap?: 0 | 1 | 2 | undefined;
1772
- /** Border stroke opacity `[0, 1]`. */
1773
- borderOpacity?: number | undefined;
1774
- }
1775
- /** Options for {@link PdfPage.drawSvgPath}. */
1776
- interface DrawSvgPathOptions {
1777
- /** X translation (PDF coordinates). */
1778
- x?: number | undefined;
1779
- /** Y translation (PDF coordinates). */
1780
- y?: number | undefined;
1781
- /** Uniform scale factor applied to the path. */
1782
- scale?: number | undefined;
1783
- /** Fill colour. */
1784
- color?: Color | undefined;
1785
- /** Border (stroke) colour. */
1786
- borderColor?: Color | undefined;
1787
- /** Border width in points. */
1788
- borderWidth?: number | undefined;
1789
- /** Opacity `[0, 1]`. */
1790
- opacity?: number | undefined;
1791
- /** Blend mode for compositing. */
1792
- blendMode?: BlendMode | undefined;
1793
- /** Dash pattern for border. */
1794
- borderDashArray?: number[] | undefined;
1795
- /** Dash phase offset for border. */
1796
- borderDashPhase?: number | undefined;
1797
- /** Line cap style for border. */
1798
- borderLineCap?: 0 | 1 | 2 | undefined;
1799
- /** Border stroke opacity `[0, 1]`. */
1800
- borderOpacity?: number | undefined;
1801
- }
1802
- /** Options for {@link PdfPage.drawQrCode}. */
1803
- interface DrawQrCodeOptions {
1804
- /** X coordinate (bottom-left of QR code). */
1805
- x?: number | undefined;
1806
- /** Y coordinate (bottom-left of QR code). */
1807
- y?: number | undefined;
1808
- /** Error correction level. Default: `'M'`. */
1809
- errorCorrection?: ErrorCorrectionLevel | undefined;
1810
- /** Size of each module in PDF points. Default: `2`. */
1811
- moduleSize?: number | undefined;
1812
- /** Number of quiet-zone modules around the code. Default: `4`. */
1813
- quietZone?: number | undefined;
1814
- /** Foreground (dark module) colour. Default: black. */
1815
- color?: Color | undefined;
1816
- /** Background colour. Default: white. */
1817
- backgroundColor?: Color | undefined;
1818
- }
1819
- /** Options for {@link PdfPage.drawSquare}. */
1820
- interface DrawSquareOptions {
1821
- /** X coordinate. */
1822
- x?: number | undefined;
1823
- /** Y coordinate. */
1824
- y?: number | undefined;
1825
- /** Side length of the square. Defaults to `100`. */
1826
- size?: number | undefined;
1827
- /** Fill colour. */
1828
- color?: Color | undefined;
1829
- /** Border (stroke) colour. */
1830
- borderColor?: Color | undefined;
1831
- /** Border width in points. */
1832
- borderWidth?: number | undefined;
1833
- /** Rotation angle. */
1834
- rotate?: Angle | undefined;
1835
- /** Opacity `[0, 1]`. */
1836
- opacity?: number | undefined;
1837
- /** Blend mode for compositing. */
1838
- blendMode?: BlendMode | undefined;
1839
- /** Horizontal skew angle. */
1840
- xSkew?: Angle | undefined;
1841
- /** Vertical skew angle. */
1842
- ySkew?: Angle | undefined;
1843
- /** Dash pattern for border. */
1844
- borderDashArray?: number[] | undefined;
1845
- /** Dash phase offset for border. */
1846
- borderDashPhase?: number | undefined;
1847
- /** Line cap style for border. */
1848
- borderLineCap?: 0 | 1 | 2 | undefined;
1849
- /** Border stroke opacity `[0, 1]`. */
1850
- borderOpacity?: number | undefined;
1851
- }
1852
- /** Opaque handle for a font that has been embedded in the document. */
1853
- interface FontRef {
1854
- /** Resource name used in content-stream operators (e.g. `F1`). */
1855
- readonly name: string;
1856
- /** Indirect reference to the font dictionary. */
1857
- readonly ref: PdfRef;
1858
- /**
1859
- * Compute the width of a text string at the given font size (in points).
1860
- * Available for both standard and TrueType fonts.
1861
- */
1862
- widthOfTextAtSize(text: string, size: number): number;
1863
- /**
1864
- * Compute the height of the font at the given size (ascender - descender).
1865
- * Available for both standard and TrueType fonts.
1866
- */
1867
- heightAtSize(size: number): number;
1868
- /**
1869
- * Whether this font uses CID (Identity-H) encoding.
1870
- * When true, text must be encoded as hex glyph IDs in content streams.
1871
- * @internal
1872
- */
1873
- readonly _isCIDFont?: boolean;
1874
- /**
1875
- * Encode text as a hex string of CID glyph IDs for content streams.
1876
- * Only present for CID (TrueType) fonts.
1877
- * @internal
1878
- */
1879
- _encodeText?(text: string): string;
1880
- /**
1881
- * Compute the font size needed to achieve a given height (ascender - descender).
1882
- * This is the inverse of `heightAtSize()`.
1883
- *
1884
- * @param height Desired height in points.
1885
- * @returns Font size in points.
1886
- */
1887
- sizeAtHeight?(height: number): number;
1888
- /**
1889
- * Return the set of Unicode codepoints supported by this font.
1890
- *
1891
- * For standard fonts, returns the WinAnsi character set.
1892
- * For embedded fonts, returns all codepoints in the cmap table.
1893
- *
1894
- * @returns Array of Unicode codepoint numbers.
1895
- */
1896
- getCharacterSet?(): number[];
1897
- }
1898
- /** Opaque handle for an image that has been embedded in the document. */
1899
- interface ImageRef {
1900
- /** Resource name used in content-stream operators (e.g. `Im1`). */
1901
- readonly name: string;
1902
- /** Indirect reference to the image XObject. */
1903
- readonly ref: PdfRef;
1904
- /** Intrinsic width in pixels. */
1905
- readonly width: number;
1906
- /** Intrinsic height in pixels. */
1907
- readonly height: number;
1908
- /**
1909
- * Return a new `{ width, height }` scaled by the given factor.
1910
- *
1911
- * @param factor Scale multiplier (e.g. `0.5` for half size).
1912
- */
1913
- scale(factor: number): {
1914
- width: number;
1915
- height: number;
1916
- };
1917
- /**
1918
- * Return a new `{ width, height }` that fits within the given bounds
1919
- * while preserving the aspect ratio.
1920
- *
1921
- * @param maxWidth Maximum allowed width.
1922
- * @param maxHeight Maximum allowed height.
1923
- */
1924
- scaleToFit(maxWidth: number, maxHeight: number): {
1925
- width: number;
1926
- height: number;
1927
- };
1928
- }
1929
- /**
1930
- * Options for transparency groups.
1931
- *
1932
- * Transparency groups allow a set of drawing operations to be composited
1933
- * as a single unit before being blended with the page content.
1934
- */
1935
- interface TransparencyGroupOptions {
1936
- /**
1937
- * When `true`, the group is composited against a fully transparent
1938
- * backdrop rather than the existing page content. Default: `true`.
1939
- */
1940
- isolated?: boolean;
1941
- /**
1942
- * When `true`, earlier objects in the group are knocked out (replaced)
1943
- * by later objects, rather than composited on top. Default: `false`.
1944
- */
1945
- knockout?: boolean;
1946
- /**
1947
- * Color space for the transparency group. Default: `'DeviceRGB'`.
1948
- */
1949
- colorSpace?: 'DeviceRGB' | 'DeviceCMYK' | 'DeviceGray';
1950
- }
1951
- /**
1952
- * Builder interface for constructing soft mask content.
1953
- *
1954
- * All drawing is in grayscale: `1` = fully opaque, `0` = fully transparent.
1955
- */
1956
- interface SoftMaskBuilder {
1957
- /**
1958
- * Draw a filled rectangle at the given position with the specified
1959
- * grayscale value (`0` = black/transparent, `1` = white/opaque).
1960
- */
1961
- drawRectangle(x: number, y: number, width: number, height: number, gray: number): void;
1962
- /**
1963
- * Draw a filled circle at the given center with the specified radius
1964
- * and grayscale value.
1965
- */
1966
- drawCircle(cx: number, cy: number, radius: number, gray: number): void;
1967
- /**
1968
- * Append raw PDF content-stream operators to the mask.
1969
- */
1970
- pushRawOperators(ops: string): void;
1971
- }
1972
- /**
1973
- * Opaque reference to a soft mask Form XObject.
1974
- *
1975
- * Created by {@link PdfDocument.createSoftMask} and consumed by
1976
- * {@link PdfPage.applySoftMask}.
1977
- */
1978
- interface SoftMaskRef {
1979
- readonly _tag: 'softMask';
1980
- readonly ref: PdfRef;
1981
- }
1982
- /**
1983
- * A single page in a PDF document.
1984
- *
1985
- * Drawing methods are synchronous and append PDF operators to an
1986
- * internal string buffer. The buffer is converted to a content stream
1987
- * when the document is saved.
1988
- */
1989
- declare class PdfPage {
1990
- /** Object registry for allocating refs. */
1991
- private readonly registry;
1992
- /** Content-stream operators accumulated so far. */
1993
- private ops;
1994
- /** Fonts referenced by this page — maps resource name → PdfRef. */
1995
- private readonly fonts;
1996
- /**
1997
- * CID font text encoders — maps resource name → encode function.
1998
- * Only present for TrueType (CIDFont Type 2) fonts.
1999
- * @internal
2000
- */
2001
- private readonly cidFontEncoders;
2002
- /** XObjects (images) referenced by this page. */
2003
- private readonly xObjects;
2004
- /**
2005
- * ExtGState dictionaries referenced by this page.
2006
- * Maps a resource name (e.g. `GS1`) to its indirect reference.
2007
- * Used for opacity and other graphics state parameters.
2008
- */
2009
- private readonly extGStates;
2010
- /**
2011
- * Pattern resources referenced by this page.
2012
- * Maps a resource name (e.g. `Pat5`) to its indirect reference.
2013
- * Used for gradient fills and tiling patterns.
2014
- */
2015
- private readonly patterns;
2016
- /**
2017
- * Counter for ExtGState resource names (`GS1`, `GS2`, ...).
2018
- */
2019
- private extGStateCounter;
2020
- /**
2021
- * Counter for transparency group XObject resource names (`TG1`, `TG2`, ...).
2022
- */
2023
- private transparencyGroupCounter;
2024
- /**
2025
- * Stack of transparency group state. Each entry records the ops length
2026
- * at the time `beginTransparencyGroup()` was called, plus the options.
2027
- */
2028
- private readonly transparencyGroupStack;
2029
- /**
2030
- * Cache mapping composite keys (opacity + blend mode) to their ExtGState
2031
- * resource names, so the same combination reuses the same graphics state
2032
- * dictionary.
2033
- */
2034
- private readonly extGStateCache;
2035
- /** Default font used by `drawText()` when no `font` option is provided. */
2036
- private _defaultFont?;
2037
- /** Default font size used by `drawText()` when no `size` option is provided. */
2038
- private _defaultFontSize?;
2039
- /** Default font colour used by `drawText()` when no `color` option is provided. */
2040
- private _defaultFontColor?;
2041
- /** Default line height used by `drawText()` when no `lineHeight` option is provided. */
2042
- private _defaultLineHeight?;
2043
- /** Current cursor X coordinate (used as fallback when x is not specified). */
2044
- private _cursorX;
2045
- /** Current cursor Y coordinate (used as fallback when y is not specified). */
2046
- private _cursorY;
2047
- /** Pre-allocated indirect reference for this page's /Page dictionary. */
2048
- readonly pageRef: PdfRef;
2049
- /** Pre-allocated indirect reference for this page's content stream. */
2050
- readonly contentStreamRef: PdfRef;
2051
- /**
2052
- * Page rotation in degrees (0, 90, 180, or 270).
2053
- * This is written to the /Rotate entry in the page dictionary at save time.
2054
- * @internal
2055
- */
2056
- private rotation;
2057
- /**
2058
- * Tab order for the page.
2059
- * - `'S'` — Structure order (follows the logical structure tree)
2060
- * - `'R'` — Row order
2061
- * - `'C'` — Column order
2062
- *
2063
- * Written to the /Tabs entry in the page dictionary at save time.
2064
- * PDF/UA requires `'S'` (structure order).
2065
- * @internal
2066
- */
2067
- private tabOrder;
2068
- /**
2069
- * Optional crop box `[llx, lly, urx, ury]`.
2070
- * When set, written to the /CropBox entry in the page dictionary at save time.
2071
- * @internal
2072
- */
2073
- private cropBox;
2074
- /**
2075
- * Optional bleed box `[llx, lly, urx, ury]`.
2076
- * When set, written to the /BleedBox entry in the page dictionary at save time.
2077
- * @internal
2078
- */
2079
- private bleedBox;
2080
- /**
2081
- * Optional art box `[llx, lly, urx, ury]`.
2082
- * When set, written to the /ArtBox entry in the page dictionary at save time.
2083
- * @internal
2084
- */
2085
- private artBox;
2086
- /**
2087
- * Optional trim box `[llx, lly, urx, ury]`.
2088
- * When set, written to the /TrimBox entry in the page dictionary at save time.
2089
- * @internal
2090
- */
2091
- private trimBox;
2092
- /**
2093
- * Mutable media box origin and dimensions. Initially set from constructor.
2094
- * @internal
2095
- */
2096
- private mediaX;
2097
- /** @internal */
2098
- private mediaY;
2099
- /** @internal */
2100
- private mediaWidth;
2101
- /** @internal */
2102
- private mediaHeight;
2103
- /** Original page width from construction time (used by resetSize). */
2104
- private readonly _originalWidth;
2105
- /** Original page height from construction time (used by resetSize). */
2106
- private readonly _originalHeight;
2107
- /**
2108
- * @internal Original content stream refs from a loaded PDF.
2109
- * These are indirect references to PdfStream objects already in the registry.
2110
- */
2111
- private _originalContentRefs;
2112
- /**
2113
- * @internal Original resources dictionary from a loaded PDF.
2114
- * Merged with new resources in `buildResources()`.
2115
- */
2116
- private _originalResources;
2117
- /**
2118
- * @internal Original annotation refs from a loaded PDF.
2119
- * Combined with new annotations in `finalize()`.
2120
- */
2121
- private _originalAnnotRefs;
2122
- constructor(/** Page width in points. */
2123
-
2124
- w: number, /** Page height in points. */
2125
-
2126
- h: number, /** Object registry for allocating refs. */
2127
-
2128
- registry: PdfObjectRegistry);
2129
- /**
2130
- * @internal Create a PdfPage pre-loaded with content from a parsed PDF.
2131
- *
2132
- * Unlike the normal constructor which creates a blank page, this factory
2133
- * preserves the original content streams, resources, annotations, and
2134
- * other page attributes from the parsed PDF.
2135
- */
2136
- static _fromParsed(width: number, height: number, registry: PdfObjectRegistry, opts: {
2137
- contentRefs?: PdfRef[] | undefined;
2138
- resources?: PdfDict | undefined;
2139
- rotation?: number | undefined;
2140
- cropBox?: [number, number, number, number] | undefined;
2141
- bleedBox?: [number, number, number, number] | undefined;
2142
- artBox?: [number, number, number, number] | undefined;
2143
- trimBox?: [number, number, number, number] | undefined;
2144
- annotRefs?: PdfRef[] | undefined;
2145
- }): PdfPage;
2146
- /** Page width in points. */
2147
- get width(): number;
2148
- /** Page height in points. */
2149
- get height(): number;
2150
- /** @internal Register a font resource on this page. */
2151
- registerFont(name: string, ref: PdfRef): void;
2152
- /**
2153
- * @internal Register a CID font encoder for a font resource on this page.
2154
- * When drawText is called with this font, text will be encoded using the
2155
- * provided encoder function (producing hex glyph IDs) instead of literal strings.
2156
- */
2157
- registerCIDFont(name: string, encoder: (text: string) => string): void;
2158
- /** @internal Register an image XObject resource on this page. */
2159
- registerXObject(name: string, ref: PdfRef): void;
2160
- /** @internal Register an ExtGState resource on this page. */
2161
- registerExtGState(name: string, ref: PdfRef): void;
2162
- /** @internal Register a Pattern resource on this page. */
2163
- registerPattern(name: string, ref: PdfRef): void;
2164
- /**
2165
- * Set the default font used by {@link drawText} when the `font` option
2166
- * is not provided.
2167
- *
2168
- * @param font A {@link FontRef} returned by `doc.embedFont()`.
2169
- */
2170
- setFont(font: FontRef): void;
2171
- /**
2172
- * Set the default font size (in points) used by {@link drawText} when
2173
- * the `size` option is not provided.
2174
- *
2175
- * @param size Font size in points.
2176
- */
2177
- setFontSize(size: number): void;
2178
- /**
2179
- * Set the default font colour used by {@link drawText} when the `color`
2180
- * option is not provided.
2181
- *
2182
- * @param color A {@link Color} value (e.g. from `rgb()`, `cmyk()`, etc.).
2183
- */
2184
- setFontColor(color: Color): void;
2185
- /**
2186
- * Set the default line height used by {@link drawText} when the
2187
- * `lineHeight` option is not provided.
2188
- *
2189
- * @param height Line height in points.
2190
- */
2191
- setLineHeight(height: number): void;
2192
- /**
2193
- * Get the current cursor position.
2194
- *
2195
- * @returns An object with `x` and `y` properties (in points).
2196
- */
2197
- getPosition(): {
2198
- x: number;
2199
- y: number;
2200
- };
2201
- /**
2202
- * Get the current cursor X coordinate.
2203
- *
2204
- * @returns The X coordinate in points.
2205
- */
2206
- getX(): number;
2207
- /**
2208
- * Get the current cursor Y coordinate.
2209
- *
2210
- * @returns The Y coordinate in points.
2211
- */
2212
- getY(): number;
2213
- /**
2214
- * Move the cursor to an absolute position.
2215
- *
2216
- * Drawing methods that accept optional `x` / `y` parameters will use the
2217
- * cursor position as a fallback when those parameters are omitted.
2218
- *
2219
- * @param x The X coordinate in points.
2220
- * @param y The Y coordinate in points.
2221
- */
2222
- moveTo(x: number, y: number): void;
2223
- /**
2224
- * Move the cursor upward by the given amount (increases Y).
2225
- *
2226
- * @param amount Distance in points.
2227
- */
2228
- moveUp(amount: number): void;
2229
- /**
2230
- * Move the cursor downward by the given amount (decreases Y).
2231
- *
2232
- * @param amount Distance in points.
2233
- */
2234
- moveDown(amount: number): void;
2235
- /**
2236
- * Move the cursor to the right by the given amount (increases X).
2237
- *
2238
- * @param amount Distance in points.
2239
- */
2240
- moveRight(amount: number): void;
2241
- /**
2242
- * Move the cursor to the left by the given amount (decreases X).
2243
- *
2244
- * @param amount Distance in points.
2245
- */
2246
- moveLeft(amount: number): void;
2247
- /**
2248
- * Reset the cursor position to `(0, 0)`.
2249
- */
2250
- resetPosition(): void;
2251
- /**
2252
- * Get or create an ExtGState resource for the given opacity and/or
2253
- * blend mode.
2254
- *
2255
- * Creates a PDF ExtGState dictionary with `/ca` + `/CA` (when opacity
2256
- * is less than 1) and `/BM` (when a non-Normal blend mode is specified).
2257
- * The dictionary is registered in the object registry and cached so that
2258
- * the same combination of parameters shares a single resource.
2259
- *
2260
- * @param opacity Opacity value in the range `[0, 1]` (optional).
2261
- * @param blendMode A PDF blend mode name (optional).
2262
- * @returns The resource name (e.g. `GS1`) to use in content stream operators.
2263
- * @internal
2264
- */
2265
- private getOrCreateExtGState;
2266
- /**
2267
- * Draw a text string at the specified position.
2268
- *
2269
- * @param text The text to render.
2270
- * @param options Position, font, size, colour, rotation.
2271
- */
2272
- drawText(text: string, options?: DrawTextOptions): void;
2273
- /**
2274
- * Draw an embedded image on this page.
2275
- *
2276
- * @param image Image reference returned by `doc.embedPng()` or
2277
- * `doc.embedJpeg()`.
2278
- * @param options Position, dimensions, rotation.
2279
- */
2280
- drawImage(image: ImageRef, options?: DrawImageOptions): void;
2281
- /**
2282
- * Draw an embedded PDF page (Form XObject) on this page.
2283
- *
2284
- * The embedded page is painted at the given position and scaled to the
2285
- * specified dimensions. If `width` or `height` is omitted, the
2286
- * original page dimensions are used.
2287
- *
2288
- * @param embeddedPage An embedded page returned by `doc.embedPdf()` or
2289
- * `doc.embedPage()`.
2290
- * @param options Position, dimensions, rotation, opacity.
2291
- *
2292
- * @example
2293
- * ```ts
2294
- * const [embedded] = await doc.embedPdf(otherPdfBytes, [0]);
2295
- * page.drawPage(embedded, { x: 50, y: 50, width: 300, height: 400 });
2296
- * ```
2297
- */
2298
- drawPage(embeddedPage: EmbeddedPdfPage, options?: DrawPageOptions): void;
2299
- /**
2300
- * Draw a rectangle.
2301
- *
2302
- * By default the rectangle is filled with black. Set `color` to
2303
- * `undefined` and provide `borderColor` for stroke-only.
2304
- */
2305
- drawRectangle(options?: DrawRectangleOptions): void;
2306
- /**
2307
- * Draw a square (convenience wrapper around {@link drawRectangle}).
2308
- *
2309
- * @param options Position, size, colours, rotation, opacity, blend mode.
2310
- */
2311
- drawSquare(options?: DrawSquareOptions): void;
2312
- /**
2313
- * Draw a straight line.
2314
- */
2315
- drawLine(options: DrawLineOptions): void;
2316
- /**
2317
- * Draw a circle.
2318
- */
2319
- drawCircle(options?: DrawCircleOptions): void;
2320
- /**
2321
- * Draw an ellipse.
2322
- */
2323
- drawEllipse(options?: DrawEllipseOptions): void;
2324
- /**
2325
- * Push the current graphics state onto the stack (`q`).
2326
- *
2327
- * Must be balanced with a matching {@link popGraphicsState} call.
2328
- */
2329
- pushGraphicsState(): void;
2330
- /**
2331
- * Pop the most recently saved graphics state (`Q`).
2332
- */
2333
- popGraphicsState(): void;
2334
- /**
2335
- * Concatenate an arbitrary transformation matrix with the CTM (`cm`).
2336
- *
2337
- * @param a Horizontal scaling / rotation.
2338
- * @param b Rotation / skew.
2339
- * @param c Rotation / skew.
2340
- * @param d Vertical scaling / rotation.
2341
- * @param tx Horizontal translation.
2342
- * @param ty Vertical translation.
2343
- */
2344
- setTransform(a: number, b: number, c: number, d: number, tx: number, ty: number): void;
2345
- /**
2346
- * Append raw PDF operator string(s) to the content stream.
2347
- *
2348
- * Use with caution — no validation is performed.
2349
- */
2350
- pushOperators(operators: string): void;
2351
- /**
2352
- * Get the current page rotation in degrees.
2353
- * @returns The rotation angle (0, 90, 180, or 270).
2354
- */
2355
- getRotation(): number;
2356
- /**
2357
- * Set the page rotation in degrees.
2358
- *
2359
- * @param angle Must be 0, 90, 180, or 270.
2360
- * @internal
2361
- */
2362
- setRotation(angle: number): void;
2363
- /**
2364
- * Get the current tab order for this page.
2365
- *
2366
- * @returns `'S'` (structure), `'R'` (row), `'C'` (column), or
2367
- * `undefined` if not set.
2368
- */
2369
- getTabOrder(): 'S' | 'R' | 'C' | undefined;
2370
- /**
2371
- * Set the tab order for this page.
2372
- *
2373
- * PDF/UA requires `'S'` (structure order) so that assistive technology
2374
- * follows the logical structure tree.
2375
- *
2376
- * @param order `'S'` (structure), `'R'` (row), or `'C'` (column).
2377
- */
2378
- setTabOrder(order: 'S' | 'R' | 'C'): void;
2379
- /** Get the page width in points. Alias for the `width` getter. */
2380
- getWidth(): number;
2381
- /** Get the page height in points. Alias for the `height` getter. */
2382
- getHeight(): number;
2383
- /** Set the page width in points. */
2384
- setWidth(w: number): void;
2385
- /** Set the page height in points. */
2386
- setHeight(h: number): void;
2387
- /** Set both page width and height in points. */
2388
- setSize(w: number, h: number): void;
2389
- /** Get the page width and height as an object. */
2390
- getSize(): {
2391
- width: number;
2392
- height: number;
2393
- };
2394
- /** Reset page dimensions to their original values from creation time. */
2395
- resetSize(): void;
2396
- /** Translate all page content by (x, y) points. Prepends a cm operator. */
2397
- translateContent(x: number, y: number): void;
2398
- /** Scale page content by the given factors. Prepends a cm operator. */
2399
- scaleContent(xFactor: number, yFactor: number): void;
2400
- /** Scale annotation rectangles by the given factors. */
2401
- scaleAnnotations(xFactor: number, yFactor: number): void;
2402
- /** Scale page dimensions, content, and annotations together. */
2403
- scale(xFactor: number, yFactor: number): void;
2404
- /** Get the media box for this page. */
2405
- getMediaBox(): {
2406
- x: number;
2407
- y: number;
2408
- width: number;
2409
- height: number;
2410
- };
2411
- /** Set the media box (page dimensions) for this page. */
2412
- setMediaBox(x: number, y: number, width: number, height: number): void;
2413
- /** Get the crop box if set, or undefined. */
2414
- getCropBox(): {
2415
- x: number;
2416
- y: number;
2417
- width: number;
2418
- height: number;
2419
- } | undefined;
2420
- /** Set the crop box for this page. */
2421
- setCropBox(x: number, y: number, width: number, height: number): void;
2422
- /** Get the bleed box if set, or undefined. */
2423
- getBleedBox(): {
2424
- x: number;
2425
- y: number;
2426
- width: number;
2427
- height: number;
2428
- } | undefined;
2429
- /** Set the bleed box for this page. */
2430
- setBleedBox(x: number, y: number, width: number, height: number): void;
2431
- /** Get the trim box if set, or undefined. */
2432
- getTrimBox(): {
2433
- x: number;
2434
- y: number;
2435
- width: number;
2436
- height: number;
2437
- } | undefined;
2438
- /** Set the trim box for this page. */
2439
- setTrimBox(x: number, y: number, width: number, height: number): void;
2440
- /** Get the art box if set, or undefined. */
2441
- getArtBox(): {
2442
- x: number;
2443
- y: number;
2444
- width: number;
2445
- height: number;
2446
- } | undefined;
2447
- /** Set the art box for this page. */
2448
- setArtBox(x: number, y: number, width: number, height: number): void;
2449
- /**
2450
- * Alt text entries for images, keyed by image resource name.
2451
- * Used during structure tree serialization.
2452
- * @internal
2453
- */
2454
- private readonly imageAltTexts;
2455
- /**
2456
- * Wrap the current content-stream operators in a marked-content
2457
- * sequence.
2458
- *
2459
- * This wraps ALL currently accumulated content in a BDC/EMC pair
2460
- * with the given structure tag and marked-content ID (MCID). The
2461
- * MCID links the content to a structure element in the document's
2462
- * structure tree.
2463
- *
2464
- * Call this after adding content to the page and before adding
2465
- * more content that belongs to a different structure element.
2466
- *
2467
- * @param tag The structure type tag (e.g. `"P"`, `"H1"`, `"Span"`).
2468
- * @param mcid The marked-content ID assigned by the structure tree.
2469
- */
2470
- markContent(tag: StructureType, mcid: number): void;
2471
- /**
2472
- * Begin a marked-content sequence in the content stream.
2473
- *
2474
- * Must be paired with a call to {@link endMarkedContentSequence}.
2475
- * Content added between the two calls will be associated with the
2476
- * given structure element.
2477
- *
2478
- * @param tag The structure type tag.
2479
- * @param mcid The marked-content ID.
2480
- */
2481
- beginMarkedContent(tag: StructureType, mcid: number): void;
2482
- /**
2483
- * End a marked-content sequence in the content stream.
2484
- *
2485
- * Must be preceded by a call to {@link beginMarkedContent}.
2486
- */
2487
- endMarkedContentSequence(): void;
2488
- /**
2489
- * Associate alt text with an image reference on this page.
2490
- *
2491
- * The alt text is stored and used during structure tree serialization
2492
- * to create a Figure structure element with the `/Alt` attribute.
2493
- *
2494
- * @param imageRef The image reference returned by `doc.embedPng()`
2495
- * or `doc.embedJpeg()`.
2496
- * @param altText The alternative text describing the image.
2497
- */
2498
- addAltText(imageRef: ImageRef, altText: string): void;
2499
- /**
2500
- * Get the alt text for an image, if set.
2501
- *
2502
- * @param imageRef The image reference.
2503
- * @returns The alt text, or `undefined`.
2504
- */
2505
- getAltText(imageRef: ImageRef): string | undefined;
2506
- /**
2507
- * Annotations on this page.
2508
- * @internal
2509
- */
2510
- private readonly annotations;
2511
- /** Raw widget annotation dicts added via addWidgetAnnotation. */
2512
- private readonly widgetDicts;
2513
- /**
2514
- * Get all annotations on this page.
2515
- *
2516
- * @returns An array of PdfAnnotation instances.
2517
- */
2518
- getAnnotations(): PdfAnnotation[];
2519
- /**
2520
- * Add an annotation to this page.
2521
- *
2522
- * @param type The annotation subtype.
2523
- * @param options Annotation options (rect, contents, color, etc.).
2524
- * @returns The created PdfAnnotation.
2525
- */
2526
- addAnnotation(type: AnnotationType, options: AnnotationOptions): PdfAnnotation;
2527
- /**
2528
- * Add a pre-created annotation to this page.
2529
- *
2530
- * @param annotation The annotation to add.
2531
- * @internal
2532
- */
2533
- addExistingAnnotation(annotation: PdfAnnotation): void;
2534
- /**
2535
- * Remove an annotation from this page.
2536
- *
2537
- * @param annotation The annotation to remove.
2538
- */
2539
- removeAnnotation(annotation: PdfAnnotation): void;
2540
- /**
2541
- * Add a raw widget annotation dictionary to this page.
2542
- *
2543
- * Used by form fields' `addToPage()` to register their widget
2544
- * annotation without wrapping in a `PdfAnnotation` instance.
2545
- *
2546
- * @param widgetDict The widget annotation dictionary.
2547
- */
2548
- addWidgetAnnotation(widgetDict: PdfDict): void;
2549
- /**
2550
- * Flatten all annotations into the page content stream.
2551
- *
2552
- * After flattening, annotations are rendered as part of the page
2553
- * content and are no longer interactive. The annotations are
2554
- * removed from the page's annotation list.
2555
- */
2556
- flattenAnnotations(): void;
2557
- /**
2558
- * @internal Get annotation refs for the page dictionary /Annots array.
2559
- */
2560
- getAnnotationRefs(registry: PdfObjectRegistry): PdfRef[];
2561
- /**
2562
- * Draw an SVG image onto this page.
2563
- *
2564
- * @param svgString The SVG markup string.
2565
- * @param options Rendering options (position, size).
2566
- */
2567
- drawSvg(svgString: string, options?: SvgRenderOptions): void;
2568
- /**
2569
- * Draw an SVG path data string onto this page.
2570
- *
2571
- * The `pathData` parameter uses the same syntax as the SVG `<path d="...">`
2572
- * attribute (M, L, C, Q, H, V, S, T, A, Z commands).
2573
- *
2574
- * **Important:** SVG path coordinates use a top-down Y axis. This
2575
- * method applies a Y-axis flip so that the path renders correctly in
2576
- * PDF's bottom-up coordinate system. The `x` / `y` options position
2577
- * the origin of the path in PDF space.
2578
- *
2579
- * @param pathData SVG path data string (e.g. `"M 0 0 L 100 0 L 100 100 Z"`).
2580
- * @param options Drawing options (position, scale, colours).
2581
- */
2582
- drawSvgPath(pathData: string, options?: DrawSvgPathOptions): void;
2583
- /**
2584
- * Draw a QR code at the specified position.
2585
- *
2586
- * The QR code is rendered as native PDF vector graphics (filled
2587
- * rectangles for each dark module), producing resolution-independent
2588
- * output.
2589
- *
2590
- * @param data The string to encode in the QR code.
2591
- * @param options Position, error correction level, colours, module size.
2592
- */
2593
- drawQrCode(data: string, options?: DrawQrCodeOptions): void;
2594
- /**
2595
- * Draw a table on this page.
2596
- *
2597
- * The table is rendered as native PDF vector graphics (rectangles,
2598
- * borders, and text operators). The top-left corner of the table is
2599
- * at `(options.x, options.y)` and rows extend downward.
2600
- *
2601
- * @param options Table configuration: position, size, rows, columns,
2602
- * fonts, colours, borders, and padding.
2603
- * @returns A {@link TableRenderResult} with the computed
2604
- * dimensions and layout metrics.
2605
- *
2606
- * @example
2607
- * ```ts
2608
- * const result = page.drawTable({
2609
- * x: 50,
2610
- * y: 700,
2611
- * width: 500,
2612
- * rows: [
2613
- * { cells: ['Name', 'Age', 'City'] },
2614
- * { cells: ['Alice', '30', 'London'] },
2615
- * { cells: ['Bob', '25', 'Paris'] },
2616
- * ],
2617
- * });
2618
- * ```
2619
- */
2620
- drawTable(options: DrawTableOptions): TableRenderResult;
2621
- /**
2622
- * Draw a gradient fill (linear or radial) clipped to a rectangle.
2623
- *
2624
- * The gradient is registered as a `/Pattern` resource on this page
2625
- * and painted within the specified rectangular region.
2626
- *
2627
- * @param gradient A gradient descriptor from {@link linearGradient}
2628
- * or {@link radialGradient}.
2629
- * @param rect The rectangle to fill.
2630
- */
2631
- drawGradient(gradient: GradientFill, rect: {
2632
- x: number;
2633
- y: number;
2634
- width: number;
2635
- height: number;
2636
- }): void;
2637
- /**
2638
- * Draw a tiling pattern fill clipped to a rectangle.
2639
- *
2640
- * The pattern is registered as a `/Pattern` resource on this page
2641
- * and painted within the specified rectangular region.
2642
- *
2643
- * @param pattern A pattern descriptor from {@link tilingPattern}.
2644
- * @param rect The rectangle to fill.
2645
- */
2646
- drawPattern(pattern: PatternFill, rect: {
2647
- x: number;
2648
- y: number;
2649
- width: number;
2650
- height: number;
2651
- }): void;
2652
- /**
2653
- * Begin layer-specific content.
2654
- *
2655
- * Content drawn after this call and before {@link endLayer} will be
2656
- * associated with the given layer and can be shown/hidden by the
2657
- * viewer.
2658
- *
2659
- * @param layer The layer to begin.
2660
- */
2661
- beginLayer(layer: PdfLayer): void;
2662
- /**
2663
- * End layer-specific content.
2664
- *
2665
- * Must be preceded by a call to {@link beginLayer}.
2666
- */
2667
- endLayer(): void;
2668
- /**
2669
- * Begin a transparency group. All drawing operations until
2670
- * {@link endTransparencyGroup} will be captured and composited as a
2671
- * single Form XObject with a `/Group` transparency dictionary.
2672
- *
2673
- * Transparency groups enable isolated and knockout compositing effects
2674
- * that are not possible with simple opacity settings.
2675
- *
2676
- * Groups can be nested — each call must be paired with a matching
2677
- * {@link endTransparencyGroup}.
2678
- *
2679
- * @param options Isolation, knockout, and color-space settings.
2680
- *
2681
- * @example
2682
- * ```ts
2683
- * page.beginTransparencyGroup({ isolated: true });
2684
- * page.drawRectangle({ x: 50, y: 50, width: 100, height: 100, opacity: 0.5 });
2685
- * page.drawCircle({ x: 100, y: 100, size: 60, opacity: 0.5 });
2686
- * page.endTransparencyGroup();
2687
- * ```
2688
- */
2689
- beginTransparencyGroup(options?: TransparencyGroupOptions): void;
2690
- /**
2691
- * End the current transparency group and composite it onto the page
2692
- * as a Form XObject.
2693
- *
2694
- * @throws {Error} If there is no matching {@link beginTransparencyGroup}.
2695
- */
2696
- endTransparencyGroup(): void;
2697
- /**
2698
- * Apply a soft mask (luminosity-based) for subsequent drawing operations.
2699
- *
2700
- * White regions in the mask are fully opaque; black regions are fully
2701
- * transparent. The mask stays active until {@link clearSoftMask} is
2702
- * called or the graphics state is restored.
2703
- *
2704
- * @param mask A soft mask reference created by
2705
- * {@link PdfDocument.createSoftMask}.
2706
- *
2707
- * @example
2708
- * ```ts
2709
- * const mask = doc.createSoftMask(200, 200, (b) => {
2710
- * b.drawRectangle(0, 0, 200, 200, 1); // white = opaque
2711
- * b.drawCircle(100, 100, 80, 0); // black = transparent
2712
- * });
2713
- * page.applySoftMask(mask);
2714
- * page.drawImage(image, { x: 50, y: 50, width: 200, height: 200 });
2715
- * page.clearSoftMask();
2716
- * ```
2717
- */
2718
- applySoftMask(mask: SoftMaskRef): void;
2719
- /**
2720
- * Clear the current soft mask, resetting to no masking.
2721
- *
2722
- * This emits an ExtGState with `/SMask /None`, which removes any
2723
- * previously applied soft mask for subsequent drawing operations.
2724
- */
2725
- clearSoftMask(): void;
2726
- /**
2727
- * Mark a rectangular region on this page for redaction.
2728
- *
2729
- * The mark is stored but not applied until `doc.applyRedactions()`
2730
- * is called.
2731
- *
2732
- * @param rect The region to redact: [x, y, width, height].
2733
- * @param options Additional redaction options (overlay text, colour).
2734
- */
2735
- markForRedaction(rect: [number, number, number, number], options?: Partial<RedactionOptions>): void;
2736
- /** @internal Return the accumulated operator string. */
2737
- getContentStreamData(): string;
2738
- /** @internal Return the original content-stream refs from a loaded PDF. */
2739
- getOriginalContentRefs(): readonly PdfRef[];
2740
- /** @internal Return the original resources dict from a loaded PDF. */
2741
- getOriginalResources(): PdfDict | undefined;
2742
- /** @internal Return the object registry for this page. */
2743
- getRegistry(): PdfObjectRegistry;
2744
- /**
2745
- * @internal Build the `/Resources` dictionary for this page.
2746
- */
2747
- buildResources(): PdfDict;
2748
- /**
2749
- * @internal Merge original resources from a loaded PDF with any newly
2750
- * added resources (fonts, images, graphics states).
2751
- *
2752
- * The original resources dict is used as the base. New entries are
2753
- * added into the appropriate sub-dictionaries (e.g. /Font, /XObject).
2754
- */
2755
- private _mergeResources;
2756
- /**
2757
- * @internal Finalize this page: create the content stream object and
2758
- * register it in the object registry. Returns a {@link PageEntry}
2759
- * compatible with {@link buildPageTree}.
2760
- */
2761
- finalize(): {
2762
- pageRef: PdfRef;
2763
- mediaBox: readonly [number, number, number, number];
2764
- width: number;
2765
- height: number;
2766
- contentStreamRefs: PdfRef | readonly PdfRef[];
2767
- resources: PdfDict;
2768
- rotation?: number | undefined;
2769
- cropBox?: readonly [number, number, number, number] | undefined;
2770
- bleedBox?: readonly [number, number, number, number] | undefined;
2771
- artBox?: readonly [number, number, number, number] | undefined;
2772
- trimBox?: readonly [number, number, number, number] | undefined;
2773
- annotationRefs?: PdfRef[] | undefined;
2774
- tabOrder?: 'S' | 'R' | 'C' | undefined;
2775
- };
2776
- }
2777
- //#endregion
2778
- //#region src/core/pdfCatalog.d.ts
2779
- /**
2780
- * Format a `Date` as a PDF date string.
2781
- *
2782
- * PDF dates follow the form: `D:YYYYMMDDHHmmSSOHH'mm`
2783
- *
2784
- * - `O` is the relationship to UT: `+`, `-`, or `Z`.
2785
- * - The trailing `HH'mm` is the UT offset.
2786
- *
2787
- * @param date A JavaScript Date object.
2788
- * @returns A PDF date string wrapped in parentheses.
2789
- */
2790
- declare function formatPdfDate(date: Date): string;
2791
- /** Metadata fields for the /Info dictionary. */
2792
- interface DocumentMetadata {
2793
- title?: string | undefined;
2794
- author?: string | undefined;
2795
- subject?: string | undefined;
2796
- keywords?: string | undefined;
2797
- creator?: string | undefined;
2798
- producer?: string | undefined;
2799
- creationDate?: Date | undefined;
2800
- modDate?: Date | undefined;
2801
- }
2802
- /**
2803
- * Build the `/Info` dictionary from metadata.
2804
- *
2805
- * @param meta Document metadata.
2806
- * @param registry Object registry — the info dict is registered as an
2807
- * indirect object.
2808
- * @returns The indirect reference to the `/Info` dict.
2809
- */
2810
- declare function buildInfoDict(meta: DocumentMetadata, registry: PdfObjectRegistry): PdfRef;
2811
- /**
2812
- * Represents a single page's key refs for building the page tree.
2813
- */
2814
- interface PageEntry {
2815
- /** Indirect reference for this page object. */
2816
- readonly pageRef: PdfRef;
2817
- /** Full media box `[llx, lly, urx, ury]`. */
2818
- readonly mediaBox?: readonly [number, number, number, number] | undefined;
2819
- /** Width of the page (points). */
2820
- readonly width: number;
2821
- /** Height of the page (points). */
2822
- readonly height: number;
2823
- /**
2824
- * Content stream reference(s).
2825
- *
2826
- * A single PdfRef for newly created pages, or an array for loaded pages
2827
- * that may have multiple content streams (or original + appended).
2828
- */
2829
- readonly contentStreamRefs: PdfRef | readonly PdfRef[];
2830
- /** Resources dictionary (fonts, images, etc.). */
2831
- readonly resources: PdfDict;
2832
- /** Optional rotation in degrees (0, 90, 180, 270). */
2833
- readonly rotation?: number | undefined;
2834
- /** Optional crop box `[llx, lly, urx, ury]`. */
2835
- readonly cropBox?: readonly [number, number, number, number] | undefined;
2836
- /** Optional bleed box `[llx, lly, urx, ury]`. */
2837
- readonly bleedBox?: readonly [number, number, number, number] | undefined;
2838
- /** Optional art box `[llx, lly, urx, ury]`. */
2839
- readonly artBox?: readonly [number, number, number, number] | undefined;
2840
- /** Optional trim box `[llx, lly, urx, ury]`. */
2841
- readonly trimBox?: readonly [number, number, number, number] | undefined;
2842
- /** Optional annotation indirect references. */
2843
- readonly annotationRefs?: readonly PdfRef[] | undefined;
2844
- /** Optional tab order: 'S' (structure), 'R' (row), 'C' (column). */
2845
- readonly tabOrder?: 'S' | 'R' | 'C' | undefined;
2846
- }
2847
- /**
2848
- * Build the `/Pages` tree and individual `/Page` dictionaries.
2849
- *
2850
- * This implementation uses a flat page tree (a single `/Pages` node)
2851
- * which is correct for documents with up to several thousand pages.
2852
- *
2853
- * @param pages Ordered list of page entries.
2854
- * @param registry Object registry.
2855
- * @returns The indirect reference to the root `/Pages` node.
2856
- */
2857
- declare function buildPageTree(pages: readonly PageEntry[], registry: PdfObjectRegistry): PdfRef;
2858
- /** Options for building the catalog. */
2859
- interface CatalogOptions {
2860
- /** Page layout hint. */
2861
- pageLayout?: 'SinglePage' | 'OneColumn' | 'TwoColumnLeft' | 'TwoColumnRight' | 'TwoPageLeft' | 'TwoPageRight' | undefined;
2862
- /** Page mode hint. */
2863
- pageMode?: 'UseNone' | 'UseOutlines' | 'UseThumbs' | 'FullScreen' | 'UseOC' | 'UseAttachments' | undefined;
2864
- /** The natural language of the document content (e.g. `en-US`). */
2865
- lang?: string | undefined;
2866
- }
2867
- /**
2868
- * Build the `/Catalog` dictionary.
2869
- *
2870
- * @param pagesRef Indirect reference to the root `/Pages` node.
2871
- * @param registry Object registry.
2872
- * @param options Optional catalog-level settings.
2873
- * @returns The indirect reference to the `/Catalog` dict.
2874
- */
2875
- declare function buildCatalog(pagesRef: PdfRef, registry: PdfObjectRegistry, options?: CatalogOptions): PdfRef;
2876
- /**
2877
- * High-level helper that wires together the catalog, page tree, and info
2878
- * dict, returning all the references the writer needs.
2879
- */
2880
- interface DocumentStructure {
2881
- /** Reference to the /Catalog. */
2882
- catalogRef: PdfRef;
2883
- /** Reference to the /Info dict. */
2884
- infoRef: PdfRef;
2885
- /** Reference to the /Pages node. */
2886
- pagesRef: PdfRef;
2887
- }
2888
- /**
2889
- * Build the complete document structure.
2890
- *
2891
- * @param pages Page entries (already have refs allocated).
2892
- * @param meta Document metadata.
2893
- * @param registry Object registry.
2894
- * @param options Optional catalog settings.
2895
- */
2896
- declare function buildDocumentStructure(pages: readonly PageEntry[], meta: DocumentMetadata, registry: PdfObjectRegistry, options?: CatalogOptions): DocumentStructure;
2897
- //#endregion
2898
- //#region src/crypto/permissions.d.ts
2899
- /**
2900
- * @module crypto/permissions
2901
- *
2902
- * PDF document permission flags encoding and decoding.
2903
- *
2904
- * The /P entry in the encryption dictionary is a 32-bit signed integer
2905
- * whose individual bits represent document access permissions. Bits
2906
- * are numbered starting from 1 (least significant).
2907
- *
2908
- * Reference: PDF 1.7 spec, Table 22 (User access permissions).
2909
- *
2910
- * Bit layout (1-indexed):
2911
- * - Bits 1-2: Reserved, must be 0
2912
- * - Bit 3: Print the document
2913
- * - Bit 4: Modify the contents of the document
2914
- * - Bit 5: Copy or otherwise extract text and graphics
2915
- * - Bit 6: Add or modify text annotations, fill in interactive form fields
2916
- * - Bits 7-8: Reserved, must be 1
2917
- * - Bit 9: Fill in existing interactive form fields (revision 3+)
2918
- * - Bit 10: Extract text and graphics for accessibility (revision 3+)
2919
- * - Bit 11: Assemble the document (revision 3+)
2920
- * - Bit 12: Print in high fidelity (revision 3+)
2921
- * - Bits 13-32: Reserved, must be 0
2922
- *
2923
- * When a bit is SET (1), the corresponding permission is GRANTED.
2924
- * Bits 7-8 must always be 1. Bits 13-32 must always be 0.
2925
- */
2926
- /**
2927
- * Human-friendly permission flags for a PDF document.
2928
- *
2929
- * Each flag controls a specific capability:
2930
- *
2931
- * - `printing`: `true` = full quality, `'lowResolution'` = low-res only,
2932
- * `false` / `undefined` = no printing allowed.
2933
- * - `modifying`: Allow content modifications.
2934
- * - `copying`: Allow text/graphics extraction.
2935
- * - `annotating`: Allow adding/modifying annotations.
2936
- * - `fillingForms`: Allow filling interactive form fields.
2937
- * - `contentAccessibility`: Allow text extraction for accessibility.
2938
- * - `documentAssembly`: Allow inserting/deleting/rotating pages.
2939
- */
2940
- interface PdfPermissionFlags {
2941
- printing?: boolean | 'lowResolution' | undefined;
2942
- modifying?: boolean | undefined;
2943
- copying?: boolean | undefined;
2944
- annotating?: boolean | undefined;
2945
- fillingForms?: boolean | undefined;
2946
- contentAccessibility?: boolean | undefined;
2947
- documentAssembly?: boolean | undefined;
2948
- }
2949
- /**
2950
- * Encode human-friendly permission flags into the 32-bit /P integer
2951
- * used in the PDF encryption dictionary.
2952
- *
2953
- * By default (when all flags are `undefined` or `false`), no
2954
- * permissions are granted beyond the reserved bits.
2955
- *
2956
- * @param flags The permissions to encode.
2957
- * @returns A 32-bit signed integer for the /P entry.
2958
- */
2959
- declare function encodePermissions(flags: PdfPermissionFlags): number;
2960
- /**
2961
- * Decode the 32-bit /P integer from a PDF encryption dictionary into
2962
- * human-friendly permission flags.
2963
- *
2964
- * @param value The /P integer from the encryption dictionary.
2965
- * @returns The decoded permission flags.
2966
- */
2967
- declare function decodePermissions(value: number): PdfPermissionFlags;
2968
- //#endregion
2969
- //#region src/crypto/encryptionHandler.d.ts
2970
- /**
2971
- * Algorithm selection for new encryption.
2972
- */
2973
- type EncryptAlgorithm = 'rc4-40' | 'rc4-128' | 'aes-128' | 'aes-256';
2974
- /**
2975
- * Options for encrypting a PDF document.
2976
- */
2977
- interface EncryptOptions {
2978
- /** The user password (may be empty string for open access). */
2979
- userPassword: string;
2980
- /** The owner password (restricts editing). */
2981
- ownerPassword: string;
2982
- /** Permission flags. */
2983
- permissions?: PdfPermissionFlags | undefined;
2984
- /** Encryption algorithm. Default: `'aes-128'`. */
2985
- algorithm?: EncryptAlgorithm | undefined;
2986
- }
2987
- /**
2988
- * Handles encryption and decryption of PDF objects according to the
2989
- * standard security handler.
2990
- *
2991
- * Create via:
2992
- * - `PdfEncryptionHandler.create(options)` for new encryption
2993
- * - `PdfEncryptionHandler.fromEncryptDict(dict, fileId, password)` for existing
2994
- */
2995
- declare class PdfEncryptionHandler {
2996
- /** The file-level encryption key. */
2997
- private readonly fileKey;
2998
- /** Algorithm version (/V). */
2999
- private readonly version;
3000
- /** Security handler revision (/R). */
3001
- private readonly revision;
3002
- /** Key length in bits. */
3003
- private readonly keyLengthBits;
3004
- /** Whether to use AES (true) or RC4 (false). */
3005
- private readonly useAes;
3006
- /** Whether to encrypt the /Metadata stream. */
3007
- private readonly encryptMetadata;
3008
- /** Permission flags as a 32-bit integer. */
3009
- private readonly permissionsValue;
3010
- /** Owner key (/O). */
3011
- private readonly ownerKey;
3012
- /** User key (/U). */
3013
- private readonly userKey;
3014
- /** Owner encryption key (/OE, V=5 only). */
3015
- private readonly ownerEncryptionKey?;
3016
- /** User encryption key (/UE, V=5 only). */
3017
- private readonly userEncryptionKey?;
3018
- /** Encrypted permissions (/Perms, V=5 only). */
3019
- private readonly perms?;
3020
- /** The file ID (first element of /ID array). */
3021
- private readonly fileId;
3022
- /**
3023
- * Cache for per-object derived keys (V=1-4 only).
3024
- * Key: `(objNum << 16) | genNum` — unique integer per object.
3025
- * Value: the derived encryption key.
3026
- *
3027
- * Avoids recomputing MD5(fileKey + objNum + genNum [+ sAlT]) for
3028
- * every string and stream in the same object.
3029
- */
3030
- private readonly objectKeyCache;
3031
- private constructor();
3032
- /**
3033
- * Create a new encryption handler for encrypting a document.
3034
- *
3035
- * Generates all necessary keys and values for the /Encrypt dictionary.
3036
- *
3037
- * @param options Encryption options.
3038
- * @param fileId Optional file ID. If omitted, a random one is generated.
3039
- * @returns A configured PdfEncryptionHandler.
3040
- */
3041
- static create(options: EncryptOptions, fileId?: Uint8Array | undefined): Promise<PdfEncryptionHandler>;
3042
- /**
3043
- * Create an encryption handler from an existing /Encrypt dictionary.
3044
- *
3045
- * @param dict The /Encrypt dictionary from the PDF trailer.
3046
- * @param fileId The first element of the /ID array.
3047
- * @param password The password to try (user or owner).
3048
- * @returns A configured PdfEncryptionHandler.
3049
- * @throws If the password is incorrect or the dict is invalid.
3050
- */
3051
- static fromEncryptDict(dict: PdfDict, fileId: Uint8Array, password: string): Promise<PdfEncryptionHandler>;
3052
- /**
3053
- * Derive the per-object encryption key for V=1-4.
3054
- *
3055
- * Per the spec: MD5(fileKey + objNum(3LE) + genNum(2LE) [+ "sAlT" for AES])
3056
- * Truncated to min(keyLength/8 + 5, 16) bytes.
3057
- *
3058
- * @param objNum Object number.
3059
- * @param genNum Generation number.
3060
- * @returns The per-object key.
3061
- */
3062
- private deriveObjectKey;
3063
- /**
3064
- * Encrypt raw data for a specific object.
3065
- *
3066
- * @param objNum Object number.
3067
- * @param genNum Generation number.
3068
- * @param data Plaintext data.
3069
- * @returns Encrypted data.
3070
- */
3071
- encryptObject(objNum: number, genNum: number, data: Uint8Array): Promise<Uint8Array>;
3072
- /**
3073
- * Decrypt raw data for a specific object.
3074
- *
3075
- * @param objNum Object number.
3076
- * @param genNum Generation number.
3077
- * @param data Encrypted data.
3078
- * @returns Decrypted data.
3079
- */
3080
- decryptObject(objNum: number, genNum: number, data: Uint8Array): Promise<Uint8Array>;
3081
- /**
3082
- * Encrypt a PdfString value.
3083
- *
3084
- * Converts the string value to bytes, encrypts, and returns a new
3085
- * hex-encoded PdfString.
3086
- *
3087
- * @param objNum Object number.
3088
- * @param genNum Generation number.
3089
- * @param str The string to encrypt.
3090
- * @returns An encrypted PdfString (hex-encoded).
3091
- */
3092
- encryptString(objNum: number, genNum: number, str: PdfString): Promise<PdfString>;
3093
- /**
3094
- * Decrypt a stream's data.
3095
- *
3096
- * @param objNum Object number.
3097
- * @param genNum Generation number.
3098
- * @param streamData Encrypted stream bytes.
3099
- * @returns Decrypted stream bytes.
3100
- */
3101
- decryptStream(objNum: number, genNum: number, streamData: Uint8Array): Promise<Uint8Array>;
3102
- /**
3103
- * Build the /Encrypt dictionary for the PDF trailer.
3104
- *
3105
- * @returns A PdfDict suitable for use as the /Encrypt entry.
3106
- */
3107
- buildEncryptDict(): PdfDict;
3108
- /** Get the permission flags. */
3109
- getPermissions(): PdfPermissionFlags;
3110
- /** Get the raw permissions value. */
3111
- getPermissionsValue(): number;
3112
- /** Whether this handler uses AES (vs RC4). */
3113
- isAes(): boolean;
3114
- /** The algorithm version (/V). */
3115
- getVersion(): number;
3116
- /** The security handler revision (/R). */
3117
- getRevision(): number;
3118
- /** The file encryption key (for testing/debugging). */
3119
- getFileKey(): Uint8Array;
3120
- /** The file ID used for key derivation. */
3121
- getFileId(): Uint8Array;
3122
- /** Whether metadata streams are encrypted. */
3123
- isMetadataEncrypted(): boolean;
3124
- }
3125
- //#endregion
3126
- //#region src/core/pdfWriter.d.ts
3127
- /** Options that control how the PDF is written. */
3128
- interface PdfSaveOptions {
3129
- /** Apply FlateDecode compression to streams. Default: `true`. */
3130
- compress?: boolean | undefined;
3131
- /**
3132
- * Compression level for FlateDecode (1–9). Default: `6`.
3133
- * Ignored when `compress` is `false`.
3134
- */
3135
- compressionLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
3136
- /**
3137
- * When `true`, attempt to use WASM-accelerated compression if the
3138
- * WASM module has been initialized. Default: `false`.
3139
- */
3140
- useWasm?: boolean | undefined;
3141
- /**
3142
- * Minimum number of non-stream indirect objects before object streams
3143
- * are used. When the count exceeds this threshold, objects are packed
3144
- * into compressed object streams and a cross-reference stream replaces
3145
- * the traditional xref table.
3146
- *
3147
- * Set to `Infinity` to disable object streams (traditional xref).
3148
- * A useful value for size reduction is `100`.
3149
- *
3150
- * Default: `Infinity` (disabled for backward compatibility).
3151
- */
3152
- objectStreamThreshold?: number | undefined;
3153
- /** Add a blank page if the document has no pages. Default: `true`. */
3154
- addDefaultPage?: boolean | undefined;
3155
- /** Regenerate form field appearances before saving. Default: `true`. */
3156
- updateFieldAppearances?: boolean | undefined;
3157
- }
3158
- /**
3159
- * Serialize a PDF document to a `Uint8Array`.
3160
- *
3161
- * ```ts
3162
- * const writer = new PdfWriter(registry, structure, options);
3163
- * const bytes = writer.write();
3164
- * ```
3165
- */
3166
- declare class PdfWriter {
3167
- /** All indirect objects. */
3168
- private readonly registry;
3169
- /** Document structure references. */
3170
- private readonly structure;
3171
- private readonly buf;
3172
- private readonly xrefOffsets;
3173
- private readonly compress;
3174
- private readonly compressionLevel;
3175
- private readonly useWasm;
3176
- private readonly objectStreamThreshold;
3177
- private readonly encryptionHandler;
3178
- /**
3179
- * When encryption is active, the /Encrypt dict is registered as an
3180
- * indirect object. Its reference is stored here for the trailer.
3181
- */
3182
- private encryptDictRef;
3183
- constructor(/** All indirect objects. */
3184
-
3185
- registry: PdfObjectRegistry, /** Document structure references. */
3186
-
3187
- structure: DocumentStructure, options?: PdfSaveOptions, encryptionHandler?: PdfEncryptionHandler | undefined);
3188
- /**
3189
- * Produce the complete PDF file as a `Uint8Array`.
3190
- *
3191
- * When an encryption handler is present, all string and stream
3192
- * objects are encrypted and the /Encrypt dictionary + /ID array
3193
- * are added to the trailer.
3194
- */
3195
- write(): Promise<Uint8Array>;
3196
- private writeHeader;
3197
- private writeBody;
3198
- private writeIndirectObject;
3199
- /**
3200
- * Encrypt all encryptable data within an indirect object.
3201
- *
3202
- * Per the PDF spec:
3203
- * - Strings inside the object are encrypted with the per-object key.
3204
- * - Stream data is encrypted with the per-object key.
3205
- * - The /Encrypt dictionary itself is never encrypted.
3206
- * - String values in the trailer /ID array are never encrypted.
3207
- */
3208
- private encryptEntry;
3209
- /**
3210
- * Recursively encrypt all PdfString values inside a PdfDict.
3211
- */
3212
- private encryptDictStrings;
3213
- /**
3214
- * Recursively encrypt all PdfString values inside a PdfArray.
3215
- */
3216
- private encryptArrayStrings;
3217
- /**
3218
- * Apply FlateDecode compression to a stream's data if it is not
3219
- * already compressed.
3220
- */
3221
- private compressStream;
3222
- /**
3223
- * Set of object numbers that must NOT be placed inside an object
3224
- * stream. This includes the catalog, info dict, pages root, and
3225
- * any stream objects (which by definition cannot nest in an ObjStm).
3226
- */
3227
- private protectedObjectNumbers;
3228
- /**
3229
- * Write the document body using object streams when the number of
3230
- * eligible non-stream objects exceeds `threshold`.
3231
- *
3232
- * @returns `true` if object streams (and a cross-reference stream)
3233
- * were used and the PDF is complete. `false` if the
3234
- * threshold was not met — in that case the body has been
3235
- * written in traditional format and the caller must still
3236
- * emit the classic xref table and trailer.
3237
- */
3238
- writeBodyWithObjectStreams(threshold: number): Promise<boolean>;
3239
- /**
3240
- * Serialize a group of non-stream objects into a single object stream
3241
- * (`/Type /ObjStm`) and record xref entries for them.
3242
- */
3243
- private writeObjectStream;
3244
- /**
3245
- * Write a cross-reference stream (PDF 1.5+) that replaces the
3246
- * traditional xref table and trailer.
3247
- */
3248
- private writeXrefStream;
3249
- private writeXref;
3250
- private writeTrailer;
3251
- }
3252
- /**
3253
- * Serialize a complete PDF from a registry and structure refs.
3254
- *
3255
- * @param registry All registered indirect objects.
3256
- * @param structure Catalog / Info / Pages references.
3257
- * @param options Save options.
3258
- * @param encryptionHandler Optional encryption handler for encrypting
3259
- * all objects and adding /Encrypt + /ID to
3260
- * the trailer.
3261
- * @returns The raw PDF bytes.
3262
- */
3263
- declare function serializePdf(registry: PdfObjectRegistry, structure: DocumentStructure, options?: PdfSaveOptions, encryptionHandler?: PdfEncryptionHandler | undefined): Promise<Uint8Array>;
3264
- //#endregion
3265
- //#region src/parser/documentParser.d.ts
3266
- /**
3267
- * Options for loading a PDF document from bytes.
3268
- */
3269
- interface LoadPdfOptions {
3270
- /** Password for encrypted PDFs (Phase 5). */
3271
- password?: string;
3272
- /** When true, skip decryption even if the PDF is encrypted. */
3273
- ignoreEncryption?: boolean;
3274
- /**
3275
- * When true, update the /ModDate in the /Info dictionary to the
3276
- * current time when saving. Defaults to true.
3277
- */
3278
- updateMetadata?: boolean;
3279
- /**
3280
- * Number of objects to process per event-loop tick during parsing.
3281
- * Lower values keep the main thread more responsive in browsers.
3282
- * Defaults to `Infinity` (no throttling).
3283
- */
3284
- objectsPerTick?: number;
3285
- /**
3286
- * When `true`, throw an error if a malformed or invalid PDF object
3287
- * is encountered during parsing. When `false` (default), malformed
3288
- * objects are silently skipped.
3289
- */
3290
- throwOnInvalidObject?: boolean | undefined;
3291
- /**
3292
- * When `true`, clamp extreme floating-point values (very large or
3293
- * very small numbers) to safe ranges during parsing. This prevents
3294
- * numeric overflows from producing garbage output.
3295
- *
3296
- * Default: `false`.
3297
- */
3298
- capNumbers?: boolean | undefined;
3299
- }
3300
- /**
3301
- * Load a PDF document from raw bytes, an ArrayBuffer, or a Base64-encoded
3302
- * string.
3303
- *
3304
- * This is the primary entry point for parsing existing PDFs. It creates
3305
- * a `PdfDocumentParser`, runs the full parse pipeline, and returns
3306
- * a populated {@link PdfDocument}.
3307
- *
3308
- * @param data The PDF data as a `Uint8Array`, `ArrayBuffer`, or a
3309
- * Base64-encoded string.
3310
- * @param options Optional loading options.
3311
- * @returns A fully parsed PdfDocument.
3312
- *
3313
- * @example
3314
- * ```ts
3315
- * import { loadPdf } from 'modern-pdf-lib';
3316
- *
3317
- * // From fetch (ArrayBuffer)
3318
- * const pdfBytes = await fetch('document.pdf').then(r => r.arrayBuffer());
3319
- * const doc = await loadPdf(pdfBytes);
3320
- *
3321
- * // From a Base64 string
3322
- * const doc2 = await loadPdf(base64String);
3323
- * ```
3324
- */
3325
- declare function loadPdf(data: Uint8Array | ArrayBuffer | string, options?: LoadPdfOptions): Promise<PdfDocument>;
3326
- //#endregion
3327
- //#region src/outline/pdfOutline.d.ts
3328
- /**
3329
- * Describes where an outline item navigates to when clicked.
3330
- *
3331
- * - `type: 'page'` — navigate to a specific page by zero-based index.
3332
- * - `type: 'named'` — use a named destination string.
3333
- */
3334
- interface OutlineDestination {
3335
- /** Whether to navigate by page index or named destination. */
3336
- type: 'page' | 'named';
3337
- /** Zero-based page index (used when `type` is `'page'`). */
3338
- pageIndex?: number | undefined;
3339
- /** Named destination string (used when `type` is `'named'`). */
3340
- namedDestination?: string | undefined;
3341
- /** Page fit mode — how the page should be displayed. */
3342
- fit?: 'Fit' | 'FitH' | 'FitV' | 'FitB' | 'FitBH' | 'FitBV' | 'XYZ' | undefined;
3343
- /** Top coordinate for FitH, FitBH, XYZ fit modes. */
3344
- top?: number | undefined;
3345
- /** Left coordinate for FitV, FitBV, XYZ fit modes. */
3346
- left?: number | undefined;
3347
- /** Zoom factor for XYZ fit mode (0 means keep current). */
3348
- zoom?: number | undefined;
3349
- }
3350
- /** Options for creating an outline item. */
3351
- interface OutlineItemOptions {
3352
- /** Whether the item's children are initially visible. Default: `true`. */
3353
- isOpen?: boolean | undefined;
3354
- /** Colour of the outline text as RGB in range 0-1. */
3355
- color?: {
3356
- r: number;
3357
- g: number;
3358
- b: number;
3359
- } | undefined;
3360
- /** Whether the title text is bold. */
3361
- bold?: boolean | undefined;
3362
- /** Whether the title text is italic. */
3363
- italic?: boolean | undefined;
3364
- }
3365
- /**
3366
- * A single node in the outline tree. Each item has a title, a
3367
- * destination, and zero or more child items.
3368
- */
3369
- declare class PdfOutlineItem {
3370
- /** The displayed bookmark title. */
3371
- title: string;
3372
- /** Where clicking this bookmark navigates. */
3373
- destination: OutlineDestination;
3374
- /** Child outline items. */
3375
- children: PdfOutlineItem[];
3376
- /** Whether children are initially expanded. */
3377
- isOpen: boolean;
3378
- /** Optional colour for the outline text (RGB, 0-1 range). */
3379
- color?: {
3380
- r: number;
3381
- g: number;
3382
- b: number;
3383
- } | undefined;
3384
- /** Whether the title is displayed in bold. */
3385
- bold?: boolean | undefined;
3386
- /** Whether the title is displayed in italic. */
3387
- italic?: boolean | undefined;
3388
- /**
3389
- * Create a new outline item.
3390
- *
3391
- * @param title Display title for the bookmark.
3392
- * @param destination Navigation target.
3393
- * @param options Visual style options.
3394
- */
3395
- constructor(title: string, destination: OutlineDestination, options?: OutlineItemOptions);
3396
- /**
3397
- * Add a child outline item.
3398
- *
3399
- * @param title Display title.
3400
- * @param destination Navigation target.
3401
- * @param options Visual style options.
3402
- * @returns The newly created child item.
3403
- */
3404
- addChild(title: string, destination: OutlineDestination, options?: OutlineItemOptions): PdfOutlineItem;
3405
- /**
3406
- * Remove a child outline item.
3407
- *
3408
- * @param item The child item to remove.
3409
- * @throws If the item is not a direct child.
3410
- */
3411
- removeChild(item: PdfOutlineItem): void;
3412
- /**
3413
- * Count all visible descendants (for the /Count entry).
3414
- *
3415
- * Per the PDF spec:
3416
- * - If the item is open, /Count is the total number of visible
3417
- * descendants (children + their visible descendants).
3418
- * - If the item is closed, /Count is the negative of the total
3419
- * number of descendants that *would* be visible if opened.
3420
- *
3421
- * @returns The count value for the /Count entry.
3422
- */
3423
- getVisibleDescendantCount(): number;
3424
- /**
3425
- * Count the total number of descendants regardless of open/closed state.
3426
- * @internal
3427
- */
3428
- getTotalDescendantCount(): number;
3429
- }
3430
- /**
3431
- * The root of the outline tree, containing top-level outline items.
3432
- */
3433
- declare class PdfOutlineTree {
3434
- /** Top-level outline items. */
3435
- items: PdfOutlineItem[];
3436
- constructor();
3437
- /**
3438
- * Add a top-level outline item.
3439
- *
3440
- * @param title Display title.
3441
- * @param destination Navigation target.
3442
- * @param options Visual style options.
3443
- * @returns The newly created item.
3444
- */
3445
- addItem(title: string, destination: OutlineDestination, options?: OutlineItemOptions): PdfOutlineItem;
3446
- /**
3447
- * Remove a top-level outline item.
3448
- *
3449
- * @param item The item to remove.
3450
- * @throws If the item is not in the tree.
3451
- */
3452
- removeItem(item: PdfOutlineItem): void;
3453
- /**
3454
- * Serialize the outline tree to a PDF /Outlines dictionary.
3455
- *
3456
- * This creates the complete outline object graph:
3457
- * - A root /Outlines dict with /Type, /First, /Last, /Count
3458
- * - One dict per outline item with /Title, /Parent, /Prev, /Next,
3459
- * /First, /Last, /Count, /Dest (or /A), /C, /F
3460
- *
3461
- * All dictionaries are registered in the provided registry and
3462
- * cross-linked via indirect references.
3463
- *
3464
- * @param registry Object registry for allocating refs.
3465
- * @param pageRefs Array of PdfRef for each page (indexed by page number).
3466
- * @returns The indirect reference to the /Outlines root dict.
3467
- */
3468
- toDict(registry: PdfObjectRegistry, pageRefs: readonly PdfRef[]): PdfRef;
3469
- /**
3470
- * Parse an outline tree from an existing /Outlines dictionary.
3471
- *
3472
- * @param dict The /Outlines dictionary.
3473
- * @param resolver Function to resolve indirect references to objects.
3474
- * @param pageRefToIndex Mapping from page ref object numbers to page indices.
3475
- * @returns A fully populated PdfOutlineTree.
3476
- */
3477
- static fromDict(dict: PdfDict, resolver: (ref: PdfRef) => PdfObject | undefined, pageRefToIndex: ReadonlyMap<number, number>): PdfOutlineTree;
3478
- /**
3479
- * Serialize a list of sibling outline items, linking them with
3480
- * /Prev and /Next references.
3481
- *
3482
- * @param items The sibling items to serialize.
3483
- * @param parentRef The indirect reference to the parent node.
3484
- * @param registry Object registry.
3485
- * @param pageRefs Page references array.
3486
- * @returns Array of refs for the serialized items.
3487
- *
3488
- * @internal
3489
- */
3490
- private serializeItems;
3491
- /**
3492
- * Serialize a destination into a /Dest array on the item dict.
3493
- *
3494
- * Destination formats per PDF spec:
3495
- * - [page /Fit]
3496
- * - [page /FitH top]
3497
- * - [page /FitV left]
3498
- * - [page /FitB]
3499
- * - [page /FitBH top]
3500
- * - [page /FitBV left]
3501
- * - [page /XYZ left top zoom]
3502
- *
3503
- * @internal
3504
- */
3505
- private serializeDestination;
3506
- }
3507
- //#endregion
3508
- //#region src/metadata/viewerPreferences.d.ts
3509
- /**
3510
- * Viewer preference settings for a PDF document.
3511
- *
3512
- * All properties are optional. Omitted properties use the viewer's
3513
- * default behaviour.
3514
- */
3515
- interface ViewerPreferences {
3516
- /** Hide the viewer's toolbar when the document is active. */
3517
- hideToolbar?: boolean | undefined;
3518
- /** Hide the viewer's menu bar when the document is active. */
3519
- hideMenubar?: boolean | undefined;
3520
- /** Hide the viewer's window UI elements (scrollbars, etc.). */
3521
- hideWindowUI?: boolean | undefined;
3522
- /** Resize the document's window to fit the first page. */
3523
- fitWindow?: boolean | undefined;
3524
- /** Center the document's window on the screen. */
3525
- centerWindow?: boolean | undefined;
3526
- /** Display the document title (from /Info /Title) in the title bar. */
3527
- displayDocTitle?: boolean | undefined;
3528
- /** Page mode to use when exiting full-screen mode. */
3529
- nonFullScreenPageMode?: 'UseNone' | 'UseOutlines' | 'UseThumbs' | 'UseOC' | undefined;
3530
- /** Predominant reading order for text. */
3531
- direction?: 'L2R' | 'R2L' | undefined;
3532
- /** Page scaling preference for the print dialog. */
3533
- printScaling?: 'None' | 'AppDefault' | undefined;
3534
- /** Paper handling option for duplex printing. */
3535
- duplex?: 'Simplex' | 'DuplexFlipShortEdge' | 'DuplexFlipLongEdge' | undefined;
3536
- /** Page ranges to print, as [start, end] pairs (1-based). */
3537
- printPageRange?: [number, number][] | undefined;
3538
- /** Default number of copies to print. */
3539
- numCopies?: number | undefined;
3540
- /** Whether to pick the paper tray based on the PDF page size. */
3541
- pickTrayByPDFSize?: boolean | undefined;
3542
- }
3543
- /**
3544
- * Build a `/ViewerPreferences` dictionary from preferences.
3545
- *
3546
- * Only includes entries for properties that are explicitly set
3547
- * (non-undefined). Boolean values of `false` are included to
3548
- * explicitly override viewer defaults.
3549
- *
3550
- * @param prefs Viewer preferences to serialize.
3551
- * @returns A PdfDict representing the `/ViewerPreferences` entry.
3552
- */
3553
- declare function buildViewerPreferencesDict(prefs: ViewerPreferences): PdfDict;
3554
- /**
3555
- * Parse a `/ViewerPreferences` dictionary into a ViewerPreferences object.
3556
- *
3557
- * @param dict The PDF dictionary to parse.
3558
- * @returns The parsed viewer preferences.
3559
- */
3560
- declare function parseViewerPreferences(dict: PdfDict): ViewerPreferences;
3561
- //#endregion
3562
- //#region src/metadata/pdfViewerPreferences.d.ts
3563
- /**
3564
- * Class-based API for PDF viewer preferences with individual getter/setter pairs.
3565
- *
3566
- * Provides the same functionality as the plain `ViewerPreferences` interface
3567
- * but with a more discoverable, pdf-lib-compatible API.
3568
- *
3569
- * ```ts
3570
- * const prefs = doc.getViewerPreferences();
3571
- * prefs.setHideToolbar(true);
3572
- * prefs.setDisplayDocTitle(true);
3573
- * prefs.setPrintScaling('None');
3574
- * ```
3575
- */
3576
- declare class PdfViewerPreferences {
3577
- private data;
3578
- constructor(data?: ViewerPreferences);
3579
- /** Whether the viewer's toolbar should be hidden. */
3580
- getHideToolbar(): boolean;
3581
- /** Set whether the viewer's toolbar should be hidden. */
3582
- setHideToolbar(value: boolean): void;
3583
- /** Whether the viewer's menu bar should be hidden. */
3584
- getHideMenubar(): boolean;
3585
- /** Set whether the viewer's menu bar should be hidden. */
3586
- setHideMenubar(value: boolean): void;
3587
- /** Whether the viewer's window UI elements should be hidden. */
3588
- getHideWindowUI(): boolean;
3589
- /** Set whether the viewer's window UI elements should be hidden. */
3590
- setHideWindowUI(value: boolean): void;
3591
- /** Whether the document window should be resized to fit the first page. */
3592
- getFitWindow(): boolean;
3593
- /** Set whether the document window should be resized to fit the first page. */
3594
- setFitWindow(value: boolean): void;
3595
- /** Whether the document window should be centered on the screen. */
3596
- getCenterWindow(): boolean;
3597
- /** Set whether the document window should be centered on the screen. */
3598
- setCenterWindow(value: boolean): void;
3599
- /** Whether the title bar should display the document title from metadata. */
3600
- getDisplayDocTitle(): boolean;
3601
- /** Set whether the title bar should display the document title. */
3602
- setDisplayDocTitle(value: boolean): void;
3603
- /** Whether the paper tray should be selected based on the PDF page size. */
3604
- getPickTrayByPDFSize(): boolean;
3605
- /** Set whether the paper tray should be selected based on the PDF page size. */
3606
- setPickTrayByPDFSize(value: boolean): void;
3607
- /** Page mode to use when exiting full-screen mode. */
3608
- getNonFullScreenPageMode(): 'UseNone' | 'UseOutlines' | 'UseThumbs' | 'UseOC';
3609
- /** Set the page mode to use when exiting full-screen mode. */
3610
- setNonFullScreenPageMode(value: 'UseNone' | 'UseOutlines' | 'UseThumbs' | 'UseOC'): void;
3611
- /** Predominant reading order for text. */
3612
- getDirection(): 'L2R' | 'R2L';
3613
- /** Set the predominant reading order for text. */
3614
- setDirection(value: 'L2R' | 'R2L'): void;
3615
- /** Page scaling preference for the print dialog. */
3616
- getPrintScaling(): 'None' | 'AppDefault';
3617
- /** Set the page scaling preference for the print dialog. */
3618
- setPrintScaling(value: 'None' | 'AppDefault'): void;
3619
- /** Paper handling option for duplex printing, or undefined if not set. */
3620
- getDuplex(): 'Simplex' | 'DuplexFlipShortEdge' | 'DuplexFlipLongEdge' | undefined;
3621
- /** Set the paper handling option for duplex printing. */
3622
- setDuplex(value: 'Simplex' | 'DuplexFlipShortEdge' | 'DuplexFlipLongEdge'): void;
3623
- /** Default number of copies to print. */
3624
- getNumCopies(): number;
3625
- /** Set the default number of copies to print. */
3626
- setNumCopies(value: number): void;
3627
- /** Page ranges to print, as [start, end] pairs, or undefined if not set. */
3628
- getPrintPageRange(): [number, number][] | undefined;
3629
- /** Set the page ranges to print, as [start, end] pairs. */
3630
- setPrintPageRange(value: [number, number][]): void;
3631
- /** Convert to a PdfDict for embedding in the PDF catalog. */
3632
- toDict(): PdfDict;
3633
- /** Convert to a plain ViewerPreferences object. */
3634
- toObject(): ViewerPreferences;
3635
- }
3636
- //#endregion
3637
- //#region src/signature/signatureHandler.d.ts
3638
- /**
3639
- * @module signature/signatureHandler
3640
- *
3641
- * High-level API for signing PDF documents and extracting signature
3642
- * information.
3643
- *
3644
- * This module orchestrates the lower-level modules (byteRange, pkcs7)
3645
- * to provide a simple `signPdf()` function and a `getSignatures()`
3646
- * function for inspecting existing signatures.
3647
- *
3648
- * @packageDocumentation
3649
- */
3650
- /**
3651
- * Options for a visible signature appearance on the page.
3652
- */
3653
- interface VisibleSignatureOptions {
3654
- /** Zero-based page index where the signature should appear. Default: 0. */
3655
- pageIndex?: number | undefined;
3656
- /** Rectangle [x, y, width, height] in PDF points from the bottom-left corner. */
3657
- rect: [number, number, number, number];
3658
- /**
3659
- * Text lines to display in the signature box.
3660
- * Each string becomes a separate line. If omitted, auto-generates
3661
- * from the signer name, reason, location, and date.
3662
- */
3663
- text?: string[] | undefined;
3664
- /** Font size for the text. Default: 10. */
3665
- fontSize?: number | undefined;
3666
- /**
3667
- * Background color as [r, g, b] values (0–1). Default: transparent.
3668
- */
3669
- backgroundColor?: [number, number, number] | undefined;
3670
- /**
3671
- * Border color as [r, g, b] values (0–1). Default: [0, 0, 0] (black).
3672
- */
3673
- borderColor?: [number, number, number] | undefined;
3674
- /** Border width in points. Default: 1. Set to 0 for no border. */
3675
- borderWidth?: number | undefined;
3676
- }
3677
- /**
3678
- * Options for signing a PDF.
3679
- */
3680
- interface SignOptions {
3681
- /** DER-encoded X.509 certificate. */
3682
- certificate: Uint8Array;
3683
- /** PKCS#8 DER-encoded private key. */
3684
- privateKey: Uint8Array;
3685
- /** Hash algorithm. Default: 'SHA-256'. */
3686
- hashAlgorithm?: 'SHA-256' | 'SHA-384' | 'SHA-512' | undefined;
3687
- /** Reason for signing. */
3688
- reason?: string | undefined;
3689
- /** Location of signing. */
3690
- location?: string | undefined;
3691
- /** Contact information. */
3692
- contactInfo?: string | undefined;
3693
- /** RFC 3161 TSA URL for timestamping (optional). */
3694
- timestampUrl?: string | undefined;
3695
- /**
3696
- * Visible signature appearance options. When provided, the signature
3697
- * field is rendered visibly on the specified page with text and
3698
- * optional styling. When omitted, the signature is invisible.
3699
- */
3700
- appearance?: VisibleSignatureOptions | undefined;
3701
- }
3702
- /**
3703
- * Information about an existing signature in a PDF.
3704
- */
3705
- interface PdfSignatureInfo {
3706
- /** The signature field name. */
3707
- fieldName: string;
3708
- /** Subject CN from the certificate. */
3709
- signedBy: string;
3710
- /** Reason for signing. */
3711
- reason?: string | undefined;
3712
- /** Location of signing. */
3713
- location?: string | undefined;
3714
- /** Contact information. */
3715
- contactInfo?: string | undefined;
3716
- /** Signing date/time. */
3717
- signingDate?: Date | undefined;
3718
- /** The ByteRange covering this signature. */
3719
- byteRange: [number, number, number, number];
3720
- /** Whether the signature is valid (set during verification). */
3721
- signatureValid?: boolean | undefined;
3722
- }
3723
- /**
3724
- * Sign a PDF document.
3725
- *
3726
- * Returns the signed PDF bytes. Uses incremental save to preserve
3727
- * existing content (including any previous signatures).
3728
- *
3729
- * @param pdfBytes The original PDF file bytes.
3730
- * @param fieldName The name for the signature field.
3731
- * @param options Signing options (certificate, key, etc.).
3732
- * @returns The signed PDF bytes.
3733
- *
3734
- * @example
3735
- * ```ts
3736
- * const signedPdf = await signPdf(pdfBytes, 'Signature1', {
3737
- * certificate: certDer,
3738
- * privateKey: keyDer,
3739
- * reason: 'Document approval',
3740
- * location: 'New York, NY',
3741
- * });
3742
- * ```
3743
- */
3744
- declare function signPdf(pdfBytes: Uint8Array, fieldName: string, options: SignOptions): Promise<Uint8Array>;
3745
- /**
3746
- * Extract signature information from a PDF.
3747
- *
3748
- * Scans the PDF for signature dictionaries and extracts metadata
3749
- * from each one.
3750
- *
3751
- * @param pdfBytes The PDF file bytes.
3752
- * @returns Array of signature info objects.
3753
- */
3754
- declare function getSignatures(pdfBytes: Uint8Array): PdfSignatureInfo[];
3755
- //#endregion
3756
- //#region src/core/embeddedFiles.d.ts
3757
- /** Describes a file to attach to (or already attached to) a PDF. */
3758
- interface EmbeddedFile {
3759
- /** Filename. */
3760
- name: string;
3761
- /** File data. */
3762
- data: Uint8Array;
3763
- /** MIME type (e.g. `"application/pdf"`, `"text/plain"`). */
3764
- mimeType: string;
3765
- /** Optional description. */
3766
- description?: string | undefined;
3767
- /** Optional creation date. */
3768
- creationDate?: Date | undefined;
3769
- /** Optional modification date. */
3770
- modificationDate?: Date | undefined;
3771
- }
3772
- /**
3773
- * Create an embedded file stream and filespec dictionary, registering
3774
- * them in the object registry.
3775
- *
3776
- * @param registry The PDF object registry.
3777
- * @param file The file to embed.
3778
- * @returns The indirect reference to the filespec dictionary.
3779
- */
3780
- declare function attachFile(registry: PdfObjectRegistry, file: EmbeddedFile): PdfRef;
3781
- /**
3782
- * Extract embedded file attachments from a catalog dictionary.
3783
- *
3784
- * @param catalogDict The catalog dictionary.
3785
- * @param resolver A function to resolve indirect references.
3786
- * @returns An array of embedded file descriptions.
3787
- */
3788
- declare function getAttachments(catalogDict: PdfDict, resolver: (ref: PdfRef) => PdfObject): EmbeddedFile[];
3789
- /**
3790
- * Build an `/EmbeddedFiles` name tree dictionary.
3791
- *
3792
- * @param files Array of indirect references to filespec dictionaries.
3793
- * @param names Corresponding file names (same order as `files`).
3794
- * @param registry The PDF object registry.
3795
- * @returns The name tree dictionary.
3796
- */
3797
- declare function buildEmbeddedFilesNameTree(files: PdfRef[], names: string[], registry: PdfObjectRegistry): PdfDict;
3798
- //#endregion
3799
- //#region src/core/watermark.d.ts
3800
- /** Options for watermark rendering. */
3801
- interface WatermarkOptions {
3802
- /** The watermark text. */
3803
- text: string;
3804
- /** Font size in points (default: 60). */
3805
- fontSize?: number | undefined;
3806
- /** Text colour as RGB (0-1 range, default: light gray). */
3807
- color?: {
3808
- r: number;
3809
- g: number;
3810
- b: number;
3811
- } | undefined;
3812
- /** Opacity from 0 (invisible) to 1 (opaque), default: 0.3. */
3813
- opacity?: number | undefined;
3814
- /** Rotation angle in degrees (default: 45). */
3815
- rotation?: number | undefined;
3816
- /** Position: `'center'`, `'top'`, or `'bottom'` (default: `'center'`). */
3817
- position?: 'center' | 'top' | 'bottom' | undefined;
3818
- }
3819
- /**
3820
- * Add a watermark to a single page.
3821
- *
3822
- * The watermark is drawn using the Helvetica standard font (no
3823
- * embedding required). The text is rendered with the specified
3824
- * rotation, opacity, and colour.
3825
- *
3826
- * @param page The page to watermark.
3827
- * @param options Watermark options.
3828
- * @param registry The PDF object registry (for ExtGState).
3829
- */
3830
- declare function addWatermarkToPage(page: PdfPage, options: WatermarkOptions, registry: PdfObjectRegistry): void;
3831
- /**
3832
- * Add a watermark to all pages in a document.
3833
- *
3834
- * @param doc The PDF document.
3835
- * @param options Watermark options.
3836
- */
3837
- declare function addWatermark(doc: PdfDocument, options: WatermarkOptions): void;
3838
- //#endregion
3839
- //#region src/signature/signatureVerifier.d.ts
3840
- /**
3841
- * @module signature/signatureVerifier
3842
- *
3843
- * Signature verification for signed PDF documents.
3844
- *
3845
- * Verifies that:
3846
- * 1. The PDF bytes covered by the ByteRange have not been tampered with
3847
- * (integrity check by hashing the covered regions).
3848
- * 2. The PKCS#7 signature is valid for the hash (cryptographic verification
3849
- * using the certificate's public key via Web Crypto).
3850
- *
3851
- * Limitations:
3852
- * - Certificate chain validation (CA trust) is not performed because
3853
- * Web Crypto does not provide chain validation APIs. Only the
3854
- * mathematical signature is verified against the embedded certificate.
3855
- * - CRL/OCSP revocation checking is not performed.
3856
- *
3857
- * @packageDocumentation
3858
- */
3859
- /**
3860
- * Result of verifying a single signature.
3861
- */
3862
- interface SignatureVerificationResult {
3863
- /** The signature field name. */
3864
- fieldName: string;
3865
- /** Subject CN from the certificate. */
3866
- signedBy: string;
3867
- /** Overall validity (integrity AND signature). */
3868
- valid: boolean;
3869
- /** Reason for signing (if present). */
3870
- reason?: string | undefined;
3871
- /** Whether the ByteRange hash matches the signed hash. */
3872
- integrityValid: boolean;
3873
- /** Whether the cryptographic signature is valid. */
3874
- certificateValid?: boolean | undefined;
3875
- /** Signing date (if present in signed attributes). */
3876
- signingDate?: Date | undefined;
3877
- }
3878
- /**
3879
- * Verify all signatures in a PDF.
3880
- *
3881
- * For each signature found:
3882
- * 1. Computes the hash of the ByteRange-covered bytes
3883
- * 2. Extracts the PKCS#7 structure
3884
- * 3. Verifies the message digest matches
3885
- * 4. Verifies the cryptographic signature against the certificate
3886
- *
3887
- * @param pdfBytes The PDF file bytes.
3888
- * @returns Array of verification results.
3889
- */
3890
- declare function verifySignatures(pdfBytes: Uint8Array): Promise<SignatureVerificationResult[]>;
3891
- /**
3892
- * Verify a single signature.
3893
- *
3894
- * Extracts the signed attributes from the PKCS#7 structure and
3895
- * verifies the signature using the certificate's public key.
3896
- *
3897
- * @param pdfBytes The PDF file bytes.
3898
- * @param byteRange The ByteRange array.
3899
- * @param signatureBytes The DER-encoded PKCS#7 signature.
3900
- * @param certificateBytes The DER-encoded X.509 certificate.
3901
- * @returns `true` if the signature is valid.
3902
- */
3903
- declare function verifySignature(pdfBytes: Uint8Array, byteRange: [number, number, number, number], signatureBytes: Uint8Array, certificateBytes: Uint8Array): Promise<boolean>;
3904
- //#endregion
3905
- //#region src/core/pdfDocument.d.ts
3906
- /**
3907
- * The 14 standard PDF fonts guaranteed to be available in every PDF
3908
- * viewer. These can be used without embedding font data.
3909
- */
3910
- declare const StandardFonts: {
3911
- readonly Courier: "Courier";
3912
- readonly CourierBold: "Courier-Bold";
3913
- readonly CourierOblique: "Courier-Oblique";
3914
- readonly CourierBoldOblique: "Courier-BoldOblique";
3915
- readonly Helvetica: "Helvetica";
3916
- readonly HelveticaBold: "Helvetica-Bold";
3917
- readonly HelveticaOblique: "Helvetica-Oblique";
3918
- readonly HelveticaBoldOblique: "Helvetica-BoldOblique";
3919
- readonly TimesRoman: "Times-Roman";
3920
- readonly TimesBold: "Times-Bold";
3921
- readonly TimesItalic: "Times-Italic";
3922
- readonly TimesBoldItalic: "Times-BoldItalic";
3923
- readonly Symbol: "Symbol";
3924
- readonly ZapfDingbats: "ZapfDingbats";
3925
- };
3926
- type StandardFontName = (typeof StandardFonts)[keyof typeof StandardFonts];
3927
- /**
3928
- * Options for font embedding.
3929
- */
3930
- interface EmbedFontOptions {
3931
- /** Whether to subset the font to reduce file size. Default: true. */
3932
- subset?: boolean | undefined;
3933
- /** OpenType feature flags. e.g., { kern: true, liga: true }. */
3934
- features?: Record<string, boolean> | undefined;
3935
- /** Custom name to use in the font dictionary's /BaseFont instead of the font's PostScript name. */
3936
- customName?: string | undefined;
3937
- }
3938
- /**
3939
- * Options for {@link PdfDocument.setTitle}.
3940
- */
3941
- interface SetTitleOptions {
3942
- /** When `true`, tell PDF viewers to display the document title in the window title bar. */
3943
- showInWindowTitleBar?: boolean | undefined;
3944
- }
3945
- /**
3946
- * The root document object. Create via {@link createPdf}.
3947
- *
3948
- * Manages:
3949
- * - Page collection (ordered)
3950
- * - Embedded resources (fonts, images)
3951
- * - Document metadata (title, author, dates, …)
3952
- * - Object-number allocation
3953
- */
3954
- declare class PdfDocument {
3955
- /**
3956
- * Load an existing PDF document from raw bytes, an ArrayBuffer, or a
3957
- * Base64-encoded string.
3958
- *
3959
- * This is the primary entry point for parsing existing PDFs. It
3960
- * validates the file header, parses the cross-reference structure,
3961
- * resolves the page tree and metadata, and returns a fully populated
3962
- * {@link PdfDocument} that can be inspected or further modified.
3963
- *
3964
- * @param data The PDF data as a `Uint8Array`, `ArrayBuffer`, or a
3965
- * Base64-encoded string.
3966
- * @param options Optional loading options (e.g. password, encryption).
3967
- * @returns A promise that resolves to the parsed PdfDocument.
3968
- *
3969
- * @example
3970
- * ```ts
3971
- * // From fetch (ArrayBuffer)
3972
- * const pdfBytes = await fetch('document.pdf').then(r => r.arrayBuffer());
3973
- * const doc = await PdfDocument.load(pdfBytes);
3974
- *
3975
- * // From a Base64 string
3976
- * const doc2 = await PdfDocument.load(base64String);
3977
- * ```
3978
- */
3979
- static load(data: Uint8Array | ArrayBuffer | string, options?: LoadPdfOptions): Promise<PdfDocument>;
3980
- /**
3981
- * Create a new, empty PDF document.
3982
- *
3983
- * This is the static-method equivalent of {@link createPdf}.
3984
- *
3985
- * ```ts
3986
- * const doc = PdfDocument.create();
3987
- * ```
3988
- */
3989
- static create(): PdfDocument;
3990
- /** Object registry — allocates indirect references. */
3991
- private readonly registry;
3992
- /** Pages in document order. */
3993
- private readonly pages;
3994
- /** Metadata fields. */
3995
- private readonly meta;
3996
- /** Counter for font resource names (F1, F2, …). */
3997
- private fontCounter;
3998
- /** Counter for image resource names (Im1, Im2, …). */
3999
- private imageCounter;
4000
- /** Counter for form XObject resource names (XF1, XF2, …). */
4001
- private formXObjectCounter;
4002
- /**
4003
- * @param registry Optional pre-populated object registry (used when
4004
- * loading an existing PDF so parsed objects are preserved).
4005
- */
4006
- constructor(registry?: PdfObjectRegistry);
4007
- /** Embedded fonts — maps base font name → FontRef. */
4008
- private readonly embeddedFonts;
4009
- /** Embedded images — maps an internal key → ImageRef. */
4010
- private readonly embeddedImages;
4011
- /**
4012
- * Add a page to the document.
4013
- *
4014
- * When called with a {@link PageSize} (or no argument), a new blank page
4015
- * is created. When called with an existing {@link PdfPage} instance
4016
- * (e.g. one returned by {@link copyPages}), that page is inserted
4017
- * directly.
4018
- *
4019
- * @param sizeOrPage A page size as `[width, height]` tuple,
4020
- * `{ width, height }` object, one of the
4021
- * {@link PageSizes} constants, or an existing
4022
- * {@link PdfPage} instance. Defaults to A4.
4023
- * @returns The {@link PdfPage} that was added.
4024
- */
4025
- addPage(sizeOrPage?: PageSize | PdfPage): PdfPage;
4026
- /**
4027
- * Return a specific page by zero-based index.
4028
- *
4029
- * @param index Zero-based page index.
4030
- * @returns The {@link PdfPage} at the given index.
4031
- * @throws If the index is out of range.
4032
- */
4033
- getPage(index: number): PdfPage;
4034
- /**
4035
- * Return all pages.
4036
- */
4037
- getPages(): readonly PdfPage[];
4038
- /**
4039
- * Return the page count.
4040
- */
4041
- getPageCount(): number;
4042
- /** The number of pages in this document. */
4043
- get pageCount(): number;
4044
- /**
4045
- * @internal Return the mutable internal pages array.
4046
- * Used by `pageManipulation.ts` and `documentMerge.ts`.
4047
- */
4048
- getInternalPages(): PdfPage[];
4049
- /**
4050
- * @internal Return the object registry for external modules.
4051
- */
4052
- getRegistry(): PdfObjectRegistry;
4053
- /**
4054
- * @internal Register all currently embedded fonts and CID encoders
4055
- * on the given page. Used when inserting or copying pages.
4056
- */
4057
- registerFontsOnPage(page: PdfPage): void;
4058
- /**
4059
- * @internal Return the embedded fonts map for cross-document operations.
4060
- */
4061
- getEmbeddedFonts(): ReadonlyMap<string, FontRef>;
4062
- /**
4063
- * @internal Add a pre-built page (from loading a parsed PDF).
4064
- * Unlike `addPage()`, this does NOT create a new blank page —
4065
- * it inserts a PdfPage that already carries original content.
4066
- */
4067
- _addLoadedPage(page: PdfPage): void;
4068
- /**
4069
- * @internal Advance font/image counters past names already used
4070
- * by loaded pages so new resources don't collide.
4071
- */
4072
- _advanceCounters(maxFont: number, maxImage: number, maxGState: number): void;
4073
- /**
4074
- * @internal Get the next font counter value and increment it.
4075
- */
4076
- allocateFontName(): string;
4077
- /**
4078
- * @internal Get the next image counter value and increment it.
4079
- */
4080
- allocateImageName(): string;
4081
- /**
4082
- * Insert a new blank page at the specified position.
4083
- *
4084
- * @param index Zero-based position (0 to pageCount inclusive).
4085
- * @param size Optional page size. Defaults to A4.
4086
- * @returns The newly created PdfPage.
4087
- */
4088
- insertPage(index: number, size?: PageSize): PdfPage;
4089
- /**
4090
- * Remove a page by its zero-based index.
4091
- *
4092
- * @param index Zero-based page index to remove.
4093
- * @throws RangeError if the index is out of bounds.
4094
- */
4095
- removePage(index: number): void;
4096
- /**
4097
- * Move a page from one position to another.
4098
- *
4099
- * @param fromIndex Current zero-based index of the page.
4100
- * @param toIndex Target zero-based index (after removal).
4101
- */
4102
- movePage(fromIndex: number, toIndex: number): void;
4103
- /**
4104
- * Copy pages from another document into this one.
4105
- *
4106
- * The copied pages are appended to the end of this document.
4107
- * Resources (fonts, images) are deeply cloned and re-registered
4108
- * in the target document's registry.
4109
- *
4110
- * @param sourceDoc The source document to copy pages from.
4111
- * @param indices Zero-based indices of pages to copy.
4112
- * @returns The newly created pages in this document.
4113
- */
4114
- copyPages(sourceDoc: PdfDocument, indices: number[]): Promise<PdfPage[]>;
4115
- /** Counter for unique TTF font keys (to distinguish multiple TTF embeds). */
4116
- private ttfCounter;
4117
- /**
4118
- * Maps TTF font resource name → EmbeddedFont and mutable PDF objects
4119
- * that need to be updated at save time with subsetted data.
4120
- */
4121
- private readonly ttfFonts;
4122
- /**
4123
- * Embed a font in the document.
4124
- *
4125
- * Accepts either:
4126
- * - A **standard font name** string (e.g. `"Helvetica"`) — embeds a
4127
- * Type 1 font reference (no font data needed).
4128
- * - A **Uint8Array** of TrueType font bytes — embeds a CIDFont Type 2
4129
- * composite font with /Identity-H encoding, /FontDescriptor, /ToUnicode
4130
- * CMap, and /FontFile2 stream.
4131
- *
4132
- * The returned {@link FontRef} includes `widthOfTextAtSize()` and
4133
- * `heightAtSize()` methods for text measurement.
4134
- *
4135
- * @param fontNameOrData Base font name string or raw TTF/OTF bytes.
4136
- * @param options Optional embedding options (subset, OpenType features).
4137
- * @returns A {@link FontRef} to pass to drawing methods.
4138
- */
4139
- embedFont(fontNameOrData: string | Uint8Array, options?: EmbedFontOptions): Promise<FontRef>;
4140
- /**
4141
- * Embed a standard (Type 1) font.
4142
- * @internal
4143
- */
4144
- private embedStandardFont;
4145
- /**
4146
- * Embed a TrueType font from raw bytes as a CIDFont Type 2.
4147
- * @internal
4148
- */
4149
- private embedTrueTypeFont;
4150
- /**
4151
- * Embed a CFF-based OpenType font from raw bytes as a CIDFont Type 0.
4152
- *
4153
- * CFF fonts use /CIDFontType0 (instead of /CIDFontType2 for TrueType),
4154
- * /FontFile3 with /Subtype /CIDFontType0C (instead of /FontFile2),
4155
- * and embed only the raw CFF table data (not the full OTF wrapper).
4156
- * No /CIDToGIDMap is needed since CFF fonts map CIDs directly.
4157
- *
4158
- * @internal
4159
- */
4160
- private embedCffFont;
4161
- /**
4162
- * Embed a PNG image.
4163
- *
4164
- * Fully decodes the PNG (including filter reconstruction and alpha
4165
- * channel separation) and creates a correct PDF image XObject.
4166
- * For images with transparency, a separate SMask XObject is created
4167
- * and referenced from the main image.
4168
- *
4169
- * @param pngData Raw PNG file bytes as a `Uint8Array` or `ArrayBuffer`.
4170
- * @returns An {@link ImageRef} to pass to `page.drawImage()`.
4171
- */
4172
- embedPng(pngData: Uint8Array | ArrayBuffer): ImageRef;
4173
- /**
4174
- * Embed a JPEG image.
4175
- *
4176
- * JPEG data can be embedded directly as a PDF stream with
4177
- * `DCTDecode` filter — no re-encoding is needed.
4178
- *
4179
- * @param jpegData Raw JPEG file bytes as a `Uint8Array` or `ArrayBuffer`.
4180
- * @returns An {@link ImageRef}.
4181
- */
4182
- embedJpeg(jpegData: Uint8Array | ArrayBuffer): Promise<ImageRef>;
4183
- /**
4184
- * Embed a WebP image.
4185
- *
4186
- * WebP cannot be directly embedded in PDF. This method decodes the
4187
- * WebP image to raw pixels (VP8/lossy, VP8L/lossless, or VP8+ALPH),
4188
- * then embeds as a FlateDecode image XObject. If the WebP has
4189
- * transparency, the alpha channel is embedded as a soft mask.
4190
- *
4191
- * @param webpData Raw WebP file bytes as a `Uint8Array` or `ArrayBuffer`.
4192
- * @returns An {@link ImageRef}.
4193
- */
4194
- embedWebP(webpData: Uint8Array | ArrayBuffer): ImageRef;
4195
- /**
4196
- * Embed a TIFF image.
4197
- *
4198
- * Decodes the TIFF image and creates a PDF image XObject with
4199
- * FlateDecode compression. For multi-page TIFFs, a specific page
4200
- * can be selected via options.
4201
- *
4202
- * @param tiffData Raw TIFF file bytes as a `Uint8Array` or `ArrayBuffer`.
4203
- * @param options Options (e.g., `{ page: 0 }` for multi-page TIFFs).
4204
- * @returns An {@link ImageRef}.
4205
- */
4206
- embedTiff(tiffData: Uint8Array | ArrayBuffer, options?: {
4207
- page?: number | undefined;
4208
- } | undefined): ImageRef;
4209
- /**
4210
- * Embed an image, auto-detecting the format from file headers.
4211
- *
4212
- * Inspects the first bytes to determine the image format (PNG, JPEG,
4213
- * WebP, or TIFF), then delegates to the appropriate embedding method.
4214
- *
4215
- * Supported formats:
4216
- * - **PNG**: `89 50 4E 47` — embedded via {@link embedPng}
4217
- * - **JPEG**: `FF D8 FF` — embedded via {@link embedJpeg}
4218
- * - **WebP**: `52 49 46 46` + `57 45 42 50` — embedded via {@link embedWebP}
4219
- * - **TIFF LE**: `49 49 2A 00` — embedded via {@link embedTiff}
4220
- * - **TIFF BE**: `4D 4D 00 2A` — embedded via {@link embedTiff}
4221
- *
4222
- * @param imageData Raw image file bytes (PNG, JPEG, WebP, or TIFF).
4223
- * @returns An {@link ImageRef} to pass to `page.drawImage()`.
4224
- * @throws If the image format cannot be detected.
4225
- *
4226
- * @example
4227
- * ```ts
4228
- * const bytes = new Uint8Array(await readFile('photo.jpg'));
4229
- * const image = await pdf.embedImage(bytes);
4230
- * page.drawImage(image, { x: 50, y: 400, width: 200, height: 150 });
4231
- * ```
4232
- */
4233
- embedImage(imageData: Uint8Array | ArrayBuffer): Promise<ImageRef>;
4234
- /**
4235
- * Embed pages from another PDF as Form XObjects.
4236
- *
4237
- * Each embedded page is turned into a self-contained Form XObject that
4238
- * can be painted onto any page via `page.drawPage()`. The source PDF's
4239
- * content streams are decoded and concatenated, and all referenced
4240
- * resources (fonts, images, etc.) are deep-cloned into this document's
4241
- * registry.
4242
- *
4243
- * @param data Raw PDF bytes (Uint8Array or ArrayBuffer).
4244
- * @param pageIndices Zero-based page indices to embed. Defaults to
4245
- * `[0]` (first page only).
4246
- * @returns Array of {@link EmbeddedPdfPage} handles.
4247
- *
4248
- * @example
4249
- * ```ts
4250
- * const [embeddedPage] = await doc.embedPdf(existingPdfBytes, [0]);
4251
- * page.drawPage(embeddedPage, { x: 50, y: 50, width: 300, height: 400 });
4252
- * ```
4253
- */
4254
- embedPdf(data: Uint8Array | ArrayBuffer, pageIndices?: number[], options?: EmbedPageOptions): Promise<EmbeddedPdfPage[]>;
4255
- /**
4256
- * Embed a single page (from this or another document) as a Form XObject.
4257
- *
4258
- * This is useful when you have an already-parsed PdfPage and want to
4259
- * stamp it onto other pages as a form XObject.
4260
- *
4261
- * @param page The PdfPage to embed.
4262
- * @param options Optional bounding box / transformation matrix.
4263
- * @returns An {@link EmbeddedPdfPage} handle.
4264
- */
4265
- embedPage(page: PdfPage, options?: EmbedPageOptions): EmbeddedPdfPage;
4266
- /**
4267
- * Embed multiple pages as Form XObjects in batch.
4268
- * Convenience wrapper around {@link embedPage}.
4269
- *
4270
- * @param pages Array of PdfPage instances to embed.
4271
- * @returns Array of {@link EmbeddedPdfPage} handles, one per input page.
4272
- */
4273
- embedPages(pages: PdfPage[]): EmbeddedPdfPage[];
4274
- /** Set the document title. */
4275
- setTitle(title: string, options?: SetTitleOptions): void;
4276
- /** Set the document author. */
4277
- setAuthor(author: string): void;
4278
- /** Set the document subject. */
4279
- setSubject(subject: string): void;
4280
- /** Set the document keywords. */
4281
- setKeywords(keywords: string | string[]): void;
4282
- /** Set the creator application name. */
4283
- setCreator(creator: string): void;
4284
- /** Set the producer string (defaults to `"modern-pdf"`). */
4285
- setProducer(producer: string): void;
4286
- /** Set the document creation date. */
4287
- setCreationDate(date: Date): void;
4288
- /** Set the document modification date. */
4289
- setModDate(date: Date): void;
4290
- /** Get the document title, or `undefined` if not set. */
4291
- getTitle(): string | undefined;
4292
- /** Get the document author, or `undefined` if not set. */
4293
- getAuthor(): string | undefined;
4294
- /** Get the document subject, or `undefined` if not set. */
4295
- getSubject(): string | undefined;
4296
- /** Get the document keywords, or `undefined` if not set. */
4297
- getKeywords(): string | undefined;
4298
- /** Get the creator application name, or `undefined` if not set. */
4299
- getCreator(): string | undefined;
4300
- /** Get the producer string. */
4301
- getProducer(): string | undefined;
4302
- /** Get the document creation date. */
4303
- getCreationDate(): Date | undefined;
4304
- /** Get the document modification date, or `undefined` if not set. */
4305
- getModDate(): Date | undefined;
4306
- /** The encryption handler, set when `encrypt()` is called. */
4307
- private encryptionHandler;
4308
- /**
4309
- * Configure encryption for this document.
4310
- *
4311
- * When encryption is set, the document will be encrypted on the next
4312
- * call to `save()`. The /Encrypt dictionary and file ID are
4313
- * generated automatically.
4314
- *
4315
- * @param options Encryption options (passwords, permissions, algorithm).
4316
- *
4317
- * @example
4318
- * ```ts
4319
- * const doc = createPdf();
4320
- * doc.addPage();
4321
- * doc.encrypt({
4322
- * userPassword: 'user123',
4323
- * ownerPassword: 'owner456',
4324
- * permissions: { printing: true, copying: false },
4325
- * algorithm: 'aes-256',
4326
- * });
4327
- * const bytes = await doc.save();
4328
- * ```
4329
- */
4330
- encrypt(options: EncryptOptions): Promise<void>;
4331
- /**
4332
- * Check whether this document has encryption configured.
4333
- *
4334
- * Returns `true` if `encrypt()` has been called on this document,
4335
- * or if the document was loaded from an encrypted PDF.
4336
- */
4337
- isEncrypted(): boolean;
4338
- /**
4339
- * Get the permission flags for this document, if encrypted.
4340
- *
4341
- * @returns The decoded permission flags, or `undefined` if the
4342
- * document is not encrypted.
4343
- */
4344
- getPermissions(): PdfPermissionFlags | undefined;
4345
- /**
4346
- * Get the encryption handler (for advanced use / testing).
4347
- * @internal
4348
- */
4349
- getEncryptionHandler(): PdfEncryptionHandler | undefined;
4350
- /** Original PDF bytes (set when loaded from an existing file). */
4351
- private originalBytes;
4352
- /**
4353
- * @internal Set the original bytes (called by the parser on load).
4354
- */
4355
- setOriginalBytes(bytes: Uint8Array): void;
4356
- /**
4357
- * @internal Get the original bytes.
4358
- */
4359
- getOriginalBytes(): Uint8Array | undefined;
4360
- /**
4361
- * Add a signature field to a page.
4362
- *
4363
- * This is a placeholder method that records the intent to sign.
4364
- * The actual signature creation happens in `sign()`.
4365
- *
4366
- * @param pageIndex Zero-based page index.
4367
- * @param rect Rectangle [x1, y1, x2, y2] for the visual appearance.
4368
- * @param name The signature field name (must be unique).
4369
- */
4370
- addSignatureField(pageIndex: number, rect: [number, number, number, number], name: string): void;
4371
- /** Pending signature field definitions. */
4372
- private readonly signatureFields;
4373
- /**
4374
- * Sign the PDF document.
4375
- *
4376
- * Returns the signed PDF bytes. Uses incremental save to preserve
4377
- * existing content and any previous signatures.
4378
- *
4379
- * @param fieldName The signature field name.
4380
- * @param options Signing options (certificate, private key, etc.).
4381
- * @returns The signed PDF bytes.
4382
- *
4383
- * @example
4384
- * ```ts
4385
- * const doc = await PdfDocument.load(pdfBytes);
4386
- * const signedBytes = await doc.sign('Signature1', {
4387
- * certificate: certDer,
4388
- * privateKey: keyDer,
4389
- * reason: 'Document approval',
4390
- * });
4391
- * ```
4392
- */
4393
- sign(fieldName: string, options: SignOptions): Promise<Uint8Array>;
4394
- /**
4395
- * Get information about all signatures in this document.
4396
- *
4397
- * @returns Array of signature info objects.
4398
- */
4399
- getSignatures(): PdfSignatureInfo[];
4400
- /**
4401
- * Verify all signatures in this document.
4402
- *
4403
- * @returns Array of verification results.
4404
- */
4405
- verifySignatures(): Promise<SignatureVerificationResult[]>;
4406
- /** The outline tree, lazily created. */
4407
- private outlineTree;
4408
- /**
4409
- * Get the outline (bookmark) tree for this document.
4410
- *
4411
- * If no outlines have been added, returns an empty tree.
4412
- *
4413
- * @returns The {@link PdfOutlineTree} for this document.
4414
- */
4415
- getOutlines(): PdfOutlineTree;
4416
- /**
4417
- * Add a top-level outline (bookmark) entry.
4418
- *
4419
- * Convenience method that creates or retrieves the outline tree and
4420
- * adds a new item pointing to the specified page.
4421
- *
4422
- * @param title The display title for the bookmark.
4423
- * @param pageIndex Zero-based page index to navigate to.
4424
- * @param options Optional visual style and behaviour settings.
4425
- * @returns The newly created {@link PdfOutlineItem}.
4426
- */
4427
- addOutline(title: string, pageIndex: number, options?: OutlineItemOptions & {
4428
- fit?: OutlineDestination['fit'];
4429
- top?: number;
4430
- left?: number;
4431
- zoom?: number;
4432
- }): PdfOutlineItem;
4433
- /**
4434
- * Replace the outline tree for this document.
4435
- *
4436
- * @param outlines The new outline tree.
4437
- */
4438
- setOutlines(outlines: PdfOutlineTree): void;
4439
- /** Raw XMP metadata string, if set. */
4440
- private xmpMetadataString;
4441
- /**
4442
- * Get the raw XMP metadata string, or `undefined` if not set.
4443
- */
4444
- getXmpMetadata(): string | undefined;
4445
- /**
4446
- * Set raw XMP metadata as an XML string.
4447
- *
4448
- * The string should be a valid XMP packet. Use
4449
- * {@link buildXmpMetadata} from `modern-pdf` to generate one
4450
- * from standard metadata fields.
4451
- *
4452
- * @param xmp The XMP XML string.
4453
- */
4454
- setXmpMetadata(xmp: string): void;
4455
- /** The document's structure tree (for tagged PDF), if created. */
4456
- private structureTree;
4457
- /** The document's natural language (BCP 47 tag, e.g. "en-US"). */
4458
- private documentLanguage;
4459
- /**
4460
- * Get the structure tree for this document, or `undefined` if
4461
- * no structure tree has been created.
4462
- *
4463
- * A structure tree is required for tagged PDF / PDF/UA compliance.
4464
- *
4465
- * @returns The {@link PdfStructureTree}, or `undefined`.
4466
- */
4467
- getStructureTree(): PdfStructureTree | undefined;
4468
- /**
4469
- * Create a new structure tree for this document.
4470
- *
4471
- * If a structure tree already exists, it is returned as-is.
4472
- * Call this to begin making the document accessible (tagged PDF).
4473
- *
4474
- * @returns The {@link PdfStructureTree} for this document.
4475
- */
4476
- createStructureTree(): PdfStructureTree;
4477
- /**
4478
- * Set the document's natural language.
4479
- *
4480
- * This is required by PDF/UA and should be a BCP 47 language tag
4481
- * (e.g. `"en"`, `"en-US"`, `"de-DE"`, `"ja"`).
4482
- *
4483
- * @param lang The BCP 47 language tag.
4484
- */
4485
- setLanguage(lang: string): void;
4486
- /**
4487
- * Get the document's natural language, or `undefined` if not set.
4488
- *
4489
- * @returns The BCP 47 language tag, or `undefined`.
4490
- */
4491
- getLanguage(): string | undefined;
4492
- /**
4493
- * Run accessibility checks on this document.
4494
- *
4495
- * Validates the document against PDF/UA requirements and general
4496
- * accessibility best practices.
4497
- *
4498
- * @returns An array of {@link AccessibilityIssue} objects.
4499
- */
4500
- checkAccessibility(): AccessibilityIssue[];
4501
- /** Viewer preferences, if set. */
4502
- private viewerPrefs;
4503
- /** Cached PdfViewerPreferences instance. */
4504
- private _viewerPrefsInstance?;
4505
- /**
4506
- * Get the viewer preferences for this document as a
4507
- * {@link PdfViewerPreferences} instance with getter/setter pairs.
4508
- *
4509
- * If no preferences have been set, a default (empty) instance is
4510
- * returned. The instance is cached so that repeated calls return
4511
- * the same object and mutations are preserved.
4512
- */
4513
- getViewerPreferences(): PdfViewerPreferences;
4514
- /**
4515
- * Set viewer preferences for this document.
4516
- *
4517
- * Controls how the document is displayed when opened in a PDF viewer
4518
- * (toolbar visibility, window sizing, print options, etc.).
4519
- *
4520
- * Accepts either a plain {@link ViewerPreferences} object or a
4521
- * {@link PdfViewerPreferences} class instance.
4522
- *
4523
- * @param prefs The viewer preferences to set.
4524
- */
4525
- setViewerPreferences(prefs: ViewerPreferences | PdfViewerPreferences): void;
4526
- /** The form instance, lazily created. */
4527
- private form;
4528
- /**
4529
- * Check whether this document has an AcroForm (interactive form).
4530
- *
4531
- * Returns `true` if a form has been created or if the document
4532
- * was loaded from a PDF that contains an /AcroForm dictionary.
4533
- */
4534
- hasForm(): boolean;
4535
- /**
4536
- * Get the interactive form (AcroForm) for this document.
4537
- *
4538
- * If the document does not yet have a form, an empty one is created.
4539
- * The form provides access to all form fields and supports fill,
4540
- * flatten, and field creation operations.
4541
- *
4542
- * @returns The {@link PdfForm} for this document.
4543
- */
4544
- getForm(): PdfForm;
4545
- /**
4546
- * Set the form for this document (used when loading parsed PDFs).
4547
- * @internal
4548
- */
4549
- setForm(form: PdfForm): void;
4550
- /**
4551
- * Draw an SVG image onto a page.
4552
- *
4553
- * @param pageIndex Zero-based page index.
4554
- * @param svgString The SVG markup string.
4555
- * @param options Rendering options (position, size).
4556
- */
4557
- drawSvg(pageIndex: number, svgString: string, options?: SvgRenderOptions): void;
4558
- /** The layer manager, lazily created. */
4559
- private layerManager;
4560
- /**
4561
- * Add a new optional content layer.
4562
- *
4563
- * @param name The display name for the layer.
4564
- * @param visible Whether the layer is visible by default.
4565
- * @returns The newly created {@link PdfLayer}.
4566
- */
4567
- addLayer(name: string, visible?: boolean): PdfLayer;
4568
- /**
4569
- * Get all layers in this document.
4570
- *
4571
- * @returns An array of {@link PdfLayer} objects.
4572
- */
4573
- getLayers(): PdfLayer[];
4574
- /** Attached file references. */
4575
- private readonly attachedFiles;
4576
- /** Document-level JavaScript actions — maps name → script source. */
4577
- private readonly javaScripts;
4578
- /**
4579
- * Attach a file to this PDF document.
4580
- *
4581
- * @param name File name.
4582
- * @param data File data.
4583
- * @param mimeType MIME type string.
4584
- * @param options Optional description.
4585
- */
4586
- attachFile(name: string, data: Uint8Array, mimeType: string, options?: {
4587
- description?: string | undefined;
4588
- }): void;
4589
- /**
4590
- * Get all file attachments in this document.
4591
- *
4592
- * Note: Currently returns information about files attached via
4593
- * this API. For parsing attachments from loaded PDFs, use the
4594
- * lower-level `getAttachments()` function.
4595
- *
4596
- * @returns An array of embedded file metadata.
4597
- */
4598
- getAttachments(): EmbeddedFile[];
4599
- /**
4600
- * Add a document-level JavaScript action.
4601
- *
4602
- * The script is registered in the catalog's `/Names` dictionary under
4603
- * the `/JavaScript` name tree. When a conforming viewer opens the
4604
- * document, scripts listed here are executed automatically (in name
4605
- * order).
4606
- *
4607
- * @param name A unique name for this JavaScript entry.
4608
- * @param script The JavaScript source code.
4609
- *
4610
- * @example
4611
- * ```ts
4612
- * doc.addJavaScript('init', 'app.alert("Hello from PDF JavaScript!");');
4613
- * ```
4614
- */
4615
- addJavaScript(name: string, script: string): void;
4616
- /**
4617
- * Add a text watermark to all pages in the document.
4618
- *
4619
- * @param options Watermark appearance options.
4620
- */
4621
- addWatermark(options: WatermarkOptions): void;
4622
- /**
4623
- * Create a soft mask Form XObject that can be used with
4624
- * {@link PdfPage.applySoftMask}.
4625
- *
4626
- * The builder callback receives a {@link SoftMaskBuilder} with methods
4627
- * for generating grayscale content where white (`1`) represents fully
4628
- * opaque regions and black (`0`) represents fully transparent regions.
4629
- *
4630
- * The returned {@link SoftMaskRef} is passed to
4631
- * {@link PdfPage.applySoftMask} to activate the mask for subsequent
4632
- * drawing operations on that page.
4633
- *
4634
- * @param width Width of the mask in points.
4635
- * @param height Height of the mask in points.
4636
- * @param builder Callback that draws the mask content.
4637
- * @returns A reference to the soft mask Form XObject.
4638
- *
4639
- * @example
4640
- * ```ts
4641
- * const mask = doc.createSoftMask(200, 200, (b) => {
4642
- * // White background = fully opaque
4643
- * b.drawRectangle(0, 0, 200, 200, 1);
4644
- * // Black circle = fully transparent hole
4645
- * b.drawCircle(100, 100, 80, 0);
4646
- * });
4647
- * page.applySoftMask(mask);
4648
- * page.drawRectangle({ x: 50, y: 50, width: 200, height: 200, color: rgb(1, 0, 0) });
4649
- * page.clearSoftMask();
4650
- * ```
4651
- */
4652
- createSoftMask(width: number, height: number, builder: (ops: SoftMaskBuilder) => void): SoftMaskRef;
4653
- /**
4654
- * Apply all pending redactions across all pages.
4655
- *
4656
- * Redaction marks are added to individual pages using
4657
- * `page.markForRedaction()`. This method draws the redaction
4658
- * rectangles on all pages that have pending marks.
4659
- */
4660
- applyRedactions(): void;
4661
- /**
4662
- * Create an independent deep copy of this document.
4663
- *
4664
- * The copy is produced by serializing the document to bytes and then
4665
- * re-parsing those bytes. This guarantees that the returned
4666
- * `PdfDocument` is completely independent — mutations to the copy
4667
- * do not affect the original, and vice versa.
4668
- *
4669
- * @returns A new `PdfDocument` that is a deep copy of this one.
4670
- *
4671
- * @example
4672
- * ```ts
4673
- * const doc = createPdf();
4674
- * doc.addPage(PageSizes.A4);
4675
- * const clone = await doc.copy();
4676
- * clone.addPage(PageSizes.Letter); // does not affect `doc`
4677
- * ```
4678
- */
4679
- copy(): Promise<PdfDocument>;
4680
- /**
4681
- * Serialize the document to a `Uint8Array`.
4682
- *
4683
- * @param options Compression and serialization options.
4684
- * @returns The complete PDF file as bytes.
4685
- */
4686
- save(options?: PdfSaveOptions): Promise<Uint8Array>;
4687
- /**
4688
- * Serialize the document as a `ReadableStream<Uint8Array>`.
4689
- *
4690
- * Ideal for streaming responses in edge/serverless environments.
4691
- *
4692
- * @param options Compression and serialization options.
4693
- */
4694
- saveAsStream(options?: PdfSaveOptions): ReadableStream<Uint8Array>;
4695
- /**
4696
- * Serialize the document to a `Blob`.
4697
- *
4698
- * Convenient for client-side download links.
4699
- *
4700
- * @param options Compression and serialization options.
4701
- */
4702
- saveAsBlob(options?: PdfSaveOptions): Promise<Blob>;
4703
- /**
4704
- * Serialize the document to a Base64-encoded string.
4705
- *
4706
- * Useful for embedding PDFs in JSON payloads, data URIs, or
4707
- * transferring over text-only channels.
4708
- *
4709
- * @param options Standard save options plus an optional `dataUri`
4710
- * flag. When `dataUri` is `true`, the returned
4711
- * string is prefixed with
4712
- * `data:application/pdf;base64,`.
4713
- * @returns A Base64-encoded string of the PDF bytes.
4714
- *
4715
- * @example
4716
- * ```ts
4717
- * const b64 = await doc.saveAsBase64();
4718
- * const dataUri = await doc.saveAsBase64({ dataUri: true });
4719
- * // dataUri === "data:application/pdf;base64,JVBERi0..."
4720
- * ```
4721
- */
4722
- saveAsBase64(options?: PdfSaveOptions & {
4723
- dataUri?: boolean;
4724
- }): Promise<string>;
4725
- /**
4726
- * Finalize all pages and build the catalog / page tree / info dict.
4727
- */
4728
- private buildStructure;
4729
- /**
4730
- * Subset all embedded TrueType fonts.
4731
- *
4732
- * Called at save time, after all text has been drawn. For each TTF
4733
- * font, this:
4734
- * 1. Calls {@link subsetFont} with the used glyph set
4735
- * 2. Updates the `/FontFile2` stream data with the (possibly subsetted) font bytes
4736
- * 3. Updates the `/Length1` in the font file dict
4737
- * 4. Rebuilds the `/W` (widths) array for the CIDFont dict
4738
- * 5. Rebuilds the `/ToUnicode` CMap stream
4739
- *
4740
- * Since WASM subsetting is not yet available, the fallback returns
4741
- * the full font unchanged. But the /W array and /ToUnicode CMap
4742
- * are rebuilt to only include used glyphs, reducing PDF overhead.
4743
- *
4744
- * @internal
4745
- */
4746
- private subsetTtfFonts;
4747
- }
4748
- /**
4749
- * Create a new, empty PDF document.
4750
- *
4751
- * ```ts
4752
- * const doc = createPdf();
4753
- * ```
4754
- */
4755
- declare function createPdf(): PdfDocument;
4756
- //#endregion
4757
- export { DrawLineOptions as $, colorToComponents as $n, PdfLayerManager as $t, LoadPdfOptions as A, Angle as An, ColorStop as At, encodePermissions as B, rotationMatrix as Bn, linearGradient as Bt, ViewerPreferences as C, BlendMode as Cn, renderMultiPageTable as Ct, OutlineItemOptions as D, ParseSpeeds as Dn, QrCodeOptions as Dt, OutlineDestination as E, LineJoinStyle as En, QrCodeMatrix as Et, EncryptAlgorithm as F, degreesToRadians as Fn, RadialGradientFill as Ft, buildCatalog as G, translate as Gn, EmbeddedPdfPage as Gt, DocumentMetadata as H, scale as Hn, tilingPattern as Ht, EncryptOptions as I, radians as In, RadialGradientOptions as It, buildPageTree as J, GrayscaleColor as Jn, RedactionOptions as Jt, buildDocumentStructure as K, CmykColor as Kn, embedPageAsFormXObject as Kt, PdfEncryptionHandler as L, radiansToDegrees as Ln, TilingPatternOptions as Lt, PdfSaveOptions as M, Radians as Mn, LinearGradientOptions as Mt, PdfWriter as N, concatMatrix as Nn, NormalizedStop as Nt, PdfOutlineItem as O, TextAlignment as On, encodeQrCode as Ot, serializePdf as P, degrees as Pn, PatternFill as Pt, DrawImageOptions as Q, cmyk as Qn, PdfLayer as Qt, PdfPermissionFlags as R, restoreState as Rn, buildGradientObjects as Rt, PdfViewerPreferences as S, StructureType as Sn, TextRun as St, parseViewerPreferences as T, LineCapStyle as Tn, ErrorCorrectionLevel as Tt, DocumentStructure as U, setGraphicsState as Un, DrawPageOptions as Ut, CatalogOptions as V, saveState as Vn, radialGradient as Vt, PageEntry as W, skew as Wn, EmbedPageOptions as Wt, DrawCircleOptions as X, applyFillColor as Xn, getRedactionMarks as Xt, formatPdfDate as Y, RgbColor as Yn, applyRedactions as Yt, DrawEllipseOptions as Z, applyStrokeColor as Zn, markForRedaction as Zt, PdfSignatureInfo as _, createAnnotation as _n, PageContent as _t, StandardFonts as a, SvgDrawCommand as an, setFillColorCmyk as ar, FontRef as at, getSignatures as b, PdfStructureTree as bn, TableRenderResult as bt, verifySignature as c, parseSvgColor as cn, setFillingColor as cr, PageSizes as ct, addWatermark as d, AnnotationFlags as dn, setStrokeColorGray as dr, SoftMaskRef as dt, beginLayerContent as en, componentsToColor as er, DrawQrCodeOptions as et, addWatermarkToPage as f, AnnotationOptions as fn, setStrokeColorRgb as fr, TransparencyGroupOptions as ft, getAttachments as g, buildAnnotationDict as gn, NestedTableContent as gt, buildEmbeddedFilesNameTree as h, annotationFromDict as hn, MultiPageTableResult as ht, StandardFontName as i, svgToPdfOperators as in, setFillColor as ir, DrawTextOptions as it, loadPdf as j, Degrees as jn, GradientFill as jt, PdfOutlineTree as k, TextRenderingMode as kn, qrCodeToOperators as kt, verifySignatures as l, parseSvgPath as ln, setStrokeColor as lr, PdfPage as lt, attachFile as m, PdfAnnotation as mn, setStrokingColor as mr, DrawTableOptions as mt, PdfDocument as n, SvgRenderOptions as nn, rgb as nr, DrawSquareOptions as nt, createPdf as o, SvgElement as on, setFillColorGray as or, ImageRef as ot, EmbeddedFile as p, AnnotationType as pn, setStrokeColorSpace as pr, CellContent as pt, buildInfoDict as q, Color as qn, RedactionMark as qt, SetTitleOptions as r, drawSvgOnPage as rn, setColorSpace as rr, DrawSvgPathOptions as rt, SignatureVerificationResult as s, parseSvg as sn, setFillColorRgb as sr, PageSize as st, EmbedFontOptions as t, endLayerContent as tn, grayscale as tr, DrawRectangleOptions as tt, WatermarkOptions as u, parseSvgTransform as un, setStrokeColorCmyk as ur, SoftMaskBuilder as ut, SignOptions as v, AccessibilityIssue as vn, TableCell as vt, buildViewerPreferencesDict as w, ImageAlignment as wn, renderTable as wt, signPdf as x, StructureElementOptions as xn, TableRow as xt, VisibleSignatureOptions as y, PdfStructureElement as yn, TableColumn as yt, decodePermissions as z, rotate as zn, buildPatternObjects as zt };
4758
- //# sourceMappingURL=pdfDocument-Bi-NoyXv.d.mts.map