@ironsoftware/ironpdf 2026.2.1 → 2026.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/package.json +2 -2
  2. package/src/index.d.ts +1 -0
  3. package/src/index.d.ts.map +1 -1
  4. package/src/index.js +4 -2
  5. package/src/index.js.map +1 -1
  6. package/src/index.ts +2 -2
  7. package/src/internal/IronPdfEngine.ProtoFiles/iron_pdf_service.proto +2 -0
  8. package/src/internal/IronPdfEngine.ProtoFiles/qpdf.proto +17 -0
  9. package/src/internal/generated_proto/iron_pdf_service.d.ts +2 -0
  10. package/src/internal/generated_proto/iron_pdf_service.d.ts.map +1 -1
  11. package/src/internal/generated_proto/iron_pdf_service.ts +2 -0
  12. package/src/internal/generated_proto/ironpdfengineproto/IronPdfService.d.ts +14 -0
  13. package/src/internal/generated_proto/ironpdfengineproto/IronPdfService.d.ts.map +1 -1
  14. package/src/internal/generated_proto/ironpdfengineproto/IronPdfService.ts +18 -0
  15. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestIdP.d.ts +10 -0
  16. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestIdP.d.ts.map +1 -0
  17. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestIdP.js +4 -0
  18. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestIdP.js.map +1 -0
  19. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestIdP.ts +13 -0
  20. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestStreamP.d.ts +18 -0
  21. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestStreamP.d.ts.map +1 -0
  22. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestStreamP.js +4 -0
  23. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestStreamP.js.map +1 -0
  24. package/src/internal/generated_proto/ironpdfengineproto/QPdfCompressInMemoryRequestStreamP.ts +21 -0
  25. package/src/internal/grpc_layer/pdfium/compress.d.ts +7 -0
  26. package/src/internal/grpc_layer/pdfium/compress.d.ts.map +1 -1
  27. package/src/internal/grpc_layer/pdfium/compress.js +81 -1
  28. package/src/internal/grpc_layer/pdfium/compress.js.map +1 -1
  29. package/src/internal/grpc_layer/pdfium/compress.ts +121 -0
  30. package/src/internal/grpc_layer/pdfium/pdfa.d.ts +1 -0
  31. package/src/internal/grpc_layer/pdfium/pdfa.d.ts.map +1 -1
  32. package/src/internal/grpc_layer/pdfium/pdfa.js +22 -1
  33. package/src/internal/grpc_layer/pdfium/pdfa.js.map +1 -1
  34. package/src/internal/grpc_layer/pdfium/pdfa.ts +26 -0
  35. package/src/internal/grpc_layer/pdfium/signing.d.ts +2 -1
  36. package/src/internal/grpc_layer/pdfium/signing.d.ts.map +1 -1
  37. package/src/internal/grpc_layer/pdfium/signing.js +38 -1
  38. package/src/internal/grpc_layer/pdfium/signing.js.map +1 -1
  39. package/src/internal/grpc_layer/pdfium/signing.ts +44 -1
  40. package/src/public/pdfDocument.d.ts +57 -2
  41. package/src/public/pdfDocument.d.ts.map +1 -1
  42. package/src/public/pdfDocument.js +118 -1
  43. package/src/public/pdfDocument.js.map +1 -1
  44. package/src/public/pdfDocument.ts +2226 -2074
  45. package/src/public/signature.d.ts +33 -0
  46. package/src/public/signature.d.ts.map +1 -1
  47. package/src/public/signature.ts +34 -0
@@ -1,2074 +1,2226 @@
1
- import {Buffer} from "buffer";
2
- import {
3
- BarcodeStampOptions,
4
- BarcodeType, ChangeTrackingModes,
5
- ChromePdfRenderOptions,
6
- DigitalSignature,
7
- HtmlAffix,
8
- HtmlFilePath,
9
- HtmlStampOptions,
10
- HtmlString,
11
- HttpLoginCredentials,
12
- ImageBuffer,
13
- ImageFilePath,
14
- ImageStampOptions,
15
- ImageToPdfOptions,
16
- ImageType,
17
- PageInfo,
18
- PageRotation,
19
- PdfInput,
20
- PdfPageSelection,
21
- PdfPaperSize,
22
- PdfPassword, PdfPermission,
23
- SaveOptions,
24
- TextAffix,
25
- TextStampOptions,
26
- } from "./types";
27
-
28
- import {
29
- barcodeTypeSchema, booleanSchema, bufferArraySchema, bufferSchema, changeTrackingModesSchema,
30
- filePathSchema,
31
- htmlFilePathSchema,
32
- htmlStringSchema,
33
- imageBufferSchema,
34
- imageFilePathSchema,
35
- mapStringSchema,
36
- numberSchema, pdfFilePathSchema,
37
- pdfInputSchema,
38
- pdfPageSelectionSchema, pdfPasswordSchema, saveOptionsSchema, stringArraySchema,
39
- stringSchema, urlSchema
40
- } from "../internal/zod/typeSchema";
41
- import {z} from "zod";
42
- import {pdfPermissionSchema} from "../internal/zod/securitySchema";
43
- import {pdfDocumentSchema} from "../internal/zod/pdfDocumentSchema";
44
- import {
45
- barcodeStampOptionsSchema,
46
- htmlStampOptionsSchema,
47
- imageStampOptionsSchema,
48
- textStampOptionsSchema
49
- } from "../internal/zod/stampSchema";
50
- import {htmlAffixSchema, textAffixSchema} from "../internal/zod/affixSchema";
51
- import {digitalSignatureSchema} from "../internal/zod/signatureSchema";
52
- import {imageToPdfOptionsSchema, imageTypeSchema} from "../internal/zod/imageSchema";
53
- import {pdfPaperSizeSchema} from "../internal/zod/paperSchema";
54
- import {pageRotationSchema} from "../internal/zod/pageSchema";
55
- import {chromePdfRenderOptionsSchema, httpLoginCredentialsSchema} from "../internal/zod/renderSchema";
56
- import {
57
- getFileName,
58
- getImageExtType,
59
- separateImageBufferOrImagePathInput,
60
- separatePdfInput
61
- } from "../internal/grpc_layer/util";
62
- import fs from "fs";
63
- import {mergePdfs, renderHtmlToPdf, renderHtmlZipToPdf, renderUrlToPdf, renderHtmlFileToPdf} from "../internal/grpc_layer/chrome/render";
64
- import {disposePdf, getBinaryData, openPdfFileBuffer} from "../internal/grpc_layer/pdfium/io";
65
- import {Access} from "../internal/access";
66
- import {renderImagesBufferToPdf, renderImagesFilesToPdf} from "../internal/grpc_layer/chrome/image";
67
- import {compressImage, compressStructTree} from "../internal/grpc_layer/pdfium/compress";
68
- import {
69
- duplicate,
70
- getPageInfo,
71
- insertPdf,
72
- removePage,
73
- resizePage,
74
- setPageRotation
75
- } from "../internal/grpc_layer/pdfium/page";
76
- import {extractRawImages, rasterizeToImageBuffers} from "../internal/grpc_layer/pdfium/image";
77
- import Jimp from "jimp";
78
- import {extractAllText, replaceText} from "../internal/grpc_layer/pdfium/text";
79
- import {PdfAVersions, PdfUAVersions, toPdfA, toPdfUA} from "../internal/grpc_layer/pdfium/pdfa";
80
- import {getMetadataDict, removeMetadata, setMetadata, setMetadataDict} from "../internal/grpc_layer/pdfium/metadata";
81
- import {getSignatureCount, signPdf} from "../internal/grpc_layer/pdfium/signing";
82
- import {addHtmlAffix, addTextAffix} from "../internal/grpc_layer/pdfium/headerFooter";
83
- import {stampBarcode, stampHtml, stampImage, stampText} from "../internal/grpc_layer/chrome/stamp";
84
- import {addBackgroundForeground} from "../internal/grpc_layer/pdfium/BackgroundForeground";
85
- import {
86
- getPermission,
87
- removePasswordsAndEncryption,
88
- setOwnerPasswords, setSecurity,
89
- setUserPasswords
90
- } from "../internal/grpc_layer/pdfium/security";
91
- import { NaturalLanguages } from "./naturalLanguages";
92
-
93
- /**
94
- * Represents a PDF document. Allows: loading, editing, manipulating, merging, signing printing and saving PDFs.
95
- *
96
- * @remark Make sure that you call {@link PdfDocument.close} or {@link cleanUp} to free the memory, when you stop using the PdfDocument object.
97
- */
98
- export class PdfDocument{
99
-
100
- //#region io
101
-
102
- /**
103
- * Open or Create a PdfDocument from a {@link PdfInput}
104
- * @param pdfInput {@link PdfInput}
105
- * @param options including {@link PdfPassword} {@link ChromePdfRenderOptions} {@link HttpLoginCredentials} mainHtmlFile
106
- */
107
- public static async open(
108
- pdfInput: PdfInput,
109
- options?: {
110
- /**
111
- * required for open a protected PDF file
112
- * @default undefined
113
- */
114
- password?: PdfPassword | undefined;
115
- /**
116
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
117
- * @default undefined
118
- */
119
- renderOptions?: ChromePdfRenderOptions | undefined;
120
- /**
121
- * Apply httpLoginCredentials if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
122
- * @default undefined
123
- */
124
- httpLoginCredentials?: HttpLoginCredentials | undefined;
125
- /**
126
- * Apply mainHtmlFile if PdfInput is {@link ZipFilePath}
127
- * @default index.html
128
- */
129
- mainHtmlFile?: string | undefined;
130
- /**
131
- * Optionally track changes to the document (for use with incremental saves)
132
- * @default {@link ChangeTrackingModes.AutoChangeTracking}
133
- */
134
- trackChanges?: ChangeTrackingModes | undefined;
135
- // /**
136
- // * Apply baseUrl if
137
- // * The HTML base URL for which references to external CSS, Javascript and Image files will be relative.
138
- // * @default undefined
139
- // */
140
- // baseUrl ?: string | undefined; //not supported
141
- } | undefined
142
- ): Promise<PdfDocument> {
143
- return z.function()
144
- .args(
145
- pdfInputSchema,
146
- z.object({
147
- password: pdfPasswordSchema.optional(),
148
- renderOptions: chromePdfRenderOptionsSchema.optional(),
149
- httpLoginCredentials: httpLoginCredentialsSchema.optional(),
150
- mainHtmlFile: stringSchema.optional(),
151
- trackChanges: changeTrackingModesSchema.optional(),
152
- }).optional()
153
- )
154
- .returns(z.promise(pdfDocumentSchema))
155
- .implement(this.internal_open.bind(this))
156
- (pdfInput, options);
157
- }
158
-
159
- /**
160
- * Open a PdfDocument from .pdf file
161
- * @param pdfFilePath A path to .pdf file
162
- * @param Optionally track changes to the document (for use with incremental saves)
163
- */
164
- public static async fromFile(
165
- pdfFilePath: string, trackChanges?: ChangeTrackingModes | undefined
166
- ): Promise<PdfDocument> {
167
- return z.function()
168
- .args(
169
- pdfFilePathSchema,
170
- changeTrackingModesSchema.optional()
171
- )
172
- .returns(z.promise(pdfDocumentSchema))
173
- .implement(this.internal_fromFile.bind(this))
174
- (pdfFilePath, trackChanges);
175
- }
176
-
177
- /**
178
- * Create a PdfDocument from an Url
179
- * @param url A website Url
180
- * @param options including {@link ChromePdfRenderOptions}
181
- */
182
- public static async fromUrl(
183
- url: URL | string,
184
- options?: {
185
- /**
186
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
187
- * @default undefined
188
- */
189
- renderOptions?: ChromePdfRenderOptions | undefined;
190
- } | undefined
191
- ): Promise<PdfDocument> {
192
- return z.function()
193
- .args(
194
- z.union([urlSchema, stringSchema]),
195
- z.object({
196
- renderOptions: chromePdfRenderOptionsSchema.optional(),
197
- }).optional()
198
- )
199
- .returns(z.promise(pdfDocumentSchema))
200
- .implement(this.internal_fromUrl.bind(this))
201
- (url, options);
202
- }
203
-
204
- /**
205
- * Creates a PDF file from a local Zip file, and returns it as a {@link PdfDocument}.
206
- * IronPDF is a W3C standards compliant HTML rendering based on Google's Chromium browser.
207
- * If your output PDF does not look as expected:
208
- *
209
- * - Validate your HTML file using https://validator.w3.org/ &amp; CSS https://jigsaw.w3.org/css-validator/
210
- *
211
- * - To debug HTML, view the file in Chrome web browser's print preview which will work almost exactly as IronPDF.
212
- *
213
- * - Read our detailed documentation on pixel perfect HTML to PDF: https://ironpdf.com/tutorials/pixel-perfect-html-to-pdf/
214
- *
215
- * @param zipFilePath Path to a Zip to be rendered as a PDF.
216
- * @param options including {@link ChromePdfRenderOptions} and `mainHtmlFile` a main .html file default: `index.html`
217
- */
218
- public static async fromZip(
219
- zipFilePath: string,
220
- options?: {
221
- /**
222
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
223
- * @default undefined
224
- */
225
- renderOptions?: ChromePdfRenderOptions | undefined;
226
- /**
227
- * a main .html file default: `index.html`
228
- */
229
- mainHtmlFile?: string | undefined;
230
- } | undefined
231
- ): Promise<PdfDocument> {
232
- return z.function()
233
- .args(
234
- stringSchema,
235
- z.object({
236
- renderOptions: chromePdfRenderOptionsSchema.optional(),
237
- mainHtmlFile: stringSchema.optional()
238
- }).optional()
239
- )
240
- .returns(z.promise(pdfDocumentSchema))
241
- .implement(this.internal_fromZip.bind(this))
242
- (zipFilePath, options);
243
- }
244
-
245
- /**
246
- * Creates a PDF file from a Html string, and returns it as an {@link PdfDocument} object which can be edited and saved to disk or served on a website.
247
- *
248
- * ------------------------------------------------
249
- *
250
- * **Usage:**
251
- * ```ts
252
- * const pdf = await fromHtml(htmlStringOrHtmlFilePath, renderOptions);
253
- * ```
254
- *
255
- * ------------------------------------------------
256
- *
257
- * @param htmlStringOrHtmlFilePath The Html to be rendered as a PDF.
258
- * @param options including {@link ChromePdfRenderOptions}
259
- * @returns A `PdfDocument` generated from the provided HTML file.
260
- *
261
- * ---
262
- * ### Important Notes:
263
- *
264
- * 🐳 **Docker Limitation:**
265
- * This method **does not work** for **HTML file path** when the application runs inside a Docker environment
266
- * due to rendering engine restrictions.
267
- * In such cases, use `fromZip()` instead.
268
- *
269
- * 📄 **Input:** Requires access to a local HTML file on disk if htmlFilePath is passing.
270
- *
271
- * ---
272
- * ### Related Methods:
273
- * 📌 `fromZip()` — Recommended alternative for rendering from HTML file when running inside Docker.
274
- */
275
- public static async fromHtml(
276
- htmlStringOrHtmlFilePath: string,
277
- options?: {
278
- /**
279
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
280
- * @default undefined
281
- */
282
- renderOptions?: ChromePdfRenderOptions | undefined;
283
- } | undefined
284
- ): Promise<PdfDocument> {
285
- return z.function()
286
- .args(
287
- stringSchema,
288
- z.object({
289
- renderOptions: chromePdfRenderOptionsSchema.optional(),
290
- }).optional()
291
- )
292
- .returns(z.promise(pdfDocumentSchema))
293
- .implement(this.internal_fromHtml.bind(this))
294
- (htmlStringOrHtmlFilePath, options);
295
- }
296
-
297
- /**
298
- * Converts multiple image files to a PDF document. Each image creates 1 page which matches the image
299
- * dimensions. The default PaperSize is A4. You can set it via ImageToPdfConverter.PaperSize.
300
- * Note: Imaging.ImageBehavior.CropPage will set PaperSize equal to ImageSize.
301
- * @param images The image file path name(s) or {@link ImageBuffer} object(s)
302
- * @param options including {@link ImageToPdfOptions}
303
- */
304
- public static async fromImage(
305
- images: ImageFilePath | ImageFilePath[] | ImageBuffer | ImageBuffer[],
306
- options?: {
307
- /**
308
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
309
- * @default undefined
310
- */
311
- imageToPdfOptions?: ImageToPdfOptions | undefined;
312
- }
313
- ): Promise<PdfDocument> {
314
- return z.function()
315
- .args(
316
- z.union([imageFilePathSchema, z.array(imageFilePathSchema), imageBufferSchema, z.array(imageBufferSchema)]),
317
- z.object({
318
- imageToPdfOptions: imageToPdfOptionsSchema.optional(),
319
- }).optional()
320
- )
321
- .returns(z.promise(pdfDocumentSchema))
322
- .implement(this.internal_fromImage.bind(this))
323
- (images, options);
324
- }
325
-
326
- /**
327
- * Static method that joins (concatenates) multiple PDF documents together into one compiled PDF document.
328
- * If the PDF contains form fields the form field in the resulting PDF's name will be appended with '_{index}' e.g. 'Name' will be 'Name_0'
329
- * @param pdfs array of PDF
330
- */
331
- public static async mergePdf(pdfs: PdfInput[]): Promise<PdfDocument> {
332
- return z.function()
333
- .args(
334
- z.array(pdfInputSchema)
335
- )
336
- .returns(z.promise(pdfDocumentSchema))
337
- .implement(this.internal_mergePdf.bind(this))
338
- (pdfs);
339
- }
340
-
341
- /**
342
- * Saves the PdfDocument to a file.
343
- * @param filePath Target file path
344
- * @param saveOptions see {@link SaveOptions}
345
- */
346
- public saveAs(filePath: string, saveOptions?: SaveOptions | undefined): Promise<void> {
347
- return z.function()
348
- .args(
349
- stringSchema,
350
- saveOptionsSchema.optional()
351
- )
352
- .returns(z.promise(z.void()))
353
- .implement(this.internal_saveAs.bind(this))
354
- (filePath, saveOptions);
355
- }
356
-
357
- /**
358
- * Saves the PdfDocument to a binary (Buffer)
359
- * @param saveOptions see {@link SaveOptions}
360
- */
361
- public async saveAsBuffer(saveOptions?: SaveOptions | undefined): Promise<Buffer> {
362
- return z.function()
363
- .args(
364
- saveOptionsSchema.optional()
365
- )
366
- .returns(z.promise(bufferSchema))
367
- .implement(this.internal_saveAsBuffer.bind(this))
368
- (saveOptions);
369
- }
370
-
371
- //#endregion
372
-
373
- //#region compress
374
- /**
375
- * Compress existing PDF images using JPG encoding and the specified settings
376
- * @param imageQuality Quality (1 - 100) to use during compression
377
- * @param scaleToVisibleSize Scale down the image resolution according to its visible size in the PDF document
378
- */
379
- public async compressSize(
380
- imageQuality: number,
381
- scaleToVisibleSize = false
382
- ): Promise<void> {
383
- return await z.function()
384
- .args(
385
- numberSchema,
386
- booleanSchema.optional()
387
- )
388
- .returns(z.promise(z.void()))
389
- .implement(this.internal_compressSize.bind(this))
390
- (imageQuality, scaleToVisibleSize);
391
- }
392
-
393
- /**
394
- * Remove document struct tree information which describes the logical layout of the document.
395
- * Removing the "structure tree" can significantly reduce the disk space used by the document.
396
- * Removing the "structure tree" of a complicated document can negatively impact text selection.
397
- */
398
- public async compressStructTree(): Promise<void> {
399
- return this.internal_compressStructTree()
400
- }
401
-
402
- //#endregion
403
-
404
- //#region page
405
- /**
406
- * Gets information of all pages in the PdfDocument
407
- */
408
- public async getPagesInfo(): Promise<PageInfo[]> {
409
- return this.internal_getPagesInfo()
410
- }
411
-
412
- /**
413
- * Gets the number of pages in the PdfDocument.
414
- */
415
- public async getPageCount(): Promise<number> {
416
- return this.internal_getPageCount()
417
- }
418
-
419
- /**
420
- * Set the page orientation.
421
- * @param pageRotation see {@link PageRotation}
422
- * @param options including {@link PdfPageSelection}
423
- */
424
- public async setRotation(
425
- pageRotation: PageRotation,
426
- options?: {
427
- /**
428
- * @default "all"
429
- */
430
- pdfPageSelection?: PdfPageSelection | undefined;
431
- } | undefined
432
- ) {
433
- return z.function()
434
- .args(
435
- pageRotationSchema,
436
- z.object({pdfPageSelection: pdfPageSelectionSchema.optional()}).optional()
437
- )
438
- .returns(z.promise(z.void()))
439
- .implement(this.internal_setRotation.bind(this))
440
- (pageRotation, options);
441
- }
442
-
443
- /**
444
- * Resize a page to the specified dimensions
445
- * @param newSize {@link PdfPaperSize}
446
- * @param options including {@link PdfPageSelection}
447
- */
448
- public async resize(
449
- newSize: PdfPaperSize,
450
- options?: {
451
- /**
452
- * @default "all"
453
- */
454
- pdfPageSelection?: PdfPageSelection | undefined;
455
- } | undefined
456
- ): Promise<void> {
457
- return z.function()
458
- .args(
459
- pdfPaperSizeSchema,
460
- z.object({pdfPageSelection: pdfPageSelectionSchema.optional()}).optional()
461
- )
462
- .returns(z.promise(z.void()))
463
- .implement(this.internal_resize.bind(this))
464
- (newSize, options);
465
- }
466
-
467
- /**
468
- * Adds another PDF to the beginning of the current PdfDocument
469
- * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
470
- * @param fromPdfDocument PdfDocument to prepend
471
- */
472
- public async prependAnotherPdf(
473
- fromPdfDocument: PdfDocument
474
- ): Promise<void> {
475
- return z.function()
476
- .args(pdfDocumentSchema)
477
- .returns(z.promise(z.void()))
478
- .implement(this.internal_prependAnotherPdf.bind(this))
479
- (fromPdfDocument);
480
- }
481
-
482
- /**
483
- * Appends another PDF to the end of the current <see cref="PdfDocument"/>
484
- * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
485
- * @param fromPdfDocument PdfDocument to Append
486
- */
487
- public async appendAnotherPdf(fromPdfDocument: PdfDocument): Promise<void> {
488
- return z.function()
489
- .args(pdfDocumentSchema)
490
- .returns(z.promise(z.void()))
491
- .implement(this.internal_appendAnotherPdf.bind(this))
492
- (fromPdfDocument);
493
- }
494
-
495
- /**
496
- * Inserts another PDF into the current PdfDocument, starting at a given Page Index.
497
- * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
498
- * @param fromPdfDocument Another PdfDocument
499
- * @param insertAtPageIndex Index at which to insert the new content. Note: Page 1 has index 0...
500
- */
501
- public async insertPagesFromAnotherPdf(
502
- fromPdfDocument: PdfDocument,
503
- insertAtPageIndex: number
504
- ): Promise<void> {
505
- return z.function()
506
- .args(pdfDocumentSchema, numberSchema.describe("insertAtPageIndex: number"))
507
- .returns(z.promise(z.void()))
508
- .implement(this.internal_insertPagesFromAnotherPdf.bind(this))
509
- (fromPdfDocument, insertAtPageIndex);
510
- }
511
-
512
- /**
513
- * Removes a range of pages from the PDF
514
- * @param pages pages to remove
515
- */
516
- public async removePage(pages: PdfPageSelection): Promise<void> {
517
- return z.function()
518
- .args(pdfPageSelectionSchema)
519
- .returns(z.promise(z.void()))
520
- .implement(this.internal_removePage.bind(this))
521
- (pages);
522
- }
523
-
524
- /**
525
- * Creates a new PDF by copying a range of pages from this {@link PdfDocument}.
526
- * @param pages pages to copy (default "all")
527
- */
528
- public async duplicate(
529
- pages: PdfPageSelection = "all"
530
- ): Promise<PdfDocument> {
531
- return z.function()
532
- .args(pdfPageSelectionSchema)
533
- .returns(z.promise(pdfDocumentSchema))
534
- .implement(this.internal_duplicate.bind(this))
535
- (pages);
536
- }
537
-
538
- //#endregion
539
-
540
- //#region image
541
- /**
542
- * Finds all embedded Images from within a specified pages in the PDF and returns them as Buffer
543
- * @param options including {@link PdfPageSelection}
544
- */
545
- public async extractRawImages(options?: {
546
- /**
547
- * @default "all"
548
- */
549
- fromPages?: PdfPageSelection;
550
- } | undefined): Promise<Buffer[]> {
551
- return z.function()
552
- .args(
553
- z.object({fromPages: pdfPageSelectionSchema.optional()}).optional()
554
- )
555
- .returns(z.promise(bufferArraySchema))
556
- .implement(this.internal_extractRawImages.bind(this))
557
- (options);
558
- }
559
-
560
- /**
561
- * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
562
- * page.
563
- *
564
- * @param options including {@link PdfPageSelection} {@link ImageType}
565
- *
566
- * @return array of images as Buffer[]
567
- */
568
- public async rasterizeToImageBuffers(options?: {
569
- /**
570
- * @default "all"
571
- */
572
- fromPages?: PdfPageSelection | undefined;
573
- /**
574
- * @default {@link ImageType.PNG}
575
- */
576
- imageType?: ImageType | undefined;
577
- } | undefined): Promise<Buffer[]> {
578
- return z.function()
579
- .args(
580
- z.object({
581
- fromPages: pdfPageSelectionSchema.optional(),
582
- imageType: imageTypeSchema.optional()
583
- }).optional()
584
- )
585
- .returns(z.promise(bufferArraySchema))
586
- .implement(this.internal_rasterizeToImageBuffers.bind(this))
587
- (options);
588
- }
589
-
590
- /**
591
- * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
592
- * page. Running number will append output file path.
593
- *
594
- * @param filePath output file path.
595
- * @param options including {@link PdfPageSelection} {@link ImageType}
596
- *
597
- * @return array of images file name as string[]
598
- */
599
- public async rasterizeToImageFiles(
600
- filePath: string,
601
- options?: {
602
- /**
603
- * @default "all"
604
- */
605
- fromPages?: PdfPageSelection | undefined;
606
- /**
607
- * @default {@link ImageType.PNG}
608
- */
609
- type?: ImageType | undefined;
610
- } | undefined
611
- ): Promise<string[]> {
612
- return z.function()
613
- .args(
614
- filePathSchema,
615
- z.object({
616
- fromPages: pdfPageSelectionSchema.optional(),
617
- type: imageTypeSchema.optional()
618
- }).optional()
619
- )
620
- .returns(z.promise(stringArraySchema))
621
- .implement(this.internal_rasterizeToImageFiles.bind(this))
622
- (filePath, options);
623
- }
624
-
625
- //#endregion
626
-
627
- //#region text
628
- /**
629
- * Replace the specified old text with new text on a given page
630
- * @param oldText Old text to remove
631
- * @param newText New text to add
632
- * @param onPages Page index to search for old text to replace (default "all")
633
- */
634
- public async replaceText(
635
- oldText: string,
636
- newText: string,
637
- onPages?: PdfPageSelection | undefined
638
- ): Promise<void> {
639
- return z.function()
640
- .args(
641
- z.string({description: "oldText: string"}),
642
- z.string({description: "newText: string"}),
643
- pdfPageSelectionSchema.optional())
644
- .returns(z.promise(z.void()))
645
- .implement(this.internal_replaceText.bind(this))
646
- (oldText, newText, onPages);
647
- }
648
-
649
- public async extractText(
650
- onPages?: PdfPageSelection | undefined
651
- ): Promise<string> {
652
- return z.function()
653
- .args(pdfPageSelectionSchema.optional())
654
- .returns(z.promise(z.string()))
655
- .implement(this.internal_extractText.bind(this))
656
- (onPages);
657
- }
658
-
659
- //#endregion
660
-
661
- //#region pdfA
662
- /**
663
- * Convert the current document into the specified PDF-A standard format
664
- * @param pdfaVersion The PDF/A version to convert to (default: PdfA3b)
665
- * @param customICC (Optional) Custom color profile file path
666
- */
667
- public async convertToPdfA(pdfaVersion: PdfAVersions = PdfAVersions.PdfA3b, customICC?: string | undefined): Promise<void> {
668
- return z.function()
669
- .args(
670
- z.nativeEnum(PdfAVersions, {description: "pdfaVersion: PdfAVersions"}),
671
- z.string({description: "customICC: string"}).optional()
672
- )
673
- .returns(z.promise(z.void()))
674
- .implement(this.internal_convertToPdfA.bind(this))
675
- (pdfaVersion, customICC);
676
- }
677
-
678
- /**
679
- * Convert the current document into the specified PDF/UA standard format
680
- */
681
- public async convertToPdfUA(naturalLanguages: NaturalLanguages, pdfUaVersion: PdfUAVersions = PdfUAVersions.PdfUA1): Promise<void> {
682
- return this.internal_convertToPdfUA(naturalLanguages, pdfUaVersion)
683
- }
684
-
685
- //#endregion
686
-
687
- //#region metadata
688
- /**
689
- * Gets a Map<string, string> of metadata properties
690
- */
691
- public async getMetadata(): Promise<Map<string, string>> {
692
- return this.internal_getMetadata()
693
- }
694
-
695
- /**
696
- * Add or Update a single metadata property
697
- * @param key
698
- * @param value
699
- */
700
- public async addOrUpdateMetadata(
701
- key: string,
702
- value: string
703
- ): Promise<void> {
704
- return z.function()
705
- .args(z.string({description: "key: string"}), z.string({description: "value: string"}))
706
- .returns(z.promise(z.void()))
707
- .implement(this.internal_addOrUpdateMetadata.bind(this))
708
- (key, value);
709
- }
710
-
711
- /**
712
- * Remove a single metadata property
713
- * @param key
714
- */
715
- public async removeMetadata(key: string): Promise<void> {
716
- return z.function()
717
- .args(z.string({description: "key: string"}))
718
- .returns(z.promise(z.void()))
719
- .implement(this.internal_removeMetadata.bind(this))
720
- (key);
721
- }
722
-
723
- /**
724
- * Sets a whole metadata properties Map<string, string> (override all the metadata property)
725
- * @param newMetadataDictionary new metadata properties Map<string, string>
726
- */
727
- public async overrideMetadata(
728
- newMetadataDictionary: Map<string, string>
729
- ): Promise<void> {
730
- return z.function()
731
- .args(mapStringSchema)
732
- .returns(z.promise(z.void()))
733
- .implement(this.internal_overrideMetadata.bind(this))
734
- (newMetadataDictionary);
735
- }
736
-
737
- //#endregion
738
-
739
- //#region signing
740
- /**
741
- * Sign PDF with digital signature certificate.
742
- * Note that the PDF will not be fully signed until Saved
743
- * using {@link saveAs} or {@link saveAsBuffer}
744
- *
745
- * Multiple certificates may be used.
746
- * @param signature see {@link DigitalSignature}
747
- */
748
- public async signDigitalSignature(signature: DigitalSignature) {
749
- return z.function()
750
- .args(digitalSignatureSchema)
751
- .returns(z.promise(z.void()))
752
- .implement(this.internal_signDigitalSignature.bind(this))
753
- (signature);
754
- }
755
-
756
- /**
757
- * Check if PdfDocument was signed or not
758
- */
759
- public async isSigned(): Promise<boolean> {
760
- return this.internal_isSigned()
761
- }
762
-
763
- /**
764
- * Count the number signature that signed to this PdfDocument
765
- */
766
- public async signatureCount(): Promise<number> {
767
- return this.internal_signatureCount()
768
- }
769
-
770
- //#endregion
771
-
772
- //#region header/footer (affix)
773
- /**
774
- * Apply page header on top of an existing Pdf.
775
- * @param header {@link TextAffix}
776
- * @param toPages {@link PdfPageSelection}
777
- */
778
- public async addTextHeader(
779
- header: TextAffix,
780
- toPages?: PdfPageSelection | undefined
781
- ): Promise<void> {
782
- return z.function()
783
- .args(textAffixSchema, pdfPageSelectionSchema.optional())
784
- .returns(z.promise(z.void()))
785
- .implement(this.internal_addTextHeader.bind(this))
786
- (header, toPages);
787
- }
788
-
789
- /**
790
- * Apply page footer on top of an existing Pdf.
791
- * @param footer {@link TextAffix}
792
- * @param toPages {@link PdfPageSelection}
793
- */
794
- public async addTextFooter(
795
- footer: TextAffix,
796
- toPages?: PdfPageSelection | undefined
797
- ): Promise<void> {
798
- return z.function()
799
- .args(textAffixSchema, pdfPageSelectionSchema.optional())
800
- .returns(z.promise(z.void()))
801
- .implement(this.internal_addTextFooter.bind(this))
802
- (footer, toPages);
803
- }
804
-
805
- /**
806
- * Apply HTML header on top of an existing Pdf.
807
- * @param header {@link HtmlAffix}
808
- * @param toPages {@link PdfPageSelection}
809
- */
810
- public async addHtmlHeader(
811
- header: HtmlAffix,
812
- toPages?: PdfPageSelection | undefined
813
- ): Promise<void> {
814
- return z.function()
815
- .args(htmlAffixSchema, pdfPageSelectionSchema.optional())
816
- .returns(z.promise(z.void()))
817
- .implement(this.internal_addHtmlHeader.bind(this))
818
- (header, toPages);
819
- }
820
-
821
- /**
822
- * Apply HTML footer on top of an existing Pdf.
823
- * @param footer {@link HtmlAffix}
824
- * @param toPages {@link PdfPageSelection}
825
- */
826
- public async addHtmlFooter(
827
- footer: HtmlAffix,
828
- toPages?: PdfPageSelection | undefined
829
- ): Promise<void> {
830
- return z.function()
831
- .args(htmlAffixSchema, pdfPageSelectionSchema.optional())
832
- .returns(z.promise(z.void()))
833
- .implement(this.internal_addHtmlFooter.bind(this))
834
- (footer, toPages);
835
- }
836
-
837
- //#endregion
838
-
839
- //#region stamp
840
- /**
841
- * Edits the PDF by applying the HTML's rendered to only selected page(s).
842
- * @param htmlStringOrHtmlFilePath
843
- * @param options including {@link HtmlStampOptions} {@link PdfPageSelection}
844
- */
845
- public async stampHtml(
846
- htmlStringOrHtmlFilePath: HtmlFilePath | HtmlString,
847
- options?: {
848
- htmlStampOptions?: HtmlStampOptions | undefined;
849
- toPages?: PdfPageSelection | undefined;
850
- } | undefined
851
- ) {
852
- return z.function()
853
- .args(z.union([htmlFilePathSchema, htmlStringSchema]), z.object({
854
- htmlStampOptions: htmlStampOptionsSchema.optional(),
855
- toPages: pdfPageSelectionSchema.optional()
856
- }).optional())
857
- .returns(z.promise(z.void()))
858
- .implement(this.internal_stampHtml.bind(this))
859
- (htmlStringOrHtmlFilePath, options);
860
- }
861
-
862
- /**
863
- * Edits the PDF by applying the image to only selected page(s).
864
- * @param image image file path or image buffer
865
- * @param options including {@link ImageStampOptions} {@link PdfPageSelection}
866
- */
867
- public async stampImage(
868
- image: ImageFilePath | ImageBuffer,
869
- options?: {
870
- imageStampOptions?: ImageStampOptions | undefined;
871
- toPages?: PdfPageSelection | undefined;
872
- } | undefined
873
- ) {
874
- return z.function()
875
- .args(z.union([imageFilePathSchema, imageBufferSchema]), z.object({
876
- imageStampOptions: imageStampOptionsSchema.optional(),
877
- toPages: pdfPageSelectionSchema.optional()
878
- }).optional())
879
- .returns(z.promise(z.void()))
880
- .implement(this.internal_stampImage.bind(this))
881
- (image, options);
882
- }
883
-
884
- /**
885
- * Edits the PDF by applying the text to only selected page(s).
886
- * @param text text to stamp
887
- * @param options including {@link TextStampOptions} {@link PdfPageSelection}
888
- */
889
- public async stampText(
890
- text: string,
891
- options?: {
892
- textStampOptions?: TextStampOptions | undefined;
893
- toPages?: PdfPageSelection | undefined;
894
- } | undefined
895
- ) {
896
- return z.function()
897
- .args(stringSchema, z.object({
898
- textStampOptions: textStampOptionsSchema.optional(),
899
- toPages: pdfPageSelectionSchema.optional()
900
- }).optional())
901
- .returns(z.promise(z.void()))
902
- .implement(this.internal_stampText.bind(this))
903
- (text, options);
904
- }
905
-
906
- /**
907
- * Edits the PDF by applying the barcode to only selected page(s).
908
- * @param barcodeValue barcode
909
- * @param options including {@link BarcodeType} {@link BarcodeStampOptions} {@link PdfPageSelection}
910
- */
911
- public async stampBarcode(
912
- barcodeValue: string,
913
- options?: {
914
- barcodeEncoding: BarcodeType;
915
- barcodeStampOptions?: BarcodeStampOptions | undefined;
916
- toPages?: PdfPageSelection | undefined;
917
- } | undefined
918
- ) {
919
- return z.function()
920
- .args(stringSchema, z.object({
921
- barcodeEncoding: barcodeTypeSchema,
922
- barcodeStampOptions: barcodeStampOptionsSchema.optional(),
923
- toPages: pdfPageSelectionSchema.optional()
924
- }).optional())
925
- .returns(z.promise(z.void()))
926
- .implement(this.internal_stampBarcode.bind(this))
927
- (barcodeValue, options);
928
- }
929
-
930
- //#endregion
931
-
932
- //#region background/foreground
933
- /**
934
- * Adds a background to each page of this PDF. The background is copied from a first page in the
935
- * backgroundPdf document.
936
- *
937
- * @param fromPdf background PDF document
938
- * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
939
- * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
940
- */
941
- public async addBackgroundFromAnotherPdf(
942
- fromPdf: PdfDocument,
943
- sourcePageIndex = 0,
944
- applyToPages?: PdfPageSelection | undefined
945
- ): Promise<void> {
946
- return z.function()
947
- .args(pdfDocumentSchema, numberSchema, pdfPageSelectionSchema.optional())
948
- .returns(z.promise(z.void()))
949
- .implement(this.internal_addBackgroundFromAnotherPdf.bind(this))
950
- (fromPdf, sourcePageIndex, applyToPages);
951
- }
952
-
953
- /**
954
- * Adds a foreground to each page of this PDF. The background is copied from a first page in the
955
- * backgroundPdf document.
956
- *
957
- * @param fromPdf foreground PDF document
958
- * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
959
- * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
960
- */
961
- public async addForegroundFromAnotherPdf(
962
- fromPdf: PdfDocument,
963
- sourcePageIndex = 0,
964
- applyToPages?: PdfPageSelection | undefined
965
- ): Promise<void> {
966
- return z.function()
967
- .args(pdfDocumentSchema, numberSchema, pdfPageSelectionSchema.optional())
968
- .returns(z.promise(z.void()))
969
- .implement(this.internal_addForegroundFromAnotherPdf.bind(this))
970
- (fromPdf, sourcePageIndex, applyToPages);
971
- }
972
-
973
- //#endregion
974
-
975
- //#region security
976
- /**
977
- * Removes all user and owner password security for a PDF document. Also disables content
978
- * encryption.
979
- * If content is encrypted at 128 bit, copy and paste of content, annotations and form editing may be disabled.
980
- */
981
- public async removePasswordsAndEncryption(): Promise<void> {
982
- return this.internal_removePasswordsAndEncryption()
983
- }
984
-
985
- /**
986
- * Sets the user password and enables 128Bit encryption of PDF content.
987
- * A user password is a password that each user must enter to open or print the PDF document.
988
- */
989
- public async setUserPassword(userPassword: string): Promise<void> {
990
- return z.function()
991
- .args(z.string({description: "userPassword: string"}))
992
- .returns(z.promise(z.void()))
993
- .implement(this.internal_setUserPassword.bind(this))
994
- (userPassword);
995
- }
996
-
997
- /**
998
- * Sets the owner password and enables 128Bit encryption of PDF content. An owner password is one used to
999
- * enable and disable all other security settings. <para>OwnerPassword must be set to a non-empty string
1000
- * value for {@link PdfPermission.AllowAccessibilityExtractContent} , {@link PdfPermission.AllowAnnotations} ,
1001
- * {@link PdfPermission.AllowFillForms}, {@link PdfPermission.AllowPrint}, {@link PdfPermission.AllowModify} to be
1002
- * restricted.
1003
- */
1004
- public async setOwnerPassword(ownerPassword: string): Promise<void> {
1005
- return z.function()
1006
- .args(z.string({description: "ownerPassword: string"}))
1007
- .returns(z.promise(z.void()))
1008
- .implement(this.internal_setOwnerPassword.bind(this))
1009
- (ownerPassword);
1010
- }
1011
-
1012
- /**
1013
- * Sets the permissions of this PdfDocument
1014
- * @param permissions see {@link PdfPermission}
1015
- */
1016
- public async setPermission(permissions: PdfPermission): Promise<void> {
1017
- return z.function()
1018
- .args(pdfPermissionSchema)
1019
- .returns(z.promise(z.void()))
1020
- .implement(this.internal_setPermission.bind(this))
1021
- (permissions);
1022
- }
1023
-
1024
- /**
1025
- * Gets the current permissions of this PdfDocument
1026
- * @return {@link PdfPermission}
1027
- */
1028
- public async getPermission(): Promise<PdfPermission> {
1029
- return this.internal_getPermission()
1030
- }
1031
-
1032
- /**
1033
- * Makes this PDF document read only such that: Content is encrypted at 128 bit. Copy and paste of
1034
- * content is disallowed. Annotations and form editing are disabled.
1035
- * @param ownerPassword The owner password for the PDF. A string for owner password is required to enable PDF encryption and
1036
- * all document security options.
1037
- */
1038
- public async makePdfDocumentReadOnly(ownerPassword: string): Promise<void> {
1039
- return z.function()
1040
- .args(z.string({description: "ownerPassword: string"}))
1041
- .returns(z.promise(z.void()))
1042
- .implement(this.internal_makePdfDocumentReadOnly.bind(this))
1043
- (ownerPassword);
1044
- }
1045
-
1046
- //#endregion
1047
-
1048
- //#region close
1049
- /**
1050
- * Dispose this PdfDocument object (clean up the resource)
1051
- * This is necessary to free the memory used by PdfDocument. See {@link cleanUp}
1052
- * Once this method was called this PdfDocument object no longer usable.
1053
- */
1054
- public async close() {
1055
- return this.internal_close()
1056
- }
1057
-
1058
- //#endregion
1059
-
1060
- //#region ALL_INTERNAL_STUFF
1061
- /**
1062
- * Internal PDF document ID
1063
- * @private
1064
- */
1065
- private pdfDocumentId?: string | undefined;
1066
- /**
1067
- * @private
1068
- */
1069
- private readonly promiseDocumentId?: Promise<string> | undefined;
1070
- /**
1071
- * @private
1072
- */
1073
- private pdfPassword?: PdfPassword | undefined;
1074
-
1075
- /**
1076
- * Create a PdfDocument object from a {@link PdfInput}
1077
- * For more specific way to create/open PdfDocument see {@link fromUrl} {@link fromZip} {@link fromHtml} {@link fromImage} {@link open}
1078
- *
1079
- * @param pdfInput see {@link PdfInput} (required) (pdfInput is {@link PdfFilePath} or {@link Buffer})
1080
- * @param password a password to open the PDF required if PDF file was private.
1081
- * @param trackChanges Optionally track changes to the document (for use with incremental saves)
1082
- */
1083
- constructor(pdfInput?: PdfInput | undefined, password?: PdfPassword | undefined, trackChanges?: ChangeTrackingModes | undefined) {
1084
- if (pdfInput) {
1085
- this.pdfDocumentId = undefined;
1086
- const input = separatePdfInput(pdfInput);
1087
- switch (input.type) {
1088
- case "htmlFile":
1089
- this.promiseDocumentId = renderHtmlFileToPdf(input.htmlFile);
1090
- break;
1091
- case "htmlString":
1092
- this.promiseDocumentId = renderHtmlToPdf(input.htmlString);
1093
- break;
1094
- case "zipFile":
1095
- this.promiseDocumentId = renderHtmlZipToPdf(input.zipFile);
1096
- break;
1097
- case "buffer":
1098
- this.promiseDocumentId = openPdfFileBuffer(
1099
- input.buffer,
1100
- {userPassword: password?.userPassword, ownerPassword: password?.ownerPassword, trackChanges: trackChanges}
1101
- );
1102
- break;
1103
- case "pdfFile":
1104
- this.pdfPassword = password;
1105
- this.promiseDocumentId = openPdfFileBuffer(
1106
- fs.readFileSync(input.pdfFile),
1107
- {userPassword: password?.userPassword, ownerPassword: password?.ownerPassword, trackChanges: trackChanges}
1108
- );
1109
- break;
1110
- case "url":
1111
- this.promiseDocumentId = renderUrlToPdf(input.url);
1112
- break;
1113
- case "pdfDocument":
1114
- this.pdfDocumentId = input.pdfDocument.pdfDocumentId;
1115
- this.promiseDocumentId =
1116
- input.pdfDocument.promiseDocumentId;
1117
- break;
1118
- }
1119
- if (this.pdfDocumentId) {
1120
- Access.usedDocumentIds.add(this.pdfDocumentId);
1121
- }
1122
- this.promiseDocumentId?.then((id) =>
1123
- Access.usedDocumentIds.add(id)
1124
- );
1125
- }
1126
- }
1127
-
1128
- /**
1129
- * Dispose this PdfDocument object (clean up the resource)
1130
- * This is necessary to free the memory used by PdfDocument. See {@link cleanUp}
1131
- * Once this method was called this PdfDocument object no longer usable.
1132
- */
1133
- private async internal_close() {
1134
- await disposePdf(await this.internal_getId());
1135
- }
1136
-
1137
- /**
1138
- * @private
1139
- */
1140
- private async internal_getId(): Promise<string> {
1141
- if (this.pdfDocumentId) {
1142
- return Promise.resolve(this.pdfDocumentId) ;
1143
- } else if (this.promiseDocumentId) {
1144
- this.pdfDocumentId = await this.promiseDocumentId;
1145
- return Promise.resolve(this.pdfDocumentId);
1146
- } else {
1147
- throw new Error("Cannot Get PdfDocumentId");
1148
- }
1149
- }
1150
-
1151
- //#region io
1152
-
1153
- /**
1154
- * Open or Create a PdfDocument from a {@link PdfInput}
1155
- * @param pdfInput {@link PdfInput}
1156
- * @param options including {@link PdfPassword} {@link ChromePdfRenderOptions} {@link HttpLoginCredentials} mainHtmlFile
1157
- */
1158
- private static async internal_open(
1159
- pdfInput: PdfInput,
1160
- options?: {
1161
- /**
1162
- * required for open a private PDF file
1163
- * @default undefined
1164
- */
1165
- password?: PdfPassword | undefined;
1166
- /**
1167
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1168
- * @default undefined
1169
- */
1170
- renderOptions?: ChromePdfRenderOptions | undefined;
1171
- /**
1172
- * Apply httpLoginCredentials if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1173
- * @default undefined
1174
- */
1175
- httpLoginCredentials?: HttpLoginCredentials | undefined;
1176
- /**
1177
- * Apply mainHtmlFile if PdfInput is {@link ZipFilePath}
1178
- * @default index.html
1179
- */
1180
- mainHtmlFile?: string | undefined;
1181
- /**
1182
- * Optionally track changes to the document (for use with incremental saves)
1183
- * @default {@link ChangeTrackingModes.AutoChangeTracking}
1184
- */
1185
- trackChanges?: ChangeTrackingModes | undefined;
1186
- // /**
1187
- // * Apply baseUrl if
1188
- // * The HTML base URL for which references to external CSS, Javascript and Image files will be relative.
1189
- // * @default undefined
1190
- // */
1191
- // baseUrl ?: string | undefined; //not supported
1192
- } | undefined
1193
- ): Promise<PdfDocument> {
1194
- if (pdfInput) {
1195
- const input = separatePdfInput(pdfInput);
1196
- switch (input.type) {
1197
- case "htmlFile":
1198
- const newHtmlFilePdf = new PdfDocument();
1199
- newHtmlFilePdf.pdfDocumentId = await renderHtmlFileToPdf(
1200
- input.htmlFile,
1201
- options?.renderOptions
1202
- );
1203
- return newHtmlFilePdf;
1204
- case "htmlString":
1205
- const newHtmlStringPdf = new PdfDocument();
1206
- newHtmlStringPdf.pdfDocumentId = await renderHtmlToPdf(
1207
- input.htmlString,
1208
- options?.renderOptions
1209
- );
1210
- return newHtmlStringPdf;
1211
- case "zipFile":
1212
- const newZipFilePdf = new PdfDocument();
1213
- newZipFilePdf.pdfDocumentId = await renderHtmlZipToPdf(
1214
- input.zipFile,
1215
- options?.mainHtmlFile,
1216
- options?.renderOptions
1217
- );
1218
- return newZipFilePdf;
1219
- case "buffer":
1220
- const newBufferPdf = new PdfDocument(
1221
- undefined,
1222
- options?.password,
1223
- options?.trackChanges
1224
- );
1225
- newBufferPdf.pdfDocumentId = await openPdfFileBuffer(
1226
- input.buffer,{
1227
- userPassword: options?.password?.userPassword,
1228
- ownerPassword: options?.password?.ownerPassword,
1229
- trackChanges: options?.trackChanges
1230
- }
1231
- );
1232
- return newBufferPdf;
1233
- case "pdfFile":
1234
- const newPdfFilePdf = new PdfDocument(
1235
- undefined,
1236
- options?.password
1237
- );
1238
- newPdfFilePdf.pdfDocumentId = await openPdfFileBuffer(
1239
- fs.readFileSync(input.pdfFile),
1240
- {
1241
- userPassword: options?.password?.userPassword,
1242
- ownerPassword: options?.password?.ownerPassword,
1243
- trackChanges: options?.trackChanges
1244
- }
1245
- );
1246
-
1247
- return newPdfFilePdf;
1248
- case "url":
1249
- const newUrlPdf = new PdfDocument();
1250
- newUrlPdf.pdfDocumentId = await renderUrlToPdf(input.url, {
1251
- renderOptions: options?.renderOptions,
1252
- httpLoginCredentials: options?.httpLoginCredentials,
1253
- });
1254
- return newUrlPdf;
1255
- case "pdfDocument":
1256
- return Promise.resolve(input.pdfDocument);
1257
- }
1258
- }
1259
- throw new Error(`cannot create PdfDocument object from ${pdfInput}`);
1260
- }
1261
-
1262
- /**
1263
- * Open a PdfDocument from .pdf file
1264
- * @param pdfFilePath A path to .pdf file
1265
- * @param Optionally track changes to the document (for use with incremental saves)
1266
- */
1267
- private static async internal_fromFile(
1268
- pdfFilePath: string,
1269
- trackChanges?: ChangeTrackingModes | undefined
1270
- ): Promise<PdfDocument> {
1271
- return this.internal_open(pdfFilePath, {trackChanges: trackChanges});
1272
- }
1273
-
1274
- /**
1275
- * Create a PdfDocument from an Url
1276
- * @param url A website Url
1277
- * @param options including {@link ChromePdfRenderOptions}
1278
- */
1279
- private static async internal_fromUrl(
1280
- url: URL | string,
1281
- options?: {
1282
- /**
1283
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1284
- * @default undefined
1285
- */
1286
- renderOptions?: ChromePdfRenderOptions | undefined;
1287
- } | undefined
1288
- ): Promise<PdfDocument> {
1289
- return this.internal_open(url, options);
1290
- }
1291
-
1292
- /**
1293
- * Creates a PDF file from a local Zip file, and returns it as a {@link PdfDocument}.
1294
- * IronPDF is a W3C standards compliant HTML rendering based on Google's Chromium browser.
1295
- * If your output PDF does not look as expected:
1296
- *
1297
- * - Validate your HTML file using https://validator.w3.org/ &amp; CSS https://jigsaw.w3.org/css-validator/
1298
- *
1299
- * - To debug HTML, view the file in Chrome web browser's print preview which will work almost exactly as IronPDF.
1300
- *
1301
- * - Read our detailed documentation on pixel perfect HTML to PDF: https://ironpdf.com/tutorials/pixel-perfect-html-to-pdf/
1302
- *
1303
- * @param zipFilePath Path to a Zip to be rendered as a PDF.
1304
- * @param options including {@link ChromePdfRenderOptions} and `mainHtmlFile` a main .html file default: `index.html`
1305
- */
1306
- private static async internal_fromZip(
1307
- zipFilePath: string,
1308
- options?: {
1309
- /**
1310
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1311
- * @default undefined
1312
- */
1313
- renderOptions?: ChromePdfRenderOptions | undefined;
1314
- /**
1315
- * a main .html file default: `index.html`
1316
- */
1317
- mainHtmlFile?: string | undefined;
1318
- } | undefined
1319
- ): Promise<PdfDocument> {
1320
- return this.internal_open(zipFilePath, options);
1321
- }
1322
-
1323
- /**
1324
- * Creates a PDF file from a Html string, and returns it as an {@link PdfDocument} object which can be edited and saved to disk or served on a website.
1325
- * @param htmlStringOrHtmlFilePath The Html to be rendered as a PDF.
1326
- * @param options including {@link ChromePdfRenderOptions}
1327
- */
1328
- private static async internal_fromHtml(
1329
- htmlStringOrHtmlFilePath: string,
1330
- options?: {
1331
- /**
1332
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1333
- * @default undefined
1334
- */
1335
- renderOptions?: ChromePdfRenderOptions | undefined;
1336
- } | undefined
1337
- ): Promise<PdfDocument> {
1338
- return this.internal_open(htmlStringOrHtmlFilePath, options);
1339
- }
1340
-
1341
- /**
1342
- * Converts multiple image files to a PDF document. Each image creates 1 page which matches the image
1343
- * dimensions. The default PaperSize is A4. You can set it via ImageToPdfConverter.PaperSize.
1344
- * Note: Imaging.ImageBehavior.CropPage will set PaperSize equal to ImageSize.
1345
- * @param images The image file path name(s) or {@link ImageBuffer} object(s)
1346
- * @param options including {@link ImageToPdfOptions}
1347
- */
1348
- private static async internal_fromImage(
1349
- images: ImageFilePath | ImageFilePath[] | ImageBuffer | ImageBuffer[],
1350
- options?: {
1351
- /**
1352
- * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1353
- * @default undefined
1354
- */
1355
- imageToPdfOptions?: ImageToPdfOptions | undefined;
1356
- } | undefined
1357
- ): Promise<PdfDocument> {
1358
- let temp: Promise<string>;
1359
-
1360
- if (Array.isArray(images)) {
1361
- // const imageArray = images as Array<any>;
1362
- if(images[0]){
1363
- const t = separateImageBufferOrImagePathInput(images[0]);
1364
-
1365
- switch (t.type) {
1366
- case "imageBuffer":
1367
- temp = renderImagesBufferToPdf(
1368
- images as Buffer[],
1369
- options?.imageToPdfOptions
1370
- );
1371
- break;
1372
- case "imageFilePath":
1373
- temp = renderImagesFilesToPdf(
1374
- images as string[],
1375
- options?.imageToPdfOptions
1376
- );
1377
- break;
1378
- }
1379
- }else{
1380
- throw new Error("imageToPdf input Array is Empty");
1381
- }
1382
- } else {
1383
- const image = separateImageBufferOrImagePathInput(images);
1384
- switch (image.type) {
1385
- case "imageBuffer":
1386
- temp = renderImagesBufferToPdf(
1387
- [image.imageBuffer],
1388
- options?.imageToPdfOptions
1389
- );
1390
- break;
1391
- case "imageFilePath":
1392
- temp = renderImagesFilesToPdf(
1393
- [image.imageFilePath],
1394
- options?.imageToPdfOptions
1395
- );
1396
- break;
1397
- }
1398
- }
1399
-
1400
- if (!temp) {
1401
- throw new Error(`cannot read image: ${images}`);
1402
- }
1403
-
1404
- const newUrlPdf = new PdfDocument();
1405
- newUrlPdf.pdfDocumentId = await temp;
1406
- return newUrlPdf;
1407
- }
1408
-
1409
- /**
1410
- * Static method that joins (concatenates) multiple PDF documents together into one compiled PDF document.
1411
- * If the PDF contains form fields the form field in the resulting PDF's name will be appended with '_{index}' e.g. 'Name' will be 'Name_0'
1412
- * @param pdfs array of PDF
1413
- */
1414
- private static async internal_mergePdf(pdfs: PdfInput[]): Promise<PdfDocument> {
1415
- const ids = await Promise.all(
1416
- pdfs.map(async (x) => (await PdfDocument.open(x)).internal_getId())
1417
- );
1418
- const newDocId = mergePdfs(ids);
1419
- const newUrlPdf = new PdfDocument();
1420
- newUrlPdf.pdfDocumentId = await newDocId;
1421
- return newUrlPdf;
1422
- }
1423
-
1424
- /**
1425
- * Saves the PdfDocument to a file.
1426
- * @param filePath Target file path
1427
- * @param saveOptions see {@link SaveOptions}
1428
- */
1429
- private async internal_saveAs(filePath: string, saveOptions?: SaveOptions | undefined): Promise<void> {
1430
- return this.internal_saveAsBuffer(saveOptions).then((pdfFileBuffer) => {
1431
- fs.writeFile(filePath, pdfFileBuffer, "binary", (err) => {
1432
- if (err) throw err;
1433
- });
1434
- });
1435
- }
1436
-
1437
- /**
1438
- * Saves the PdfDocument to a binary (Buffer)
1439
- * @param saveOptions see {@link SaveOptions}
1440
- */
1441
- private async internal_saveAsBuffer(saveOptions?: SaveOptions | undefined): Promise<Buffer> {
1442
- return getBinaryData(await this.internal_getId(), saveOptions);
1443
- }
1444
-
1445
- //#endregion
1446
-
1447
- //#region compress
1448
- /**
1449
- * Compress existing PDF images using JPG encoding and the specified settings
1450
- * @param imageQuality Quality (1 - 100) to use during compression
1451
- * @param scaleToVisibleSize Scale down the image resolution according to its visible size in the PDF document
1452
- */
1453
- private async internal_compressSize(
1454
- imageQuality: number,
1455
- scaleToVisibleSize = false
1456
- ): Promise<void> {
1457
- if (imageQuality < 1 || imageQuality > 100)
1458
- throw new Error(
1459
- `Invalid quality specifier (${imageQuality}) when compressing images. Quality must be between 1 and 100.`
1460
- );
1461
- return await compressImage(
1462
- await this.internal_getId(),
1463
- imageQuality,
1464
- scaleToVisibleSize
1465
- );
1466
- }
1467
-
1468
- /**
1469
- * Remove document struct tree information which describes the logical layout of the document.
1470
- * Removing the "structure tree" can significantly reduce the disk space used by the document.
1471
- * Removing the "structure tree" of a complicated document can negatively impact text selection.
1472
- */
1473
- private async internal_compressStructTree(): Promise<void> {
1474
- return await compressStructTree(await this.internal_getId());
1475
- }
1476
-
1477
- //#endregion
1478
-
1479
- //#region page
1480
- /**
1481
- * Gets information of all pages in the PdfDocument
1482
- */
1483
- private async internal_getPagesInfo(): Promise<PageInfo[]> {
1484
- return await getPageInfo(await this.internal_getId());
1485
- }
1486
-
1487
- /**
1488
- * Gets the number of pages in the PdfDocument.
1489
- */
1490
- private async internal_getPageCount(): Promise<number> {
1491
- return (await this.internal_getPagesInfo()).length;
1492
- }
1493
-
1494
- /**
1495
- * Set the page orientation.
1496
- * @param pageRotation see {@link PageRotation}
1497
- * @param options including {@link PdfPageSelection}
1498
- */
1499
- private async internal_setRotation(
1500
- pageRotation: PageRotation,
1501
- options?: {
1502
- /**
1503
- * @default "all"
1504
- */
1505
- pdfPageSelection?: PdfPageSelection | undefined;
1506
- } | undefined
1507
- ) {
1508
- return await setPageRotation(await this.internal_getId(), pageRotation, options);
1509
- }
1510
-
1511
- /**
1512
- * Resize a page to the specified dimensions
1513
- * @param newSize {@link PdfPaperSize}
1514
- * @param options including {@link PdfPageSelection}
1515
- */
1516
- private async internal_resize(
1517
- newSize: PdfPaperSize,
1518
- options?: {
1519
- /**
1520
- * @default "all"
1521
- */
1522
- pdfPageSelection?: PdfPageSelection | undefined;
1523
- } | undefined
1524
- ): Promise<void> {
1525
- return await resizePage(await this.internal_getId(), newSize, options);
1526
- }
1527
-
1528
- /**
1529
- * Adds another PDF to the beginning of the current PdfDocument
1530
- * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
1531
- * @param fromPdfDocument PdfDocument to prepend
1532
- */
1533
- private async internal_prependAnotherPdf(
1534
- fromPdfDocument: PdfDocument
1535
- ): Promise<void> {
1536
- await this.internal_insertPagesFromAnotherPdf(fromPdfDocument, 0);
1537
- }
1538
-
1539
- /**
1540
- * Appends another PDF to the end of the current <see cref="PdfDocument"/>
1541
- * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
1542
- * @param fromPdfDocument PdfDocument to Append
1543
- */
1544
- private async internal_appendAnotherPdf(fromPdfDocument: PdfDocument): Promise<void> {
1545
- await this.internal_insertPagesFromAnotherPdf(
1546
- fromPdfDocument,
1547
- (await this.internal_getPageCount())
1548
- );
1549
- }
1550
-
1551
- /**
1552
- * Inserts another PDF into the current PdfDocument, starting at a given Page Index.
1553
- * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
1554
- * @param fromPdfDocument Another PdfDocument
1555
- * @param insertAtPageIndex Index at which to insert the new content. Note: Page 1 has index 0...
1556
- */
1557
- private async internal_insertPagesFromAnotherPdf(
1558
- fromPdfDocument: PdfDocument,
1559
- insertAtPageIndex: number
1560
- ): Promise<void> {
1561
- await insertPdf(
1562
- await this.internal_getId(),
1563
- await fromPdfDocument.internal_getId(),
1564
- insertAtPageIndex
1565
- );
1566
- }
1567
-
1568
- /**
1569
- * Removes a range of pages from the PDF
1570
- * @param pages pages to remove
1571
- */
1572
- private async internal_removePage(pages: PdfPageSelection): Promise<void> {
1573
- await removePage(await this.internal_getId(), {PdfPageSelection: pages});
1574
- }
1575
-
1576
- /**
1577
- * Creates a new PDF by copying a range of pages from this {@link PdfDocument}.
1578
- * @param pages pages to copy (default "all")
1579
- */
1580
- private async internal_duplicate(
1581
- pages: PdfPageSelection = "all"
1582
- ): Promise<PdfDocument> {
1583
- const newPdf = new PdfDocument();
1584
- newPdf.pdfDocumentId = await duplicate(await this.internal_getId(), {
1585
- PdfPageSelection: pages,
1586
- });
1587
- return newPdf;
1588
- }
1589
-
1590
- //#endregion
1591
-
1592
- //#region image
1593
- /**
1594
- * Finds all embedded Images from within a specified pages in the PDF and returns them as Buffer
1595
- * @param options including {@link PdfPageSelection}
1596
- */
1597
- private async internal_extractRawImages(options?: {
1598
- /**
1599
- * @default "all"
1600
- */
1601
- fromPages?: PdfPageSelection | undefined;
1602
- } | undefined): Promise<Buffer[]> {
1603
- return extractRawImages(
1604
- await this.internal_getId(),
1605
- options?.fromPages ?? "all"
1606
- );
1607
- }
1608
-
1609
- /**
1610
- * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
1611
- * page.
1612
- *
1613
- * @param options including {@link PdfPageSelection} {@link ImageType}
1614
- *
1615
- * @return array of images as Buffer[]
1616
- */
1617
- private async internal_rasterizeToImageBuffers(options?: {
1618
- /**
1619
- * @default "all"
1620
- */
1621
- fromPages?: PdfPageSelection | undefined;
1622
- /**
1623
- * @default {@link ImageType.PNG}
1624
- */
1625
- imageType?: ImageType | undefined;
1626
- }): Promise<Buffer[]> {
1627
- const images = await rasterizeToImageBuffers(
1628
- await this.internal_getId(),
1629
- options?.fromPages ?? "all"
1630
- );
1631
- const jimpImageType: "image/bmp" | "image/png" | "image/jpeg" = (() => {
1632
- switch (options?.imageType) {
1633
- case ImageType.BMP:
1634
- return Jimp.MIME_BMP;
1635
- case ImageType.PNG:
1636
- return Jimp.MIME_PNG;
1637
- case ImageType.JPG:
1638
- return Jimp.MIME_JPEG;
1639
- default:
1640
- return Jimp.MIME_PNG;
1641
- }
1642
- })();
1643
- return Promise.all(
1644
- images.map(async (imageBuffer) => {
1645
- //convert output type
1646
- const jimp = await Jimp.read(imageBuffer);
1647
- return await jimp.getBufferAsync(jimpImageType);
1648
- })
1649
- );
1650
- }
1651
-
1652
- /**
1653
- * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
1654
- * page. Running number will append output file path.
1655
- *
1656
- * @param filePath output file path.
1657
- * @param options including {@link PdfPageSelection} {@link ImageType}
1658
- *
1659
- * @return array of images file name as string[]
1660
- */
1661
- private async internal_rasterizeToImageFiles(
1662
- filePath: string,
1663
- options?: {
1664
- /**
1665
- * @default "all"
1666
- */
1667
- fromPages?: PdfPageSelection | undefined;
1668
- /**
1669
- * @default {@link ImageType.PNG}
1670
- */
1671
- type?: ImageType | undefined;
1672
- } | undefined
1673
- ): Promise<string[]> {
1674
- const images = await rasterizeToImageBuffers(
1675
- await this.internal_getId(),
1676
- options?.fromPages ?? "all"
1677
- );
1678
-
1679
- const promises = images.map(async (imageBuffer, index) => {
1680
- const outputFileName = getFileName(filePath,index.toString(),getImageExtType(options?.type),"image");
1681
- await Jimp.read(imageBuffer).then((value) => {
1682
- return value.write(outputFileName);
1683
- });
1684
- return outputFileName;
1685
- });
1686
-
1687
- return await Promise.all(promises);
1688
- }
1689
-
1690
- //#endregion
1691
-
1692
- //#region text
1693
- /**
1694
- * Replace the specified old text with new text on a given page
1695
- * @param oldText Old text to remove
1696
- * @param newText New text to add
1697
- * @param onPages Page index to search for old text to replace (default "all")
1698
- */
1699
- private async internal_replaceText(
1700
- oldText: string,
1701
- newText: string,
1702
- onPages?: PdfPageSelection | undefined
1703
- ): Promise<void> {
1704
- return replaceText(await this.internal_getId(), oldText, newText, onPages);
1705
- }
1706
-
1707
- private async internal_extractText(
1708
- onPages?: PdfPageSelection | undefined
1709
- ): Promise<string> {
1710
- return extractAllText(await this.internal_getId(), onPages);
1711
- }
1712
-
1713
- //#endregion
1714
-
1715
- //#region pdfA
1716
- /**
1717
- * Convert the current document into the specified PDF-A standard format
1718
- * @param pdfaVersion The PDF/A version to convert to
1719
- * @param customICC (Optional) Custom color profile file path
1720
- */
1721
- private async internal_convertToPdfA(pdfaVersion: PdfAVersions, customICC?: string | undefined): Promise<void> {
1722
- return await toPdfA(await this.internal_getId(), pdfaVersion, customICC);
1723
- }
1724
-
1725
- /**
1726
- * Convert the current document into the specified PDF/UA standard format
1727
- */
1728
- private async internal_convertToPdfUA(naturalLanguages: NaturalLanguages, pdfUaVersion: PdfUAVersions = PdfUAVersions.PdfUA1): Promise<void> {
1729
- return await toPdfUA(await this.internal_getId(), naturalLanguages, pdfUaVersion);
1730
- }
1731
-
1732
- //#endregion
1733
-
1734
- //#region metadata
1735
- /**
1736
- * Gets a Map<string, string> of metadata properties
1737
- */
1738
- private async internal_getMetadata(): Promise<Map<string, string>> {
1739
- return getMetadataDict(await this.internal_getId());
1740
- }
1741
-
1742
- /**
1743
- * Add or Update a single metadata property
1744
- * @param key
1745
- * @param value
1746
- */
1747
- private async internal_addOrUpdateMetadata(
1748
- key: string,
1749
- value: string
1750
- ): Promise<void> {
1751
- return setMetadata(await this.internal_getId(), key, value);
1752
- }
1753
-
1754
- /**
1755
- * Remove a single metadata property
1756
- * @param key
1757
- */
1758
- private async internal_removeMetadata(key: string): Promise<void> {
1759
- return removeMetadata(await this.internal_getId(), key);
1760
- }
1761
-
1762
-
1763
- /**
1764
- * Sets a whole metadata properties Map<string, string> (override all the metadata property)
1765
- * @param newMetadataDictionary new metadata properties Map<string, string>
1766
- */
1767
- private async internal_overrideMetadata(
1768
- newMetadataDictionary: Map<string, string>
1769
- ): Promise<void> {
1770
- return setMetadataDict(await this.internal_getId(), newMetadataDictionary);
1771
- }
1772
-
1773
- //#endregion
1774
-
1775
- //#region signing
1776
- /**
1777
- * Sign PDF with digital signature certificate.
1778
- * Note that the PDF will not be fully signed until Saved
1779
- * using {@link saveAs} or {@link saveAsBuffer}
1780
- *
1781
- * Multiple certificates may be used.
1782
- * @param signature see {@link DigitalSignature}
1783
- */
1784
- private async internal_signDigitalSignature(signature: DigitalSignature) {
1785
- return await signPdf(await this.internal_getId(), signature);
1786
- }
1787
-
1788
- /**
1789
- * Check if PdfDocument was signed or not
1790
- */
1791
- private async internal_isSigned(): Promise<boolean> {
1792
- const signatureCount = await getSignatureCount(await this.internal_getId());
1793
- return signatureCount > 0;
1794
- }
1795
-
1796
- /**
1797
- * Count the number signature that signed to this PdfDocument
1798
- */
1799
- private async internal_signatureCount(): Promise<number> {
1800
- return await getSignatureCount(await this.internal_getId());
1801
- }
1802
-
1803
- //#endregion
1804
-
1805
- //#region header/footer (affix)
1806
- /**
1807
- * Apply page header on top of an existing Pdf.
1808
- * @param header {@link TextAffix}
1809
- * @param toPages {@link PdfPageSelection}
1810
- */
1811
- private async internal_addTextHeader(
1812
- header: TextAffix,
1813
- toPages?: PdfPageSelection | undefined
1814
- ): Promise<void> {
1815
- await addTextAffix(await this.internal_getId(), toPages, header, true);
1816
- }
1817
-
1818
- /**
1819
- * Apply page footer on top of an existing Pdf.
1820
- * @param footer {@link TextAffix}
1821
- * @param toPages {@link PdfPageSelection}
1822
- */
1823
- private async internal_addTextFooter(
1824
- footer: TextAffix,
1825
- toPages?: PdfPageSelection | undefined
1826
- ): Promise<void> {
1827
- await addTextAffix(await this.internal_getId(), toPages, footer, false);
1828
- }
1829
-
1830
- /**
1831
- * Apply HTML header on top of an existing Pdf.
1832
- * @param header {@link HtmlAffix}
1833
- * @param toPages {@link PdfPageSelection}
1834
- */
1835
- private async internal_addHtmlHeader(
1836
- header: HtmlAffix,
1837
- toPages?: PdfPageSelection | undefined
1838
- ): Promise<void> {
1839
- await addHtmlAffix(await this.internal_getId(), toPages, header, true);
1840
- }
1841
-
1842
- /**
1843
- * Apply HTML footer on top of an existing Pdf.
1844
- * @param footer {@link HtmlAffix}
1845
- * @param toPages {@link PdfPageSelection}
1846
- */
1847
- private async internal_addHtmlFooter(
1848
- footer: HtmlAffix,
1849
- toPages?: PdfPageSelection | undefined
1850
- ): Promise<void> {
1851
- await addHtmlAffix(await this.internal_getId(), toPages, footer, false);
1852
- }
1853
-
1854
- //#endregion
1855
-
1856
- //#region stamp
1857
- /**
1858
- * Edits the PDF by applying the HTML's rendered to only selected page(s).
1859
- * @param htmlStringOrHtmlFilePath
1860
- * @param options including {@link HtmlStampOptions} {@link PdfPageSelection}
1861
- */
1862
- private async internal_stampHtml(
1863
- htmlStringOrHtmlFilePath: HtmlFilePath | HtmlString,
1864
- options?: {
1865
- htmlStampOptions?: HtmlStampOptions | undefined;
1866
- toPages?: PdfPageSelection | undefined;
1867
- } | undefined
1868
- ) {
1869
- const html =
1870
- htmlStringOrHtmlFilePath.endsWith(".html") ||
1871
- htmlStringOrHtmlFilePath.endsWith(".htm")
1872
- ? fs.readFileSync(htmlStringOrHtmlFilePath).toString()
1873
- : htmlStringOrHtmlFilePath;
1874
-
1875
- await stampHtml(await this.internal_getId(), html, {
1876
- password: this.pdfPassword,
1877
- htmlStampOptions: options?.htmlStampOptions,
1878
- pageSelection: options?.toPages,
1879
- });
1880
- }
1881
-
1882
- /**
1883
- * Edits the PDF by applying the image to only selected page(s).
1884
- * @param image image file path or image buffer
1885
- * @param options including {@link ImageStampOptions} {@link PdfPageSelection}
1886
- */
1887
- private async internal_stampImage(
1888
- image: ImageFilePath | ImageBuffer,
1889
- options?: {
1890
- imageStampOptions?: ImageStampOptions | undefined;
1891
- toPages?: PdfPageSelection | undefined;
1892
- } | undefined
1893
- ) {
1894
- const imageBuffer =
1895
- image instanceof Buffer ? image : fs.readFileSync(image);
1896
-
1897
- await stampImage(await this.internal_getId(), imageBuffer, {
1898
- password: this.pdfPassword,
1899
- imageStampOptions: options?.imageStampOptions,
1900
- pageSelection: options?.toPages,
1901
- });
1902
- }
1903
-
1904
- /**
1905
- * Edits the PDF by applying the text to only selected page(s).
1906
- * @param text text to stamp
1907
- * @param options including {@link TextStampOptions} {@link PdfPageSelection}
1908
- */
1909
- private async internal_stampText(
1910
- text: string,
1911
- options?: {
1912
- textStampOptions?: TextStampOptions | undefined;
1913
- toPages?: PdfPageSelection | undefined;
1914
- } | undefined
1915
- ) {
1916
- await stampText(await this.internal_getId(), text, {
1917
- password: this.pdfPassword,
1918
- textStampOptions: options?.textStampOptions,
1919
- pageSelection: options?.toPages,
1920
- });
1921
- }
1922
-
1923
- /**
1924
- * Edits the PDF by applying the barcode to only selected page(s).
1925
- * @param barcodeValue barcode
1926
- * @param options including {@link BarcodeType} {@link BarcodeStampOptions} {@link PdfPageSelection}
1927
- */
1928
- private async internal_stampBarcode(
1929
- barcodeValue: string,
1930
- options?: {
1931
- barcodeEncoding: BarcodeType;
1932
- barcodeStampOptions?: BarcodeStampOptions | undefined;
1933
- toPages?: PdfPageSelection | undefined;
1934
- } | undefined
1935
- ) {
1936
- await stampBarcode(
1937
- await this.internal_getId(),
1938
- barcodeValue,
1939
- {
1940
- password: this.pdfPassword,
1941
- barcodeStampOptions: options?.barcodeStampOptions,
1942
- pageSelection: options?.toPages,
1943
- }
1944
- );
1945
- }
1946
-
1947
- //#endregion
1948
-
1949
- //#region background/foreground
1950
- /**
1951
- * Adds a background to each page of this PDF. The background is copied from a first page in the
1952
- * backgroundPdf document.
1953
- *
1954
- * @param fromPdf background PDF document
1955
- * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
1956
- * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
1957
- */
1958
- private async internal_addBackgroundFromAnotherPdf(
1959
- fromPdf: PdfDocument,
1960
- sourcePageIndex = 0,
1961
- applyToPages?: PdfPageSelection | undefined
1962
- ): Promise<void> {
1963
- return await addBackgroundForeground(
1964
- await this.internal_getId(),
1965
- await fromPdf.internal_getId(),
1966
- sourcePageIndex,
1967
- true,
1968
- applyToPages
1969
- );
1970
- }
1971
-
1972
- /**
1973
- * Adds a foreground to each page of this PDF. The background is copied from a first page in the
1974
- * backgroundPdf document.
1975
- *
1976
- * @param fromPdf foreground PDF document
1977
- * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
1978
- * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
1979
- */
1980
- private async internal_addForegroundFromAnotherPdf(
1981
- fromPdf: PdfDocument,
1982
- sourcePageIndex = 0,
1983
- applyToPages?: PdfPageSelection | undefined
1984
- ): Promise<void> {
1985
- return await addBackgroundForeground(
1986
- await this.internal_getId(),
1987
- await fromPdf.internal_getId(),
1988
- sourcePageIndex,
1989
- false,
1990
- applyToPages
1991
- );
1992
- }
1993
-
1994
- //#endregion
1995
-
1996
- //#region security
1997
- /**
1998
- * Removes all user and owner password security for a PDF document. Also disables content
1999
- * encryption.
2000
- * If content is encrypted at 128 bit, copy and paste of content, annotations and form editing may be disabled.
2001
- */
2002
- private async internal_removePasswordsAndEncryption(): Promise<void> {
2003
- await removePasswordsAndEncryption(await this.internal_getId());
2004
- }
2005
-
2006
- /**
2007
- * Sets the user password and enables 128Bit encryption of PDF content.
2008
- * A user password is a password that each user must enter to open or print the PDF document.
2009
- */
2010
- private async internal_setUserPassword(userPassword: string): Promise<void> {
2011
- if (!this.pdfPassword)
2012
- this.pdfPassword = {userPassword: userPassword};
2013
- else this.pdfPassword.userPassword = userPassword;
2014
- this.pdfDocumentId = await setUserPasswords(
2015
- await this.internal_getId(),
2016
- userPassword
2017
- );
2018
- }
2019
-
2020
- /**
2021
- * Sets the owner password and enables 128Bit encryption of PDF content. An owner password is one used to
2022
- * enable and disable all other security settings. <para>OwnerPassword must be set to a non-empty string
2023
- * value for {@link PdfPermission.AllowAccessibilityExtractContent} , {@link PdfPermission.AllowAnnotations} ,
2024
- * {@link PdfPermission.AllowFillForms}, {@link PdfPermission.AllowPrint}, {@link PdfPermission.AllowModify} to be
2025
- * restricted.
2026
- */
2027
- private async internal_setOwnerPassword(ownerPassword: string): Promise<void> {
2028
- if (!this.pdfPassword)
2029
- this.pdfPassword = {ownerPassword: ownerPassword};
2030
- else this.pdfPassword.ownerPassword = ownerPassword;
2031
- this.pdfDocumentId = await setOwnerPasswords(
2032
- await this.internal_getId(),
2033
- ownerPassword
2034
- );
2035
- }
2036
-
2037
- /**
2038
- * Sets the permissions of this PdfDocument
2039
- * @param permissions see {@link PdfPermission}
2040
- */
2041
- private async internal_setPermission(permissions: PdfPermission): Promise<void> {
2042
- this.pdfDocumentId = await setSecurity(await this.internal_getId(), permissions);
2043
- }
2044
-
2045
- /**
2046
- * Gets the current permissions of this PdfDocument
2047
- * @return {@link PdfPermission}
2048
- */
2049
- private async internal_getPermission(): Promise<PdfPermission> {
2050
- return await getPermission(await this.internal_getId());
2051
- }
2052
-
2053
- /**
2054
- * Makes this PDF document read only such that: Content is encrypted at 128 bit. Copy and paste of
2055
- * content is disallowed. Annotations and form editing are disabled.
2056
- * @param ownerPassword The owner password for the PDF. A string for owner password is required to enable PDF encryption and
2057
- * all document security options.
2058
- */
2059
- private async internal_makePdfDocumentReadOnly(ownerPassword: string): Promise<void> {
2060
- await this.internal_setOwnerPassword(ownerPassword);
2061
- await this.internal_setPermission({
2062
- AllowExtractContent: false,
2063
- AllowAccessibilityExtractContent: false,
2064
- AllowAnnotations: false,
2065
- AllowModify: false,
2066
- AllowAssembleDocument: false,
2067
- AllowFillForms: false,
2068
- });
2069
- }
2070
-
2071
- //#endregion
2072
-
2073
- //#endregion
2074
- }
1
+ import {Buffer} from "buffer";
2
+ import {
3
+ BarcodeStampOptions,
4
+ BarcodeType, ChangeTrackingModes,
5
+ ChromePdfRenderOptions,
6
+ DigitalSignature,
7
+ VerifiedSignature,
8
+ HtmlAffix,
9
+ HtmlFilePath,
10
+ HtmlStampOptions,
11
+ HtmlString,
12
+ HttpLoginCredentials,
13
+ ImageBuffer,
14
+ ImageFilePath,
15
+ ImageStampOptions,
16
+ ImageToPdfOptions,
17
+ ImageType,
18
+ PageInfo,
19
+ PageRotation,
20
+ PdfInput,
21
+ PdfPageSelection,
22
+ PdfPaperSize,
23
+ PdfPassword, PdfPermission,
24
+ SaveOptions,
25
+ TextAffix,
26
+ TextStampOptions,
27
+ } from "./types";
28
+
29
+ import {
30
+ barcodeTypeSchema, booleanSchema, bufferArraySchema, bufferSchema, changeTrackingModesSchema,
31
+ filePathSchema,
32
+ htmlFilePathSchema,
33
+ htmlStringSchema,
34
+ imageBufferSchema,
35
+ imageFilePathSchema,
36
+ mapStringSchema,
37
+ numberSchema, pdfFilePathSchema,
38
+ pdfInputSchema,
39
+ pdfPageSelectionSchema, pdfPasswordSchema, saveOptionsSchema, stringArraySchema,
40
+ stringSchema, urlSchema
41
+ } from "../internal/zod/typeSchema";
42
+ import {z} from "zod";
43
+ import {pdfPermissionSchema} from "../internal/zod/securitySchema";
44
+ import {pdfDocumentSchema} from "../internal/zod/pdfDocumentSchema";
45
+ import {
46
+ barcodeStampOptionsSchema,
47
+ htmlStampOptionsSchema,
48
+ imageStampOptionsSchema,
49
+ textStampOptionsSchema
50
+ } from "../internal/zod/stampSchema";
51
+ import {htmlAffixSchema, textAffixSchema} from "../internal/zod/affixSchema";
52
+ import {digitalSignatureSchema} from "../internal/zod/signatureSchema";
53
+ import {imageToPdfOptionsSchema, imageTypeSchema} from "../internal/zod/imageSchema";
54
+ import {pdfPaperSizeSchema} from "../internal/zod/paperSchema";
55
+ import {pageRotationSchema} from "../internal/zod/pageSchema";
56
+ import {chromePdfRenderOptionsSchema, httpLoginCredentialsSchema} from "../internal/zod/renderSchema";
57
+ import {
58
+ getFileName,
59
+ getImageExtType,
60
+ separateImageBufferOrImagePathInput,
61
+ separatePdfInput
62
+ } from "../internal/grpc_layer/util";
63
+ import fs from "fs";
64
+ import {mergePdfs, renderHtmlToPdf, renderHtmlZipToPdf, renderUrlToPdf, renderHtmlFileToPdf} from "../internal/grpc_layer/chrome/render";
65
+ import {disposePdf, getBinaryData, openPdfFileBuffer} from "../internal/grpc_layer/pdfium/io";
66
+ import {Access} from "../internal/access";
67
+ import {renderImagesBufferToPdf, renderImagesFilesToPdf} from "../internal/grpc_layer/chrome/image";
68
+ import {compressAndSaveAs, compressImage, compressInMemory, compressInMemoryStream, compressStructTree} from "../internal/grpc_layer/pdfium/compress";
69
+ import {Readable} from "stream";
70
+ import {
71
+ duplicate,
72
+ getPageInfo,
73
+ insertPdf,
74
+ removePage,
75
+ resizePage,
76
+ setPageRotation
77
+ } from "../internal/grpc_layer/pdfium/page";
78
+ import {extractRawImages, rasterizeToImageBuffers} from "../internal/grpc_layer/pdfium/image";
79
+ import Jimp from "jimp";
80
+ import {extractAllText, replaceText} from "../internal/grpc_layer/pdfium/text";
81
+ import {PdfAVersions, PdfUAVersions, toPdfA, toPdfUA} from "../internal/grpc_layer/pdfium/pdfa";
82
+ import {getMetadataDict, removeMetadata, setMetadata, setMetadataDict} from "../internal/grpc_layer/pdfium/metadata";
83
+ import {getSignatureCount, getVerifiedSignatures, signPdf} from "../internal/grpc_layer/pdfium/signing";
84
+ import {addHtmlAffix, addTextAffix} from "../internal/grpc_layer/pdfium/headerFooter";
85
+ import {stampBarcode, stampHtml, stampImage, stampText} from "../internal/grpc_layer/chrome/stamp";
86
+ import {addBackgroundForeground} from "../internal/grpc_layer/pdfium/BackgroundForeground";
87
+ import {
88
+ getPermission,
89
+ removePasswordsAndEncryption,
90
+ setOwnerPasswords, setSecurity,
91
+ setUserPasswords
92
+ } from "../internal/grpc_layer/pdfium/security";
93
+ import { NaturalLanguages } from "./naturalLanguages";
94
+
95
+ /**
96
+ * Represents a PDF document. Allows: loading, editing, manipulating, merging, signing printing and saving PDFs.
97
+ *
98
+ * @remark Make sure that you call {@link PdfDocument.close} or {@link cleanUp} to free the memory, when you stop using the PdfDocument object.
99
+ */
100
+ export class PdfDocument{
101
+
102
+ //#region io
103
+
104
+ /**
105
+ * Open or Create a PdfDocument from a {@link PdfInput}
106
+ * @param pdfInput {@link PdfInput}
107
+ * @param options including {@link PdfPassword} {@link ChromePdfRenderOptions} {@link HttpLoginCredentials} mainHtmlFile
108
+ */
109
+ public static async open(
110
+ pdfInput: PdfInput,
111
+ options?: {
112
+ /**
113
+ * required for open a protected PDF file
114
+ * @default undefined
115
+ */
116
+ password?: PdfPassword | undefined;
117
+ /**
118
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
119
+ * @default undefined
120
+ */
121
+ renderOptions?: ChromePdfRenderOptions | undefined;
122
+ /**
123
+ * Apply httpLoginCredentials if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
124
+ * @default undefined
125
+ */
126
+ httpLoginCredentials?: HttpLoginCredentials | undefined;
127
+ /**
128
+ * Apply mainHtmlFile if PdfInput is {@link ZipFilePath}
129
+ * @default index.html
130
+ */
131
+ mainHtmlFile?: string | undefined;
132
+ /**
133
+ * Optionally track changes to the document (for use with incremental saves)
134
+ * @default {@link ChangeTrackingModes.AutoChangeTracking}
135
+ */
136
+ trackChanges?: ChangeTrackingModes | undefined;
137
+ // /**
138
+ // * Apply baseUrl if
139
+ // * The HTML base URL for which references to external CSS, Javascript and Image files will be relative.
140
+ // * @default undefined
141
+ // */
142
+ // baseUrl ?: string | undefined; //not supported
143
+ } | undefined
144
+ ): Promise<PdfDocument> {
145
+ return z.function()
146
+ .args(
147
+ pdfInputSchema,
148
+ z.object({
149
+ password: pdfPasswordSchema.optional(),
150
+ renderOptions: chromePdfRenderOptionsSchema.optional(),
151
+ httpLoginCredentials: httpLoginCredentialsSchema.optional(),
152
+ mainHtmlFile: stringSchema.optional(),
153
+ trackChanges: changeTrackingModesSchema.optional(),
154
+ }).optional()
155
+ )
156
+ .returns(z.promise(pdfDocumentSchema))
157
+ .implement(this.internal_open.bind(this))
158
+ (pdfInput, options);
159
+ }
160
+
161
+ /**
162
+ * Open a PdfDocument from .pdf file
163
+ * @param pdfFilePath A path to .pdf file
164
+ * @param Optionally track changes to the document (for use with incremental saves)
165
+ */
166
+ public static async fromFile(
167
+ pdfFilePath: string, trackChanges?: ChangeTrackingModes | undefined
168
+ ): Promise<PdfDocument> {
169
+ return z.function()
170
+ .args(
171
+ pdfFilePathSchema,
172
+ changeTrackingModesSchema.optional()
173
+ )
174
+ .returns(z.promise(pdfDocumentSchema))
175
+ .implement(this.internal_fromFile.bind(this))
176
+ (pdfFilePath, trackChanges);
177
+ }
178
+
179
+ /**
180
+ * Create a PdfDocument from an Url
181
+ * @param url A website Url
182
+ * @param options including {@link ChromePdfRenderOptions}
183
+ */
184
+ public static async fromUrl(
185
+ url: URL | string,
186
+ options?: {
187
+ /**
188
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
189
+ * @default undefined
190
+ */
191
+ renderOptions?: ChromePdfRenderOptions | undefined;
192
+ } | undefined
193
+ ): Promise<PdfDocument> {
194
+ return z.function()
195
+ .args(
196
+ z.union([urlSchema, stringSchema]),
197
+ z.object({
198
+ renderOptions: chromePdfRenderOptionsSchema.optional(),
199
+ }).optional()
200
+ )
201
+ .returns(z.promise(pdfDocumentSchema))
202
+ .implement(this.internal_fromUrl.bind(this))
203
+ (url, options);
204
+ }
205
+
206
+ /**
207
+ * Creates a PDF file from a local Zip file, and returns it as a {@link PdfDocument}.
208
+ * IronPDF is a W3C standards compliant HTML rendering based on Google's Chromium browser.
209
+ * If your output PDF does not look as expected:
210
+ *
211
+ * - Validate your HTML file using https://validator.w3.org/ &amp; CSS https://jigsaw.w3.org/css-validator/
212
+ *
213
+ * - To debug HTML, view the file in Chrome web browser's print preview which will work almost exactly as IronPDF.
214
+ *
215
+ * - Read our detailed documentation on pixel perfect HTML to PDF: https://ironpdf.com/tutorials/pixel-perfect-html-to-pdf/
216
+ *
217
+ * @param zipFilePath Path to a Zip to be rendered as a PDF.
218
+ * @param options including {@link ChromePdfRenderOptions} and `mainHtmlFile` a main .html file default: `index.html`
219
+ */
220
+ public static async fromZip(
221
+ zipFilePath: string,
222
+ options?: {
223
+ /**
224
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
225
+ * @default undefined
226
+ */
227
+ renderOptions?: ChromePdfRenderOptions | undefined;
228
+ /**
229
+ * a main .html file default: `index.html`
230
+ */
231
+ mainHtmlFile?: string | undefined;
232
+ } | undefined
233
+ ): Promise<PdfDocument> {
234
+ return z.function()
235
+ .args(
236
+ stringSchema,
237
+ z.object({
238
+ renderOptions: chromePdfRenderOptionsSchema.optional(),
239
+ mainHtmlFile: stringSchema.optional()
240
+ }).optional()
241
+ )
242
+ .returns(z.promise(pdfDocumentSchema))
243
+ .implement(this.internal_fromZip.bind(this))
244
+ (zipFilePath, options);
245
+ }
246
+
247
+ /**
248
+ * Creates a PDF file from a Html string, and returns it as an {@link PdfDocument} object which can be edited and saved to disk or served on a website.
249
+ *
250
+ * ------------------------------------------------
251
+ *
252
+ * **Usage:**
253
+ * ```ts
254
+ * const pdf = await fromHtml(htmlStringOrHtmlFilePath, renderOptions);
255
+ * ```
256
+ *
257
+ * ------------------------------------------------
258
+ *
259
+ * @param htmlStringOrHtmlFilePath The Html to be rendered as a PDF.
260
+ * @param options including {@link ChromePdfRenderOptions}
261
+ * @returns A `PdfDocument` generated from the provided HTML file.
262
+ *
263
+ * ---
264
+ * ### Important Notes:
265
+ *
266
+ * 🐳 **Docker Limitation:**
267
+ * This method **does not work** for **HTML file path** when the application runs inside a Docker environment
268
+ * due to rendering engine restrictions.
269
+ * In such cases, use `fromZip()` instead.
270
+ *
271
+ * 📄 **Input:** Requires access to a local HTML file on disk if htmlFilePath is passing.
272
+ *
273
+ * ---
274
+ * ### Related Methods:
275
+ * 📌 `fromZip()` — Recommended alternative for rendering from HTML file when running inside Docker.
276
+ */
277
+ public static async fromHtml(
278
+ htmlStringOrHtmlFilePath: string,
279
+ options?: {
280
+ /**
281
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
282
+ * @default undefined
283
+ */
284
+ renderOptions?: ChromePdfRenderOptions | undefined;
285
+ } | undefined
286
+ ): Promise<PdfDocument> {
287
+ return z.function()
288
+ .args(
289
+ stringSchema,
290
+ z.object({
291
+ renderOptions: chromePdfRenderOptionsSchema.optional(),
292
+ }).optional()
293
+ )
294
+ .returns(z.promise(pdfDocumentSchema))
295
+ .implement(this.internal_fromHtml.bind(this))
296
+ (htmlStringOrHtmlFilePath, options);
297
+ }
298
+
299
+ /**
300
+ * Converts multiple image files to a PDF document. Each image creates 1 page which matches the image
301
+ * dimensions. The default PaperSize is A4. You can set it via ImageToPdfConverter.PaperSize.
302
+ * Note: Imaging.ImageBehavior.CropPage will set PaperSize equal to ImageSize.
303
+ * @param images The image file path name(s) or {@link ImageBuffer} object(s)
304
+ * @param options including {@link ImageToPdfOptions}
305
+ */
306
+ public static async fromImage(
307
+ images: ImageFilePath | ImageFilePath[] | ImageBuffer | ImageBuffer[],
308
+ options?: {
309
+ /**
310
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
311
+ * @default undefined
312
+ */
313
+ imageToPdfOptions?: ImageToPdfOptions | undefined;
314
+ }
315
+ ): Promise<PdfDocument> {
316
+ return z.function()
317
+ .args(
318
+ z.union([imageFilePathSchema, z.array(imageFilePathSchema), imageBufferSchema, z.array(imageBufferSchema)]),
319
+ z.object({
320
+ imageToPdfOptions: imageToPdfOptionsSchema.optional(),
321
+ }).optional()
322
+ )
323
+ .returns(z.promise(pdfDocumentSchema))
324
+ .implement(this.internal_fromImage.bind(this))
325
+ (images, options);
326
+ }
327
+
328
+ /**
329
+ * Static method that joins (concatenates) multiple PDF documents together into one compiled PDF document.
330
+ * If the PDF contains form fields the form field in the resulting PDF's name will be appended with '_{index}' e.g. 'Name' will be 'Name_0'
331
+ * @param pdfs array of PDF
332
+ */
333
+ public static async mergePdf(pdfs: PdfInput[]): Promise<PdfDocument> {
334
+ return z.function()
335
+ .args(
336
+ z.array(pdfInputSchema)
337
+ )
338
+ .returns(z.promise(pdfDocumentSchema))
339
+ .implement(this.internal_mergePdf.bind(this))
340
+ (pdfs);
341
+ }
342
+
343
+ /**
344
+ * Saves the PdfDocument to a file.
345
+ * @param filePath Target file path
346
+ * @param saveOptions see {@link SaveOptions}
347
+ */
348
+ public saveAs(filePath: string, saveOptions?: SaveOptions | undefined): Promise<void> {
349
+ return z.function()
350
+ .args(
351
+ stringSchema,
352
+ saveOptionsSchema.optional()
353
+ )
354
+ .returns(z.promise(z.void()))
355
+ .implement(this.internal_saveAs.bind(this))
356
+ (filePath, saveOptions);
357
+ }
358
+
359
+ /**
360
+ * Saves the PdfDocument to a binary (Buffer)
361
+ * @param saveOptions see {@link SaveOptions}
362
+ */
363
+ public async saveAsBuffer(saveOptions?: SaveOptions | undefined): Promise<Buffer> {
364
+ return z.function()
365
+ .args(
366
+ saveOptionsSchema.optional()
367
+ )
368
+ .returns(z.promise(bufferSchema))
369
+ .implement(this.internal_saveAsBuffer.bind(this))
370
+ (saveOptions);
371
+ }
372
+
373
+ //#endregion
374
+
375
+ //#region compress
376
+ /**
377
+ * Compress existing PDF images using JPG encoding and the specified settings.
378
+ * @deprecated Use {@link compressAndSaveAs}, {@link compressPdfToBytes}, or {@link compressPdfToStream} instead for better compression results.
379
+ * @param imageQuality Quality (1 - 100) to use during compression
380
+ * @param scaleToVisibleSize Scale down the image resolution according to its visible size in the PDF document
381
+ */
382
+ public async compressSize(
383
+ imageQuality: number,
384
+ scaleToVisibleSize = false
385
+ ): Promise<void> {
386
+ return await z.function()
387
+ .args(
388
+ numberSchema,
389
+ booleanSchema.optional()
390
+ )
391
+ .returns(z.promise(z.void()))
392
+ .implement(this.internal_compressSize.bind(this))
393
+ (imageQuality, scaleToVisibleSize);
394
+ }
395
+
396
+ /**
397
+ * Remove document struct tree information which describes the logical layout of the document.
398
+ * Removing the "structure tree" can significantly reduce the disk space used by the document.
399
+ * Removing the "structure tree" of a complicated document can negatively impact text selection.
400
+ */
401
+ public async compressStructTree(): Promise<void> {
402
+ return this.internal_compressStructTree()
403
+ }
404
+
405
+ /**
406
+ * Compress the PDF and return the result as a Buffer (byte array).
407
+ * Uses QPdf compression which can significantly reduce file size.
408
+ * @param imageQuality Optional JPEG quality (1-100) for image compression. If omitted, default compression is applied.
409
+ * @returns A Promise resolving to a Buffer containing the compressed PDF bytes.
410
+ */
411
+ public async compressPdfToBytes(
412
+ imageQuality?: number
413
+ ): Promise<Buffer> {
414
+ return await z.function()
415
+ .args(
416
+ numberSchema.optional()
417
+ )
418
+ .returns(z.promise(z.instanceof(Buffer)))
419
+ .implement(this.internal_compressPdfToBytes.bind(this))
420
+ (imageQuality);
421
+ }
422
+
423
+ /**
424
+ * Compress the PDF and return the result as a Readable stream.
425
+ * Uses QPdf compression which can significantly reduce file size.
426
+ * Useful for piping directly to file streams or HTTP responses without buffering the entire PDF in memory.
427
+ * @param imageQuality Optional JPEG quality (1-100) for image compression. If omitted, default compression is applied.
428
+ * @returns A Promise resolving to a Readable stream of the compressed PDF bytes.
429
+ */
430
+ public async compressPdfToStream(
431
+ imageQuality?: number
432
+ ): Promise<Readable> {
433
+ return await z.function()
434
+ .args(
435
+ numberSchema.optional()
436
+ )
437
+ .returns(z.promise(z.any()))
438
+ .implement(this.internal_compressPdfToStream.bind(this))
439
+ (imageQuality);
440
+ }
441
+
442
+ /**
443
+ * Compress the PDF and save the result directly to a file.
444
+ * Uses QPdf compression which can significantly reduce file size.
445
+ * @param filePath The output file path to save the compressed PDF.
446
+ * @param imageQuality Optional JPEG quality (1-100) for image compression. If omitted, default compression is applied.
447
+ */
448
+ public async compressAndSaveAs(
449
+ filePath: string,
450
+ imageQuality?: number
451
+ ): Promise<void> {
452
+ return await z.function()
453
+ .args(
454
+ stringSchema,
455
+ numberSchema.optional()
456
+ )
457
+ .returns(z.promise(z.void()))
458
+ .implement(this.internal_compressAndSaveAs.bind(this))
459
+ (filePath, imageQuality);
460
+ }
461
+
462
+ //#endregion
463
+
464
+ //#region page
465
+ /**
466
+ * Gets information of all pages in the PdfDocument
467
+ */
468
+ public async getPagesInfo(): Promise<PageInfo[]> {
469
+ return this.internal_getPagesInfo()
470
+ }
471
+
472
+ /**
473
+ * Gets the number of pages in the PdfDocument.
474
+ */
475
+ public async getPageCount(): Promise<number> {
476
+ return this.internal_getPageCount()
477
+ }
478
+
479
+ /**
480
+ * Set the page orientation.
481
+ * @param pageRotation see {@link PageRotation}
482
+ * @param options including {@link PdfPageSelection}
483
+ */
484
+ public async setRotation(
485
+ pageRotation: PageRotation,
486
+ options?: {
487
+ /**
488
+ * @default "all"
489
+ */
490
+ pdfPageSelection?: PdfPageSelection | undefined;
491
+ } | undefined
492
+ ) {
493
+ return z.function()
494
+ .args(
495
+ pageRotationSchema,
496
+ z.object({pdfPageSelection: pdfPageSelectionSchema.optional()}).optional()
497
+ )
498
+ .returns(z.promise(z.void()))
499
+ .implement(this.internal_setRotation.bind(this))
500
+ (pageRotation, options);
501
+ }
502
+
503
+ /**
504
+ * Resize a page to the specified dimensions
505
+ * @param newSize {@link PdfPaperSize}
506
+ * @param options including {@link PdfPageSelection}
507
+ */
508
+ public async resize(
509
+ newSize: PdfPaperSize,
510
+ options?: {
511
+ /**
512
+ * @default "all"
513
+ */
514
+ pdfPageSelection?: PdfPageSelection | undefined;
515
+ } | undefined
516
+ ): Promise<void> {
517
+ return z.function()
518
+ .args(
519
+ pdfPaperSizeSchema,
520
+ z.object({pdfPageSelection: pdfPageSelectionSchema.optional()}).optional()
521
+ )
522
+ .returns(z.promise(z.void()))
523
+ .implement(this.internal_resize.bind(this))
524
+ (newSize, options);
525
+ }
526
+
527
+ /**
528
+ * Adds another PDF to the beginning of the current PdfDocument
529
+ * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
530
+ * @param fromPdfDocument PdfDocument to prepend
531
+ */
532
+ public async prependAnotherPdf(
533
+ fromPdfDocument: PdfDocument
534
+ ): Promise<void> {
535
+ return z.function()
536
+ .args(pdfDocumentSchema)
537
+ .returns(z.promise(z.void()))
538
+ .implement(this.internal_prependAnotherPdf.bind(this))
539
+ (fromPdfDocument);
540
+ }
541
+
542
+ /**
543
+ * Appends another PDF to the end of the current <see cref="PdfDocument"/>
544
+ * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
545
+ * @param fromPdfDocument PdfDocument to Append
546
+ */
547
+ public async appendAnotherPdf(fromPdfDocument: PdfDocument): Promise<void> {
548
+ return z.function()
549
+ .args(pdfDocumentSchema)
550
+ .returns(z.promise(z.void()))
551
+ .implement(this.internal_appendAnotherPdf.bind(this))
552
+ (fromPdfDocument);
553
+ }
554
+
555
+ /**
556
+ * Inserts another PDF into the current PdfDocument, starting at a given Page Index.
557
+ * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
558
+ * @param fromPdfDocument Another PdfDocument
559
+ * @param insertAtPageIndex Index at which to insert the new content. Note: Page 1 has index 0...
560
+ */
561
+ public async insertPagesFromAnotherPdf(
562
+ fromPdfDocument: PdfDocument,
563
+ insertAtPageIndex: number
564
+ ): Promise<void> {
565
+ return z.function()
566
+ .args(pdfDocumentSchema, numberSchema.describe("insertAtPageIndex: number"))
567
+ .returns(z.promise(z.void()))
568
+ .implement(this.internal_insertPagesFromAnotherPdf.bind(this))
569
+ (fromPdfDocument, insertAtPageIndex);
570
+ }
571
+
572
+ /**
573
+ * Removes a range of pages from the PDF
574
+ * @param pages pages to remove
575
+ */
576
+ public async removePage(pages: PdfPageSelection): Promise<void> {
577
+ return z.function()
578
+ .args(pdfPageSelectionSchema)
579
+ .returns(z.promise(z.void()))
580
+ .implement(this.internal_removePage.bind(this))
581
+ (pages);
582
+ }
583
+
584
+ /**
585
+ * Creates a new PDF by copying a range of pages from this {@link PdfDocument}.
586
+ * @param pages pages to copy (default "all")
587
+ */
588
+ public async duplicate(
589
+ pages: PdfPageSelection = "all"
590
+ ): Promise<PdfDocument> {
591
+ return z.function()
592
+ .args(pdfPageSelectionSchema)
593
+ .returns(z.promise(pdfDocumentSchema))
594
+ .implement(this.internal_duplicate.bind(this))
595
+ (pages);
596
+ }
597
+
598
+ //#endregion
599
+
600
+ //#region image
601
+ /**
602
+ * Finds all embedded Images from within a specified pages in the PDF and returns them as Buffer
603
+ * @param options including {@link PdfPageSelection}
604
+ */
605
+ public async extractRawImages(options?: {
606
+ /**
607
+ * @default "all"
608
+ */
609
+ fromPages?: PdfPageSelection;
610
+ } | undefined): Promise<Buffer[]> {
611
+ return z.function()
612
+ .args(
613
+ z.object({fromPages: pdfPageSelectionSchema.optional()}).optional()
614
+ )
615
+ .returns(z.promise(bufferArraySchema))
616
+ .implement(this.internal_extractRawImages.bind(this))
617
+ (options);
618
+ }
619
+
620
+ /**
621
+ * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
622
+ * page.
623
+ *
624
+ * @param options including {@link PdfPageSelection} {@link ImageType}
625
+ *
626
+ * @return array of images as Buffer[]
627
+ */
628
+ public async rasterizeToImageBuffers(options?: {
629
+ /**
630
+ * @default "all"
631
+ */
632
+ fromPages?: PdfPageSelection | undefined;
633
+ /**
634
+ * @default {@link ImageType.PNG}
635
+ */
636
+ imageType?: ImageType | undefined;
637
+ } | undefined): Promise<Buffer[]> {
638
+ return z.function()
639
+ .args(
640
+ z.object({
641
+ fromPages: pdfPageSelectionSchema.optional(),
642
+ imageType: imageTypeSchema.optional()
643
+ }).optional()
644
+ )
645
+ .returns(z.promise(bufferArraySchema))
646
+ .implement(this.internal_rasterizeToImageBuffers.bind(this))
647
+ (options);
648
+ }
649
+
650
+ /**
651
+ * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
652
+ * page. Running number will append output file path.
653
+ *
654
+ * @param filePath output file path.
655
+ * @param options including {@link PdfPageSelection} {@link ImageType}
656
+ *
657
+ * @return array of images file name as string[]
658
+ */
659
+ public async rasterizeToImageFiles(
660
+ filePath: string,
661
+ options?: {
662
+ /**
663
+ * @default "all"
664
+ */
665
+ fromPages?: PdfPageSelection | undefined;
666
+ /**
667
+ * @default {@link ImageType.PNG}
668
+ */
669
+ type?: ImageType | undefined;
670
+ } | undefined
671
+ ): Promise<string[]> {
672
+ return z.function()
673
+ .args(
674
+ filePathSchema,
675
+ z.object({
676
+ fromPages: pdfPageSelectionSchema.optional(),
677
+ type: imageTypeSchema.optional()
678
+ }).optional()
679
+ )
680
+ .returns(z.promise(stringArraySchema))
681
+ .implement(this.internal_rasterizeToImageFiles.bind(this))
682
+ (filePath, options);
683
+ }
684
+
685
+ //#endregion
686
+
687
+ //#region text
688
+ /**
689
+ * Replace the specified old text with new text on a given page
690
+ * @param oldText Old text to remove
691
+ * @param newText New text to add
692
+ * @param onPages Page index to search for old text to replace (default "all")
693
+ */
694
+ public async replaceText(
695
+ oldText: string,
696
+ newText: string,
697
+ onPages?: PdfPageSelection | undefined
698
+ ): Promise<void> {
699
+ return z.function()
700
+ .args(
701
+ z.string({description: "oldText: string"}),
702
+ z.string({description: "newText: string"}),
703
+ pdfPageSelectionSchema.optional())
704
+ .returns(z.promise(z.void()))
705
+ .implement(this.internal_replaceText.bind(this))
706
+ (oldText, newText, onPages);
707
+ }
708
+
709
+ public async extractText(
710
+ onPages?: PdfPageSelection | undefined
711
+ ): Promise<string> {
712
+ return z.function()
713
+ .args(pdfPageSelectionSchema.optional())
714
+ .returns(z.promise(z.string()))
715
+ .implement(this.internal_extractText.bind(this))
716
+ (onPages);
717
+ }
718
+
719
+ //#endregion
720
+
721
+ //#region pdfA
722
+ /**
723
+ * Convert the current document into the specified PDF-A standard format
724
+ * @param pdfaVersion The PDF/A version to convert to (default: PdfA3b)
725
+ * @param customICC (Optional) Custom color profile file path
726
+ */
727
+ public async convertToPdfA(pdfaVersion: PdfAVersions = PdfAVersions.PdfA3b, customICC?: string | undefined): Promise<void> {
728
+ return z.function()
729
+ .args(
730
+ z.nativeEnum(PdfAVersions, {description: "pdfaVersion: PdfAVersions"}),
731
+ z.string({description: "customICC: string"}).optional()
732
+ )
733
+ .returns(z.promise(z.void()))
734
+ .implement(this.internal_convertToPdfA.bind(this))
735
+ (pdfaVersion, customICC);
736
+ }
737
+
738
+ // TODO: Re-enable once IronPdfEngine handler for Pdfium_ConvertToPdfUAForScreenReader
739
+ // is fixed to call HtmlHelper.HtmlStructTreeDOM() and ConvertToPdfUAForScreenReader().
740
+ // Currently the engine handler ignores the HTML and falls back to basic ConvertToPdfUA,
741
+ // producing a flat tag tree instead of proper semantic structure.
742
+ // See: IronPdfServiceHandler.cs:97-108
743
+ //
744
+ // public static async fromHtmlAsPdfUA(
745
+ // html: string,
746
+ // naturalLanguages: NaturalLanguages = NaturalLanguages.English,
747
+ // options?: {
748
+ // renderOptions?: ChromePdfRenderOptions | undefined;
749
+ // } | undefined
750
+ // ): Promise<PdfDocument> {
751
+ // const pdf = await PdfDocument.fromHtml(html, options);
752
+ // await toPdfUAForScreenReader(await pdf.internal_getId(), html, naturalLanguages);
753
+ // return pdf;
754
+ // }
755
+
756
+ /**
757
+ * Convert the current document into the specified PDF/UA standard format
758
+ */
759
+ public async convertToPdfUA(naturalLanguages: NaturalLanguages, pdfUaVersion: PdfUAVersions = PdfUAVersions.PdfUA1): Promise<void> {
760
+ return this.internal_convertToPdfUA(naturalLanguages, pdfUaVersion)
761
+ }
762
+
763
+ //#endregion
764
+
765
+ //#region metadata
766
+ /**
767
+ * Gets a Map<string, string> of metadata properties
768
+ */
769
+ public async getMetadata(): Promise<Map<string, string>> {
770
+ return this.internal_getMetadata()
771
+ }
772
+
773
+ /**
774
+ * Add or Update a single metadata property
775
+ * @param key
776
+ * @param value
777
+ */
778
+ public async addOrUpdateMetadata(
779
+ key: string,
780
+ value: string
781
+ ): Promise<void> {
782
+ return z.function()
783
+ .args(z.string({description: "key: string"}), z.string({description: "value: string"}))
784
+ .returns(z.promise(z.void()))
785
+ .implement(this.internal_addOrUpdateMetadata.bind(this))
786
+ (key, value);
787
+ }
788
+
789
+ /**
790
+ * Remove a single metadata property
791
+ * @param key
792
+ */
793
+ public async removeMetadata(key: string): Promise<void> {
794
+ return z.function()
795
+ .args(z.string({description: "key: string"}))
796
+ .returns(z.promise(z.void()))
797
+ .implement(this.internal_removeMetadata.bind(this))
798
+ (key);
799
+ }
800
+
801
+ /**
802
+ * Sets a whole metadata properties Map<string, string> (override all the metadata property)
803
+ * @param newMetadataDictionary new metadata properties Map<string, string>
804
+ */
805
+ public async overrideMetadata(
806
+ newMetadataDictionary: Map<string, string>
807
+ ): Promise<void> {
808
+ return z.function()
809
+ .args(mapStringSchema)
810
+ .returns(z.promise(z.void()))
811
+ .implement(this.internal_overrideMetadata.bind(this))
812
+ (newMetadataDictionary);
813
+ }
814
+
815
+ //#endregion
816
+
817
+ //#region signing
818
+ /**
819
+ * Sign PDF with digital signature certificate.
820
+ * Note that the PDF will not be fully signed until Saved
821
+ * using {@link saveAs} or {@link saveAsBuffer}
822
+ *
823
+ * Multiple certificates may be used.
824
+ * @param signature see {@link DigitalSignature}
825
+ */
826
+ public async signDigitalSignature(signature: DigitalSignature) {
827
+ return z.function()
828
+ .args(digitalSignatureSchema)
829
+ .returns(z.promise(z.void()))
830
+ .implement(this.internal_signDigitalSignature.bind(this))
831
+ (signature);
832
+ }
833
+
834
+ /**
835
+ * Check if PdfDocument was signed or not
836
+ */
837
+ public async isSigned(): Promise<boolean> {
838
+ return this.internal_isSigned()
839
+ }
840
+
841
+ /**
842
+ * Count the number signature that signed to this PdfDocument
843
+ */
844
+ public async signatureCount(): Promise<number> {
845
+ return this.internal_signatureCount()
846
+ }
847
+
848
+ /**
849
+ * Get all verified digital signatures from this PdfDocument.
850
+ * Returns details including signature name, signer contact, reason, location, date, and validity.
851
+ * @returns A Promise resolving to an array of {@link VerifiedSignature} objects.
852
+ */
853
+ public async getVerifiedSignatures(): Promise<VerifiedSignature[]> {
854
+ return this.internal_getVerifiedSignatures()
855
+ }
856
+
857
+ //#endregion
858
+
859
+ //#region header/footer (affix)
860
+ /**
861
+ * Apply page header on top of an existing Pdf.
862
+ * @param header {@link TextAffix}
863
+ * @param toPages {@link PdfPageSelection}
864
+ */
865
+ public async addTextHeader(
866
+ header: TextAffix,
867
+ toPages?: PdfPageSelection | undefined
868
+ ): Promise<void> {
869
+ return z.function()
870
+ .args(textAffixSchema, pdfPageSelectionSchema.optional())
871
+ .returns(z.promise(z.void()))
872
+ .implement(this.internal_addTextHeader.bind(this))
873
+ (header, toPages);
874
+ }
875
+
876
+ /**
877
+ * Apply page footer on top of an existing Pdf.
878
+ * @param footer {@link TextAffix}
879
+ * @param toPages {@link PdfPageSelection}
880
+ */
881
+ public async addTextFooter(
882
+ footer: TextAffix,
883
+ toPages?: PdfPageSelection | undefined
884
+ ): Promise<void> {
885
+ return z.function()
886
+ .args(textAffixSchema, pdfPageSelectionSchema.optional())
887
+ .returns(z.promise(z.void()))
888
+ .implement(this.internal_addTextFooter.bind(this))
889
+ (footer, toPages);
890
+ }
891
+
892
+ /**
893
+ * Apply HTML header on top of an existing Pdf.
894
+ * @param header {@link HtmlAffix}
895
+ * @param toPages {@link PdfPageSelection}
896
+ */
897
+ public async addHtmlHeader(
898
+ header: HtmlAffix,
899
+ toPages?: PdfPageSelection | undefined
900
+ ): Promise<void> {
901
+ return z.function()
902
+ .args(htmlAffixSchema, pdfPageSelectionSchema.optional())
903
+ .returns(z.promise(z.void()))
904
+ .implement(this.internal_addHtmlHeader.bind(this))
905
+ (header, toPages);
906
+ }
907
+
908
+ /**
909
+ * Apply HTML footer on top of an existing Pdf.
910
+ * @param footer {@link HtmlAffix}
911
+ * @param toPages {@link PdfPageSelection}
912
+ */
913
+ public async addHtmlFooter(
914
+ footer: HtmlAffix,
915
+ toPages?: PdfPageSelection | undefined
916
+ ): Promise<void> {
917
+ return z.function()
918
+ .args(htmlAffixSchema, pdfPageSelectionSchema.optional())
919
+ .returns(z.promise(z.void()))
920
+ .implement(this.internal_addHtmlFooter.bind(this))
921
+ (footer, toPages);
922
+ }
923
+
924
+ //#endregion
925
+
926
+ //#region stamp
927
+ /**
928
+ * Edits the PDF by applying the HTML's rendered to only selected page(s).
929
+ * @param htmlStringOrHtmlFilePath
930
+ * @param options including {@link HtmlStampOptions} {@link PdfPageSelection}
931
+ */
932
+ public async stampHtml(
933
+ htmlStringOrHtmlFilePath: HtmlFilePath | HtmlString,
934
+ options?: {
935
+ htmlStampOptions?: HtmlStampOptions | undefined;
936
+ toPages?: PdfPageSelection | undefined;
937
+ } | undefined
938
+ ) {
939
+ return z.function()
940
+ .args(z.union([htmlFilePathSchema, htmlStringSchema]), z.object({
941
+ htmlStampOptions: htmlStampOptionsSchema.optional(),
942
+ toPages: pdfPageSelectionSchema.optional()
943
+ }).optional())
944
+ .returns(z.promise(z.void()))
945
+ .implement(this.internal_stampHtml.bind(this))
946
+ (htmlStringOrHtmlFilePath, options);
947
+ }
948
+
949
+ /**
950
+ * Edits the PDF by applying the image to only selected page(s).
951
+ * @param image image file path or image buffer
952
+ * @param options including {@link ImageStampOptions} {@link PdfPageSelection}
953
+ */
954
+ public async stampImage(
955
+ image: ImageFilePath | ImageBuffer,
956
+ options?: {
957
+ imageStampOptions?: ImageStampOptions | undefined;
958
+ toPages?: PdfPageSelection | undefined;
959
+ } | undefined
960
+ ) {
961
+ return z.function()
962
+ .args(z.union([imageFilePathSchema, imageBufferSchema]), z.object({
963
+ imageStampOptions: imageStampOptionsSchema.optional(),
964
+ toPages: pdfPageSelectionSchema.optional()
965
+ }).optional())
966
+ .returns(z.promise(z.void()))
967
+ .implement(this.internal_stampImage.bind(this))
968
+ (image, options);
969
+ }
970
+
971
+ /**
972
+ * Edits the PDF by applying the text to only selected page(s).
973
+ * @param text text to stamp
974
+ * @param options including {@link TextStampOptions} {@link PdfPageSelection}
975
+ */
976
+ public async stampText(
977
+ text: string,
978
+ options?: {
979
+ textStampOptions?: TextStampOptions | undefined;
980
+ toPages?: PdfPageSelection | undefined;
981
+ } | undefined
982
+ ) {
983
+ return z.function()
984
+ .args(stringSchema, z.object({
985
+ textStampOptions: textStampOptionsSchema.optional(),
986
+ toPages: pdfPageSelectionSchema.optional()
987
+ }).optional())
988
+ .returns(z.promise(z.void()))
989
+ .implement(this.internal_stampText.bind(this))
990
+ (text, options);
991
+ }
992
+
993
+ /**
994
+ * Edits the PDF by applying the barcode to only selected page(s).
995
+ * @param barcodeValue barcode
996
+ * @param options including {@link BarcodeType} {@link BarcodeStampOptions} {@link PdfPageSelection}
997
+ */
998
+ public async stampBarcode(
999
+ barcodeValue: string,
1000
+ options?: {
1001
+ barcodeEncoding: BarcodeType;
1002
+ barcodeStampOptions?: BarcodeStampOptions | undefined;
1003
+ toPages?: PdfPageSelection | undefined;
1004
+ } | undefined
1005
+ ) {
1006
+ return z.function()
1007
+ .args(stringSchema, z.object({
1008
+ barcodeEncoding: barcodeTypeSchema,
1009
+ barcodeStampOptions: barcodeStampOptionsSchema.optional(),
1010
+ toPages: pdfPageSelectionSchema.optional()
1011
+ }).optional())
1012
+ .returns(z.promise(z.void()))
1013
+ .implement(this.internal_stampBarcode.bind(this))
1014
+ (barcodeValue, options);
1015
+ }
1016
+
1017
+ //#endregion
1018
+
1019
+ //#region background/foreground
1020
+ /**
1021
+ * Adds a background to each page of this PDF. The background is copied from a first page in the
1022
+ * backgroundPdf document.
1023
+ *
1024
+ * @param fromPdf background PDF document
1025
+ * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
1026
+ * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
1027
+ */
1028
+ public async addBackgroundFromAnotherPdf(
1029
+ fromPdf: PdfDocument,
1030
+ sourcePageIndex = 0,
1031
+ applyToPages?: PdfPageSelection | undefined
1032
+ ): Promise<void> {
1033
+ return z.function()
1034
+ .args(pdfDocumentSchema, numberSchema, pdfPageSelectionSchema.optional())
1035
+ .returns(z.promise(z.void()))
1036
+ .implement(this.internal_addBackgroundFromAnotherPdf.bind(this))
1037
+ (fromPdf, sourcePageIndex, applyToPages);
1038
+ }
1039
+
1040
+ /**
1041
+ * Adds a foreground to each page of this PDF. The background is copied from a first page in the
1042
+ * backgroundPdf document.
1043
+ *
1044
+ * @param fromPdf foreground PDF document
1045
+ * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
1046
+ * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
1047
+ */
1048
+ public async addForegroundFromAnotherPdf(
1049
+ fromPdf: PdfDocument,
1050
+ sourcePageIndex = 0,
1051
+ applyToPages?: PdfPageSelection | undefined
1052
+ ): Promise<void> {
1053
+ return z.function()
1054
+ .args(pdfDocumentSchema, numberSchema, pdfPageSelectionSchema.optional())
1055
+ .returns(z.promise(z.void()))
1056
+ .implement(this.internal_addForegroundFromAnotherPdf.bind(this))
1057
+ (fromPdf, sourcePageIndex, applyToPages);
1058
+ }
1059
+
1060
+ //#endregion
1061
+
1062
+ //#region security
1063
+ /**
1064
+ * Removes all user and owner password security for a PDF document. Also disables content
1065
+ * encryption.
1066
+ * If content is encrypted at 128 bit, copy and paste of content, annotations and form editing may be disabled.
1067
+ */
1068
+ public async removePasswordsAndEncryption(): Promise<void> {
1069
+ return this.internal_removePasswordsAndEncryption()
1070
+ }
1071
+
1072
+ /**
1073
+ * Sets the user password and enables 128Bit encryption of PDF content.
1074
+ * A user password is a password that each user must enter to open or print the PDF document.
1075
+ */
1076
+ public async setUserPassword(userPassword: string): Promise<void> {
1077
+ return z.function()
1078
+ .args(z.string({description: "userPassword: string"}))
1079
+ .returns(z.promise(z.void()))
1080
+ .implement(this.internal_setUserPassword.bind(this))
1081
+ (userPassword);
1082
+ }
1083
+
1084
+ /**
1085
+ * Sets the owner password and enables 128Bit encryption of PDF content. An owner password is one used to
1086
+ * enable and disable all other security settings. <para>OwnerPassword must be set to a non-empty string
1087
+ * value for {@link PdfPermission.AllowAccessibilityExtractContent} , {@link PdfPermission.AllowAnnotations} ,
1088
+ * {@link PdfPermission.AllowFillForms}, {@link PdfPermission.AllowPrint}, {@link PdfPermission.AllowModify} to be
1089
+ * restricted.
1090
+ */
1091
+ public async setOwnerPassword(ownerPassword: string): Promise<void> {
1092
+ return z.function()
1093
+ .args(z.string({description: "ownerPassword: string"}))
1094
+ .returns(z.promise(z.void()))
1095
+ .implement(this.internal_setOwnerPassword.bind(this))
1096
+ (ownerPassword);
1097
+ }
1098
+
1099
+ /**
1100
+ * Sets the permissions of this PdfDocument
1101
+ * @param permissions see {@link PdfPermission}
1102
+ */
1103
+ public async setPermission(permissions: PdfPermission): Promise<void> {
1104
+ return z.function()
1105
+ .args(pdfPermissionSchema)
1106
+ .returns(z.promise(z.void()))
1107
+ .implement(this.internal_setPermission.bind(this))
1108
+ (permissions);
1109
+ }
1110
+
1111
+ /**
1112
+ * Gets the current permissions of this PdfDocument
1113
+ * @return {@link PdfPermission}
1114
+ */
1115
+ public async getPermission(): Promise<PdfPermission> {
1116
+ return this.internal_getPermission()
1117
+ }
1118
+
1119
+ /**
1120
+ * Makes this PDF document read only such that: Content is encrypted at 128 bit. Copy and paste of
1121
+ * content is disallowed. Annotations and form editing are disabled.
1122
+ * @param ownerPassword The owner password for the PDF. A string for owner password is required to enable PDF encryption and
1123
+ * all document security options.
1124
+ */
1125
+ public async makePdfDocumentReadOnly(ownerPassword: string): Promise<void> {
1126
+ return z.function()
1127
+ .args(z.string({description: "ownerPassword: string"}))
1128
+ .returns(z.promise(z.void()))
1129
+ .implement(this.internal_makePdfDocumentReadOnly.bind(this))
1130
+ (ownerPassword);
1131
+ }
1132
+
1133
+ //#endregion
1134
+
1135
+ //#region close
1136
+ /**
1137
+ * Dispose this PdfDocument object (clean up the resource)
1138
+ * This is necessary to free the memory used by PdfDocument. See {@link cleanUp}
1139
+ * Once this method was called this PdfDocument object no longer usable.
1140
+ */
1141
+ public async close() {
1142
+ return this.internal_close()
1143
+ }
1144
+
1145
+ //#endregion
1146
+
1147
+ //#region ALL_INTERNAL_STUFF
1148
+ /**
1149
+ * Internal PDF document ID
1150
+ * @private
1151
+ */
1152
+ private pdfDocumentId?: string | undefined;
1153
+ /**
1154
+ * @private
1155
+ */
1156
+ private readonly promiseDocumentId?: Promise<string> | undefined;
1157
+ /**
1158
+ * @private
1159
+ */
1160
+ private pdfPassword?: PdfPassword | undefined;
1161
+
1162
+ /**
1163
+ * Create a PdfDocument object from a {@link PdfInput}
1164
+ * For more specific way to create/open PdfDocument see {@link fromUrl} {@link fromZip} {@link fromHtml} {@link fromImage} {@link open}
1165
+ *
1166
+ * @param pdfInput see {@link PdfInput} (required) (pdfInput is {@link PdfFilePath} or {@link Buffer})
1167
+ * @param password a password to open the PDF required if PDF file was private.
1168
+ * @param trackChanges Optionally track changes to the document (for use with incremental saves)
1169
+ */
1170
+ constructor(pdfInput?: PdfInput | undefined, password?: PdfPassword | undefined, trackChanges?: ChangeTrackingModes | undefined) {
1171
+ if (pdfInput) {
1172
+ this.pdfDocumentId = undefined;
1173
+ const input = separatePdfInput(pdfInput);
1174
+ switch (input.type) {
1175
+ case "htmlFile":
1176
+ this.promiseDocumentId = renderHtmlFileToPdf(input.htmlFile);
1177
+ break;
1178
+ case "htmlString":
1179
+ this.promiseDocumentId = renderHtmlToPdf(input.htmlString);
1180
+ break;
1181
+ case "zipFile":
1182
+ this.promiseDocumentId = renderHtmlZipToPdf(input.zipFile);
1183
+ break;
1184
+ case "buffer":
1185
+ this.promiseDocumentId = openPdfFileBuffer(
1186
+ input.buffer,
1187
+ {userPassword: password?.userPassword, ownerPassword: password?.ownerPassword, trackChanges: trackChanges}
1188
+ );
1189
+ break;
1190
+ case "pdfFile":
1191
+ this.pdfPassword = password;
1192
+ this.promiseDocumentId = openPdfFileBuffer(
1193
+ fs.readFileSync(input.pdfFile),
1194
+ {userPassword: password?.userPassword, ownerPassword: password?.ownerPassword, trackChanges: trackChanges}
1195
+ );
1196
+ break;
1197
+ case "url":
1198
+ this.promiseDocumentId = renderUrlToPdf(input.url);
1199
+ break;
1200
+ case "pdfDocument":
1201
+ this.pdfDocumentId = input.pdfDocument.pdfDocumentId;
1202
+ this.promiseDocumentId =
1203
+ input.pdfDocument.promiseDocumentId;
1204
+ break;
1205
+ }
1206
+ if (this.pdfDocumentId) {
1207
+ Access.usedDocumentIds.add(this.pdfDocumentId);
1208
+ }
1209
+ this.promiseDocumentId?.then((id) =>
1210
+ Access.usedDocumentIds.add(id)
1211
+ );
1212
+ }
1213
+ }
1214
+
1215
+ /**
1216
+ * Dispose this PdfDocument object (clean up the resource)
1217
+ * This is necessary to free the memory used by PdfDocument. See {@link cleanUp}
1218
+ * Once this method was called this PdfDocument object no longer usable.
1219
+ */
1220
+ private async internal_close() {
1221
+ await disposePdf(await this.internal_getId());
1222
+ }
1223
+
1224
+ /**
1225
+ * @private
1226
+ */
1227
+ private async internal_getId(): Promise<string> {
1228
+ if (this.pdfDocumentId) {
1229
+ return Promise.resolve(this.pdfDocumentId) ;
1230
+ } else if (this.promiseDocumentId) {
1231
+ this.pdfDocumentId = await this.promiseDocumentId;
1232
+ return Promise.resolve(this.pdfDocumentId);
1233
+ } else {
1234
+ throw new Error("Cannot Get PdfDocumentId");
1235
+ }
1236
+ }
1237
+
1238
+ //#region io
1239
+
1240
+ /**
1241
+ * Open or Create a PdfDocument from a {@link PdfInput}
1242
+ * @param pdfInput {@link PdfInput}
1243
+ * @param options including {@link PdfPassword} {@link ChromePdfRenderOptions} {@link HttpLoginCredentials} mainHtmlFile
1244
+ */
1245
+ private static async internal_open(
1246
+ pdfInput: PdfInput,
1247
+ options?: {
1248
+ /**
1249
+ * required for open a private PDF file
1250
+ * @default undefined
1251
+ */
1252
+ password?: PdfPassword | undefined;
1253
+ /**
1254
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1255
+ * @default undefined
1256
+ */
1257
+ renderOptions?: ChromePdfRenderOptions | undefined;
1258
+ /**
1259
+ * Apply httpLoginCredentials if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1260
+ * @default undefined
1261
+ */
1262
+ httpLoginCredentials?: HttpLoginCredentials | undefined;
1263
+ /**
1264
+ * Apply mainHtmlFile if PdfInput is {@link ZipFilePath}
1265
+ * @default index.html
1266
+ */
1267
+ mainHtmlFile?: string | undefined;
1268
+ /**
1269
+ * Optionally track changes to the document (for use with incremental saves)
1270
+ * @default {@link ChangeTrackingModes.AutoChangeTracking}
1271
+ */
1272
+ trackChanges?: ChangeTrackingModes | undefined;
1273
+ // /**
1274
+ // * Apply baseUrl if
1275
+ // * The HTML base URL for which references to external CSS, Javascript and Image files will be relative.
1276
+ // * @default undefined
1277
+ // */
1278
+ // baseUrl ?: string | undefined; //not supported
1279
+ } | undefined
1280
+ ): Promise<PdfDocument> {
1281
+ if (pdfInput) {
1282
+ const input = separatePdfInput(pdfInput);
1283
+ switch (input.type) {
1284
+ case "htmlFile":
1285
+ const newHtmlFilePdf = new PdfDocument();
1286
+ newHtmlFilePdf.pdfDocumentId = await renderHtmlFileToPdf(
1287
+ input.htmlFile,
1288
+ options?.renderOptions
1289
+ );
1290
+ return newHtmlFilePdf;
1291
+ case "htmlString":
1292
+ const newHtmlStringPdf = new PdfDocument();
1293
+ newHtmlStringPdf.pdfDocumentId = await renderHtmlToPdf(
1294
+ input.htmlString,
1295
+ options?.renderOptions
1296
+ );
1297
+ return newHtmlStringPdf;
1298
+ case "zipFile":
1299
+ const newZipFilePdf = new PdfDocument();
1300
+ newZipFilePdf.pdfDocumentId = await renderHtmlZipToPdf(
1301
+ input.zipFile,
1302
+ options?.mainHtmlFile,
1303
+ options?.renderOptions
1304
+ );
1305
+ return newZipFilePdf;
1306
+ case "buffer":
1307
+ const newBufferPdf = new PdfDocument(
1308
+ undefined,
1309
+ options?.password,
1310
+ options?.trackChanges
1311
+ );
1312
+ newBufferPdf.pdfDocumentId = await openPdfFileBuffer(
1313
+ input.buffer,{
1314
+ userPassword: options?.password?.userPassword,
1315
+ ownerPassword: options?.password?.ownerPassword,
1316
+ trackChanges: options?.trackChanges
1317
+ }
1318
+ );
1319
+ return newBufferPdf;
1320
+ case "pdfFile":
1321
+ const newPdfFilePdf = new PdfDocument(
1322
+ undefined,
1323
+ options?.password
1324
+ );
1325
+ newPdfFilePdf.pdfDocumentId = await openPdfFileBuffer(
1326
+ fs.readFileSync(input.pdfFile),
1327
+ {
1328
+ userPassword: options?.password?.userPassword,
1329
+ ownerPassword: options?.password?.ownerPassword,
1330
+ trackChanges: options?.trackChanges
1331
+ }
1332
+ );
1333
+
1334
+ return newPdfFilePdf;
1335
+ case "url":
1336
+ const newUrlPdf = new PdfDocument();
1337
+ newUrlPdf.pdfDocumentId = await renderUrlToPdf(input.url, {
1338
+ renderOptions: options?.renderOptions,
1339
+ httpLoginCredentials: options?.httpLoginCredentials,
1340
+ });
1341
+ return newUrlPdf;
1342
+ case "pdfDocument":
1343
+ return Promise.resolve(input.pdfDocument);
1344
+ }
1345
+ }
1346
+ throw new Error(`cannot create PdfDocument object from ${pdfInput}`);
1347
+ }
1348
+
1349
+ /**
1350
+ * Open a PdfDocument from .pdf file
1351
+ * @param pdfFilePath A path to .pdf file
1352
+ * @param Optionally track changes to the document (for use with incremental saves)
1353
+ */
1354
+ private static async internal_fromFile(
1355
+ pdfFilePath: string,
1356
+ trackChanges?: ChangeTrackingModes | undefined
1357
+ ): Promise<PdfDocument> {
1358
+ return this.internal_open(pdfFilePath, {trackChanges: trackChanges});
1359
+ }
1360
+
1361
+ /**
1362
+ * Create a PdfDocument from an Url
1363
+ * @param url A website Url
1364
+ * @param options including {@link ChromePdfRenderOptions}
1365
+ */
1366
+ private static async internal_fromUrl(
1367
+ url: URL | string,
1368
+ options?: {
1369
+ /**
1370
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1371
+ * @default undefined
1372
+ */
1373
+ renderOptions?: ChromePdfRenderOptions | undefined;
1374
+ } | undefined
1375
+ ): Promise<PdfDocument> {
1376
+ return this.internal_open(url, options);
1377
+ }
1378
+
1379
+ /**
1380
+ * Creates a PDF file from a local Zip file, and returns it as a {@link PdfDocument}.
1381
+ * IronPDF is a W3C standards compliant HTML rendering based on Google's Chromium browser.
1382
+ * If your output PDF does not look as expected:
1383
+ *
1384
+ * - Validate your HTML file using https://validator.w3.org/ &amp; CSS https://jigsaw.w3.org/css-validator/
1385
+ *
1386
+ * - To debug HTML, view the file in Chrome web browser's print preview which will work almost exactly as IronPDF.
1387
+ *
1388
+ * - Read our detailed documentation on pixel perfect HTML to PDF: https://ironpdf.com/tutorials/pixel-perfect-html-to-pdf/
1389
+ *
1390
+ * @param zipFilePath Path to a Zip to be rendered as a PDF.
1391
+ * @param options including {@link ChromePdfRenderOptions} and `mainHtmlFile` a main .html file default: `index.html`
1392
+ */
1393
+ private static async internal_fromZip(
1394
+ zipFilePath: string,
1395
+ options?: {
1396
+ /**
1397
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1398
+ * @default undefined
1399
+ */
1400
+ renderOptions?: ChromePdfRenderOptions | undefined;
1401
+ /**
1402
+ * a main .html file default: `index.html`
1403
+ */
1404
+ mainHtmlFile?: string | undefined;
1405
+ } | undefined
1406
+ ): Promise<PdfDocument> {
1407
+ return this.internal_open(zipFilePath, options);
1408
+ }
1409
+
1410
+ /**
1411
+ * Creates a PDF file from a Html string, and returns it as an {@link PdfDocument} object which can be edited and saved to disk or served on a website.
1412
+ * @param htmlStringOrHtmlFilePath The Html to be rendered as a PDF.
1413
+ * @param options including {@link ChromePdfRenderOptions}
1414
+ */
1415
+ private static async internal_fromHtml(
1416
+ htmlStringOrHtmlFilePath: string,
1417
+ options?: {
1418
+ /**
1419
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1420
+ * @default undefined
1421
+ */
1422
+ renderOptions?: ChromePdfRenderOptions | undefined;
1423
+ } | undefined
1424
+ ): Promise<PdfDocument> {
1425
+ return this.internal_open(htmlStringOrHtmlFilePath, options);
1426
+ }
1427
+
1428
+ /**
1429
+ * Converts multiple image files to a PDF document. Each image creates 1 page which matches the image
1430
+ * dimensions. The default PaperSize is A4. You can set it via ImageToPdfConverter.PaperSize.
1431
+ * Note: Imaging.ImageBehavior.CropPage will set PaperSize equal to ImageSize.
1432
+ * @param images The image file path name(s) or {@link ImageBuffer} object(s)
1433
+ * @param options including {@link ImageToPdfOptions}
1434
+ */
1435
+ private static async internal_fromImage(
1436
+ images: ImageFilePath | ImageFilePath[] | ImageBuffer | ImageBuffer[],
1437
+ options?: {
1438
+ /**
1439
+ * Apply renderOptions if PdfInput is a {@link HtmlString} or {@link HtmlFilePath} or {@link ZipFilePath} or {@link Url}}
1440
+ * @default undefined
1441
+ */
1442
+ imageToPdfOptions?: ImageToPdfOptions | undefined;
1443
+ } | undefined
1444
+ ): Promise<PdfDocument> {
1445
+ let temp: Promise<string>;
1446
+
1447
+ if (Array.isArray(images)) {
1448
+ // const imageArray = images as Array<any>;
1449
+ if(images[0]){
1450
+ const t = separateImageBufferOrImagePathInput(images[0]);
1451
+
1452
+ switch (t.type) {
1453
+ case "imageBuffer":
1454
+ temp = renderImagesBufferToPdf(
1455
+ images as Buffer[],
1456
+ options?.imageToPdfOptions
1457
+ );
1458
+ break;
1459
+ case "imageFilePath":
1460
+ temp = renderImagesFilesToPdf(
1461
+ images as string[],
1462
+ options?.imageToPdfOptions
1463
+ );
1464
+ break;
1465
+ }
1466
+ }else{
1467
+ throw new Error("imageToPdf input Array is Empty");
1468
+ }
1469
+ } else {
1470
+ const image = separateImageBufferOrImagePathInput(images);
1471
+ switch (image.type) {
1472
+ case "imageBuffer":
1473
+ temp = renderImagesBufferToPdf(
1474
+ [image.imageBuffer],
1475
+ options?.imageToPdfOptions
1476
+ );
1477
+ break;
1478
+ case "imageFilePath":
1479
+ temp = renderImagesFilesToPdf(
1480
+ [image.imageFilePath],
1481
+ options?.imageToPdfOptions
1482
+ );
1483
+ break;
1484
+ }
1485
+ }
1486
+
1487
+ if (!temp) {
1488
+ throw new Error(`cannot read image: ${images}`);
1489
+ }
1490
+
1491
+ const newUrlPdf = new PdfDocument();
1492
+ newUrlPdf.pdfDocumentId = await temp;
1493
+ return newUrlPdf;
1494
+ }
1495
+
1496
+ /**
1497
+ * Static method that joins (concatenates) multiple PDF documents together into one compiled PDF document.
1498
+ * If the PDF contains form fields the form field in the resulting PDF's name will be appended with '_{index}' e.g. 'Name' will be 'Name_0'
1499
+ * @param pdfs array of PDF
1500
+ */
1501
+ private static async internal_mergePdf(pdfs: PdfInput[]): Promise<PdfDocument> {
1502
+ const ids = await Promise.all(
1503
+ pdfs.map(async (x) => (await PdfDocument.open(x)).internal_getId())
1504
+ );
1505
+ const newDocId = mergePdfs(ids);
1506
+ const newUrlPdf = new PdfDocument();
1507
+ newUrlPdf.pdfDocumentId = await newDocId;
1508
+ return newUrlPdf;
1509
+ }
1510
+
1511
+ /**
1512
+ * Saves the PdfDocument to a file.
1513
+ * @param filePath Target file path
1514
+ * @param saveOptions see {@link SaveOptions}
1515
+ */
1516
+ private async internal_saveAs(filePath: string, saveOptions?: SaveOptions | undefined): Promise<void> {
1517
+ return this.internal_saveAsBuffer(saveOptions).then((pdfFileBuffer) => {
1518
+ fs.writeFile(filePath, pdfFileBuffer, "binary", (err) => {
1519
+ if (err) throw err;
1520
+ });
1521
+ });
1522
+ }
1523
+
1524
+ /**
1525
+ * Saves the PdfDocument to a binary (Buffer)
1526
+ * @param saveOptions see {@link SaveOptions}
1527
+ */
1528
+ private async internal_saveAsBuffer(saveOptions?: SaveOptions | undefined): Promise<Buffer> {
1529
+ return getBinaryData(await this.internal_getId(), saveOptions);
1530
+ }
1531
+
1532
+ //#endregion
1533
+
1534
+ //#region compress
1535
+ /**
1536
+ * Compress existing PDF images using JPG encoding and the specified settings
1537
+ * @param imageQuality Quality (1 - 100) to use during compression
1538
+ * @param scaleToVisibleSize Scale down the image resolution according to its visible size in the PDF document
1539
+ */
1540
+ private async internal_compressSize(
1541
+ imageQuality: number,
1542
+ scaleToVisibleSize = false
1543
+ ): Promise<void> {
1544
+ if (imageQuality < 1 || imageQuality > 100)
1545
+ throw new Error(
1546
+ `Invalid quality specifier (${imageQuality}) when compressing images. Quality must be between 1 and 100.`
1547
+ );
1548
+ return await compressImage(
1549
+ await this.internal_getId(),
1550
+ imageQuality,
1551
+ scaleToVisibleSize
1552
+ );
1553
+ }
1554
+
1555
+ /**
1556
+ * Remove document struct tree information which describes the logical layout of the document.
1557
+ * Removing the "structure tree" can significantly reduce the disk space used by the document.
1558
+ * Removing the "structure tree" of a complicated document can negatively impact text selection.
1559
+ */
1560
+ private async internal_compressStructTree(): Promise<void> {
1561
+ return await compressStructTree(await this.internal_getId());
1562
+ }
1563
+
1564
+ /**
1565
+ * Compress the PDF and return the result as a Buffer (byte array).
1566
+ * Uses QPdf compression which can significantly reduce file size.
1567
+ * @param imageQuality Optional JPEG quality (1-100) for image compression. If omitted, default compression is applied.
1568
+ */
1569
+ private async internal_compressPdfToBytes(
1570
+ imageQuality?: number
1571
+ ): Promise<Buffer> {
1572
+ if (imageQuality !== undefined && (imageQuality < 1 || imageQuality > 100))
1573
+ throw new Error(
1574
+ `Invalid quality specifier (${imageQuality}) when compressing PDF. Quality must be between 1 and 100.`
1575
+ );
1576
+ return await compressInMemory(
1577
+ await this.internal_getId(),
1578
+ imageQuality
1579
+ );
1580
+ }
1581
+
1582
+ /**
1583
+ * Compress the PDF and return the result as a Readable stream.
1584
+ * Uses QPdf compression which can significantly reduce file size.
1585
+ * Useful for piping directly to file streams or HTTP responses without buffering the entire PDF in memory.
1586
+ * @param imageQuality Optional JPEG quality (1-100) for image compression. If omitted, default compression is applied.
1587
+ */
1588
+ private async internal_compressPdfToStream(
1589
+ imageQuality?: number
1590
+ ): Promise<Readable> {
1591
+ if (imageQuality !== undefined && (imageQuality < 1 || imageQuality > 100))
1592
+ throw new Error(
1593
+ `Invalid quality specifier (${imageQuality}) when compressing PDF. Quality must be between 1 and 100.`
1594
+ );
1595
+ return await compressInMemoryStream(
1596
+ await this.internal_getId(),
1597
+ imageQuality
1598
+ );
1599
+ }
1600
+
1601
+ /**
1602
+ * Compress the PDF and save the result directly to a file.
1603
+ * Uses QPdf compression which can significantly reduce file size.
1604
+ * @param filePath The output file path to save the compressed PDF.
1605
+ * @param imageQuality Optional JPEG quality (1-100) for image compression. If omitted, default compression is applied.
1606
+ */
1607
+ private async internal_compressAndSaveAs(
1608
+ filePath: string,
1609
+ imageQuality?: number
1610
+ ): Promise<void> {
1611
+ if (imageQuality !== undefined && (imageQuality < 1 || imageQuality > 100))
1612
+ throw new Error(
1613
+ `Invalid quality specifier (${imageQuality}) when compressing PDF. Quality must be between 1 and 100.`
1614
+ );
1615
+ return await compressAndSaveAs(
1616
+ await this.internal_getId(),
1617
+ filePath,
1618
+ imageQuality
1619
+ );
1620
+ }
1621
+
1622
+ //#endregion
1623
+
1624
+ //#region page
1625
+ /**
1626
+ * Gets information of all pages in the PdfDocument
1627
+ */
1628
+ private async internal_getPagesInfo(): Promise<PageInfo[]> {
1629
+ return await getPageInfo(await this.internal_getId());
1630
+ }
1631
+
1632
+ /**
1633
+ * Gets the number of pages in the PdfDocument.
1634
+ */
1635
+ private async internal_getPageCount(): Promise<number> {
1636
+ return (await this.internal_getPagesInfo()).length;
1637
+ }
1638
+
1639
+ /**
1640
+ * Set the page orientation.
1641
+ * @param pageRotation see {@link PageRotation}
1642
+ * @param options including {@link PdfPageSelection}
1643
+ */
1644
+ private async internal_setRotation(
1645
+ pageRotation: PageRotation,
1646
+ options?: {
1647
+ /**
1648
+ * @default "all"
1649
+ */
1650
+ pdfPageSelection?: PdfPageSelection | undefined;
1651
+ } | undefined
1652
+ ) {
1653
+ return await setPageRotation(await this.internal_getId(), pageRotation, options);
1654
+ }
1655
+
1656
+ /**
1657
+ * Resize a page to the specified dimensions
1658
+ * @param newSize {@link PdfPaperSize}
1659
+ * @param options including {@link PdfPageSelection}
1660
+ */
1661
+ private async internal_resize(
1662
+ newSize: PdfPaperSize,
1663
+ options?: {
1664
+ /**
1665
+ * @default "all"
1666
+ */
1667
+ pdfPageSelection?: PdfPageSelection | undefined;
1668
+ } | undefined
1669
+ ): Promise<void> {
1670
+ return await resizePage(await this.internal_getId(), newSize, options);
1671
+ }
1672
+
1673
+ /**
1674
+ * Adds another PDF to the beginning of the current PdfDocument
1675
+ * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
1676
+ * @param fromPdfDocument PdfDocument to prepend
1677
+ */
1678
+ private async internal_prependAnotherPdf(
1679
+ fromPdfDocument: PdfDocument
1680
+ ): Promise<void> {
1681
+ await this.internal_insertPagesFromAnotherPdf(fromPdfDocument, 0);
1682
+ }
1683
+
1684
+ /**
1685
+ * Appends another PDF to the end of the current <see cref="PdfDocument"/>
1686
+ * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
1687
+ * @param fromPdfDocument PdfDocument to Append
1688
+ */
1689
+ private async internal_appendAnotherPdf(fromPdfDocument: PdfDocument): Promise<void> {
1690
+ await this.internal_insertPagesFromAnotherPdf(
1691
+ fromPdfDocument,
1692
+ (await this.internal_getPageCount())
1693
+ );
1694
+ }
1695
+
1696
+ /**
1697
+ * Inserts another PDF into the current PdfDocument, starting at a given Page Index.
1698
+ * If AnotherPdfFile contains form fields, those fields will be appended with '_' in the resulting PDF. e.g. 'Name' will be 'Name_'
1699
+ * @param fromPdfDocument Another PdfDocument
1700
+ * @param insertAtPageIndex Index at which to insert the new content. Note: Page 1 has index 0...
1701
+ */
1702
+ private async internal_insertPagesFromAnotherPdf(
1703
+ fromPdfDocument: PdfDocument,
1704
+ insertAtPageIndex: number
1705
+ ): Promise<void> {
1706
+ await insertPdf(
1707
+ await this.internal_getId(),
1708
+ await fromPdfDocument.internal_getId(),
1709
+ insertAtPageIndex
1710
+ );
1711
+ }
1712
+
1713
+ /**
1714
+ * Removes a range of pages from the PDF
1715
+ * @param pages pages to remove
1716
+ */
1717
+ private async internal_removePage(pages: PdfPageSelection): Promise<void> {
1718
+ await removePage(await this.internal_getId(), {PdfPageSelection: pages});
1719
+ }
1720
+
1721
+ /**
1722
+ * Creates a new PDF by copying a range of pages from this {@link PdfDocument}.
1723
+ * @param pages pages to copy (default "all")
1724
+ */
1725
+ private async internal_duplicate(
1726
+ pages: PdfPageSelection = "all"
1727
+ ): Promise<PdfDocument> {
1728
+ const newPdf = new PdfDocument();
1729
+ newPdf.pdfDocumentId = await duplicate(await this.internal_getId(), {
1730
+ PdfPageSelection: pages,
1731
+ });
1732
+ return newPdf;
1733
+ }
1734
+
1735
+ //#endregion
1736
+
1737
+ //#region image
1738
+ /**
1739
+ * Finds all embedded Images from within a specified pages in the PDF and returns them as Buffer
1740
+ * @param options including {@link PdfPageSelection}
1741
+ */
1742
+ private async internal_extractRawImages(options?: {
1743
+ /**
1744
+ * @default "all"
1745
+ */
1746
+ fromPages?: PdfPageSelection | undefined;
1747
+ } | undefined): Promise<Buffer[]> {
1748
+ return extractRawImages(
1749
+ await this.internal_getId(),
1750
+ options?.fromPages ?? "all"
1751
+ );
1752
+ }
1753
+
1754
+ /**
1755
+ * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
1756
+ * page.
1757
+ *
1758
+ * @param options including {@link PdfPageSelection} {@link ImageType}
1759
+ *
1760
+ * @return array of images as Buffer[]
1761
+ */
1762
+ private async internal_rasterizeToImageBuffers(options?: {
1763
+ /**
1764
+ * @default "all"
1765
+ */
1766
+ fromPages?: PdfPageSelection | undefined;
1767
+ /**
1768
+ * @default {@link ImageType.PNG}
1769
+ */
1770
+ imageType?: ImageType | undefined;
1771
+ }): Promise<Buffer[]> {
1772
+ const images = await rasterizeToImageBuffers(
1773
+ await this.internal_getId(),
1774
+ options?.fromPages ?? "all"
1775
+ );
1776
+ const jimpImageType: "image/bmp" | "image/png" | "image/jpeg" = (() => {
1777
+ switch (options?.imageType) {
1778
+ case ImageType.BMP:
1779
+ return Jimp.MIME_BMP;
1780
+ case ImageType.PNG:
1781
+ return Jimp.MIME_PNG;
1782
+ case ImageType.JPG:
1783
+ return Jimp.MIME_JPEG;
1784
+ default:
1785
+ return Jimp.MIME_PNG;
1786
+ }
1787
+ })();
1788
+ return Promise.all(
1789
+ images.map(async (imageBuffer) => {
1790
+ //convert output type
1791
+ const jimp = await Jimp.read(imageBuffer);
1792
+ return await jimp.getBufferAsync(jimpImageType);
1793
+ })
1794
+ );
1795
+ }
1796
+
1797
+ /**
1798
+ * Renders the PDF and exports image Files in convenient formats. 1 image file is created for each
1799
+ * page. Running number will append output file path.
1800
+ *
1801
+ * @param filePath output file path.
1802
+ * @param options including {@link PdfPageSelection} {@link ImageType}
1803
+ *
1804
+ * @return array of images file name as string[]
1805
+ */
1806
+ private async internal_rasterizeToImageFiles(
1807
+ filePath: string,
1808
+ options?: {
1809
+ /**
1810
+ * @default "all"
1811
+ */
1812
+ fromPages?: PdfPageSelection | undefined;
1813
+ /**
1814
+ * @default {@link ImageType.PNG}
1815
+ */
1816
+ type?: ImageType | undefined;
1817
+ } | undefined
1818
+ ): Promise<string[]> {
1819
+ const images = await rasterizeToImageBuffers(
1820
+ await this.internal_getId(),
1821
+ options?.fromPages ?? "all"
1822
+ );
1823
+
1824
+ const promises = images.map(async (imageBuffer, index) => {
1825
+ const outputFileName = getFileName(filePath,index.toString(),getImageExtType(options?.type),"image");
1826
+ await Jimp.read(imageBuffer).then((value) => {
1827
+ return value.write(outputFileName);
1828
+ });
1829
+ return outputFileName;
1830
+ });
1831
+
1832
+ return await Promise.all(promises);
1833
+ }
1834
+
1835
+ //#endregion
1836
+
1837
+ //#region text
1838
+ /**
1839
+ * Replace the specified old text with new text on a given page
1840
+ * @param oldText Old text to remove
1841
+ * @param newText New text to add
1842
+ * @param onPages Page index to search for old text to replace (default "all")
1843
+ */
1844
+ private async internal_replaceText(
1845
+ oldText: string,
1846
+ newText: string,
1847
+ onPages?: PdfPageSelection | undefined
1848
+ ): Promise<void> {
1849
+ return replaceText(await this.internal_getId(), oldText, newText, onPages);
1850
+ }
1851
+
1852
+ private async internal_extractText(
1853
+ onPages?: PdfPageSelection | undefined
1854
+ ): Promise<string> {
1855
+ return extractAllText(await this.internal_getId(), onPages);
1856
+ }
1857
+
1858
+ //#endregion
1859
+
1860
+ //#region pdfA
1861
+ /**
1862
+ * Convert the current document into the specified PDF-A standard format
1863
+ * @param pdfaVersion The PDF/A version to convert to
1864
+ * @param customICC (Optional) Custom color profile file path
1865
+ */
1866
+ private async internal_convertToPdfA(pdfaVersion: PdfAVersions, customICC?: string | undefined): Promise<void> {
1867
+ return await toPdfA(await this.internal_getId(), pdfaVersion, customICC);
1868
+ }
1869
+
1870
+ /**
1871
+ * Convert the current document into the specified PDF/UA standard format
1872
+ */
1873
+ private async internal_convertToPdfUA(naturalLanguages: NaturalLanguages, pdfUaVersion: PdfUAVersions = PdfUAVersions.PdfUA1): Promise<void> {
1874
+ return await toPdfUA(await this.internal_getId(), naturalLanguages, pdfUaVersion);
1875
+ }
1876
+
1877
+ //#endregion
1878
+
1879
+ //#region metadata
1880
+ /**
1881
+ * Gets a Map<string, string> of metadata properties
1882
+ */
1883
+ private async internal_getMetadata(): Promise<Map<string, string>> {
1884
+ return getMetadataDict(await this.internal_getId());
1885
+ }
1886
+
1887
+ /**
1888
+ * Add or Update a single metadata property
1889
+ * @param key
1890
+ * @param value
1891
+ */
1892
+ private async internal_addOrUpdateMetadata(
1893
+ key: string,
1894
+ value: string
1895
+ ): Promise<void> {
1896
+ return setMetadata(await this.internal_getId(), key, value);
1897
+ }
1898
+
1899
+ /**
1900
+ * Remove a single metadata property
1901
+ * @param key
1902
+ */
1903
+ private async internal_removeMetadata(key: string): Promise<void> {
1904
+ return removeMetadata(await this.internal_getId(), key);
1905
+ }
1906
+
1907
+
1908
+ /**
1909
+ * Sets a whole metadata properties Map<string, string> (override all the metadata property)
1910
+ * @param newMetadataDictionary new metadata properties Map<string, string>
1911
+ */
1912
+ private async internal_overrideMetadata(
1913
+ newMetadataDictionary: Map<string, string>
1914
+ ): Promise<void> {
1915
+ return setMetadataDict(await this.internal_getId(), newMetadataDictionary);
1916
+ }
1917
+
1918
+ //#endregion
1919
+
1920
+ //#region signing
1921
+ /**
1922
+ * Sign PDF with digital signature certificate.
1923
+ * Note that the PDF will not be fully signed until Saved
1924
+ * using {@link saveAs} or {@link saveAsBuffer}
1925
+ *
1926
+ * Multiple certificates may be used.
1927
+ * @param signature see {@link DigitalSignature}
1928
+ */
1929
+ private async internal_signDigitalSignature(signature: DigitalSignature) {
1930
+ return await signPdf(await this.internal_getId(), signature);
1931
+ }
1932
+
1933
+ /**
1934
+ * Check if PdfDocument was signed or not
1935
+ */
1936
+ private async internal_isSigned(): Promise<boolean> {
1937
+ const signatureCount = await getSignatureCount(await this.internal_getId());
1938
+ return signatureCount > 0;
1939
+ }
1940
+
1941
+ /**
1942
+ * Count the number signature that signed to this PdfDocument
1943
+ */
1944
+ private async internal_signatureCount(): Promise<number> {
1945
+ return await getSignatureCount(await this.internal_getId());
1946
+ }
1947
+
1948
+ /**
1949
+ * Get all verified digital signatures from this PdfDocument.
1950
+ */
1951
+ private async internal_getVerifiedSignatures(): Promise<VerifiedSignature[]> {
1952
+ return await getVerifiedSignatures(await this.internal_getId());
1953
+ }
1954
+
1955
+ //#endregion
1956
+
1957
+ //#region header/footer (affix)
1958
+ /**
1959
+ * Apply page header on top of an existing Pdf.
1960
+ * @param header {@link TextAffix}
1961
+ * @param toPages {@link PdfPageSelection}
1962
+ */
1963
+ private async internal_addTextHeader(
1964
+ header: TextAffix,
1965
+ toPages?: PdfPageSelection | undefined
1966
+ ): Promise<void> {
1967
+ await addTextAffix(await this.internal_getId(), toPages, header, true);
1968
+ }
1969
+
1970
+ /**
1971
+ * Apply page footer on top of an existing Pdf.
1972
+ * @param footer {@link TextAffix}
1973
+ * @param toPages {@link PdfPageSelection}
1974
+ */
1975
+ private async internal_addTextFooter(
1976
+ footer: TextAffix,
1977
+ toPages?: PdfPageSelection | undefined
1978
+ ): Promise<void> {
1979
+ await addTextAffix(await this.internal_getId(), toPages, footer, false);
1980
+ }
1981
+
1982
+ /**
1983
+ * Apply HTML header on top of an existing Pdf.
1984
+ * @param header {@link HtmlAffix}
1985
+ * @param toPages {@link PdfPageSelection}
1986
+ */
1987
+ private async internal_addHtmlHeader(
1988
+ header: HtmlAffix,
1989
+ toPages?: PdfPageSelection | undefined
1990
+ ): Promise<void> {
1991
+ await addHtmlAffix(await this.internal_getId(), toPages, header, true);
1992
+ }
1993
+
1994
+ /**
1995
+ * Apply HTML footer on top of an existing Pdf.
1996
+ * @param footer {@link HtmlAffix}
1997
+ * @param toPages {@link PdfPageSelection}
1998
+ */
1999
+ private async internal_addHtmlFooter(
2000
+ footer: HtmlAffix,
2001
+ toPages?: PdfPageSelection | undefined
2002
+ ): Promise<void> {
2003
+ await addHtmlAffix(await this.internal_getId(), toPages, footer, false);
2004
+ }
2005
+
2006
+ //#endregion
2007
+
2008
+ //#region stamp
2009
+ /**
2010
+ * Edits the PDF by applying the HTML's rendered to only selected page(s).
2011
+ * @param htmlStringOrHtmlFilePath
2012
+ * @param options including {@link HtmlStampOptions} {@link PdfPageSelection}
2013
+ */
2014
+ private async internal_stampHtml(
2015
+ htmlStringOrHtmlFilePath: HtmlFilePath | HtmlString,
2016
+ options?: {
2017
+ htmlStampOptions?: HtmlStampOptions | undefined;
2018
+ toPages?: PdfPageSelection | undefined;
2019
+ } | undefined
2020
+ ) {
2021
+ const html =
2022
+ htmlStringOrHtmlFilePath.endsWith(".html") ||
2023
+ htmlStringOrHtmlFilePath.endsWith(".htm")
2024
+ ? fs.readFileSync(htmlStringOrHtmlFilePath).toString()
2025
+ : htmlStringOrHtmlFilePath;
2026
+
2027
+ await stampHtml(await this.internal_getId(), html, {
2028
+ password: this.pdfPassword,
2029
+ htmlStampOptions: options?.htmlStampOptions,
2030
+ pageSelection: options?.toPages,
2031
+ });
2032
+ }
2033
+
2034
+ /**
2035
+ * Edits the PDF by applying the image to only selected page(s).
2036
+ * @param image image file path or image buffer
2037
+ * @param options including {@link ImageStampOptions} {@link PdfPageSelection}
2038
+ */
2039
+ private async internal_stampImage(
2040
+ image: ImageFilePath | ImageBuffer,
2041
+ options?: {
2042
+ imageStampOptions?: ImageStampOptions | undefined;
2043
+ toPages?: PdfPageSelection | undefined;
2044
+ } | undefined
2045
+ ) {
2046
+ const imageBuffer =
2047
+ image instanceof Buffer ? image : fs.readFileSync(image);
2048
+
2049
+ await stampImage(await this.internal_getId(), imageBuffer, {
2050
+ password: this.pdfPassword,
2051
+ imageStampOptions: options?.imageStampOptions,
2052
+ pageSelection: options?.toPages,
2053
+ });
2054
+ }
2055
+
2056
+ /**
2057
+ * Edits the PDF by applying the text to only selected page(s).
2058
+ * @param text text to stamp
2059
+ * @param options including {@link TextStampOptions} {@link PdfPageSelection}
2060
+ */
2061
+ private async internal_stampText(
2062
+ text: string,
2063
+ options?: {
2064
+ textStampOptions?: TextStampOptions | undefined;
2065
+ toPages?: PdfPageSelection | undefined;
2066
+ } | undefined
2067
+ ) {
2068
+ await stampText(await this.internal_getId(), text, {
2069
+ password: this.pdfPassword,
2070
+ textStampOptions: options?.textStampOptions,
2071
+ pageSelection: options?.toPages,
2072
+ });
2073
+ }
2074
+
2075
+ /**
2076
+ * Edits the PDF by applying the barcode to only selected page(s).
2077
+ * @param barcodeValue barcode
2078
+ * @param options including {@link BarcodeType} {@link BarcodeStampOptions} {@link PdfPageSelection}
2079
+ */
2080
+ private async internal_stampBarcode(
2081
+ barcodeValue: string,
2082
+ options?: {
2083
+ barcodeEncoding: BarcodeType;
2084
+ barcodeStampOptions?: BarcodeStampOptions | undefined;
2085
+ toPages?: PdfPageSelection | undefined;
2086
+ } | undefined
2087
+ ) {
2088
+ await stampBarcode(
2089
+ await this.internal_getId(),
2090
+ barcodeValue,
2091
+ {
2092
+ password: this.pdfPassword,
2093
+ barcodeStampOptions: options?.barcodeStampOptions,
2094
+ pageSelection: options?.toPages,
2095
+ }
2096
+ );
2097
+ }
2098
+
2099
+ //#endregion
2100
+
2101
+ //#region background/foreground
2102
+ /**
2103
+ * Adds a background to each page of this PDF. The background is copied from a first page in the
2104
+ * backgroundPdf document.
2105
+ *
2106
+ * @param fromPdf background PDF document
2107
+ * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
2108
+ * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
2109
+ */
2110
+ private async internal_addBackgroundFromAnotherPdf(
2111
+ fromPdf: PdfDocument,
2112
+ sourcePageIndex = 0,
2113
+ applyToPages?: PdfPageSelection | undefined
2114
+ ): Promise<void> {
2115
+ return await addBackgroundForeground(
2116
+ await this.internal_getId(),
2117
+ await fromPdf.internal_getId(),
2118
+ sourcePageIndex,
2119
+ true,
2120
+ applyToPages
2121
+ );
2122
+ }
2123
+
2124
+ /**
2125
+ * Adds a foreground to each page of this PDF. The background is copied from a first page in the
2126
+ * backgroundPdf document.
2127
+ *
2128
+ * @param fromPdf foreground PDF document
2129
+ * @param sourcePageIndex Index (zero-based page number) of the page to copy from the Background/Foreground PDF. Default is 0.
2130
+ * @param applyToPages PageSelection to which the background/foreground will be added. Default is "all"
2131
+ */
2132
+ private async internal_addForegroundFromAnotherPdf(
2133
+ fromPdf: PdfDocument,
2134
+ sourcePageIndex = 0,
2135
+ applyToPages?: PdfPageSelection | undefined
2136
+ ): Promise<void> {
2137
+ return await addBackgroundForeground(
2138
+ await this.internal_getId(),
2139
+ await fromPdf.internal_getId(),
2140
+ sourcePageIndex,
2141
+ false,
2142
+ applyToPages
2143
+ );
2144
+ }
2145
+
2146
+ //#endregion
2147
+
2148
+ //#region security
2149
+ /**
2150
+ * Removes all user and owner password security for a PDF document. Also disables content
2151
+ * encryption.
2152
+ * If content is encrypted at 128 bit, copy and paste of content, annotations and form editing may be disabled.
2153
+ */
2154
+ private async internal_removePasswordsAndEncryption(): Promise<void> {
2155
+ await removePasswordsAndEncryption(await this.internal_getId());
2156
+ }
2157
+
2158
+ /**
2159
+ * Sets the user password and enables 128Bit encryption of PDF content.
2160
+ * A user password is a password that each user must enter to open or print the PDF document.
2161
+ */
2162
+ private async internal_setUserPassword(userPassword: string): Promise<void> {
2163
+ if (!this.pdfPassword)
2164
+ this.pdfPassword = {userPassword: userPassword};
2165
+ else this.pdfPassword.userPassword = userPassword;
2166
+ this.pdfDocumentId = await setUserPasswords(
2167
+ await this.internal_getId(),
2168
+ userPassword
2169
+ );
2170
+ }
2171
+
2172
+ /**
2173
+ * Sets the owner password and enables 128Bit encryption of PDF content. An owner password is one used to
2174
+ * enable and disable all other security settings. <para>OwnerPassword must be set to a non-empty string
2175
+ * value for {@link PdfPermission.AllowAccessibilityExtractContent} , {@link PdfPermission.AllowAnnotations} ,
2176
+ * {@link PdfPermission.AllowFillForms}, {@link PdfPermission.AllowPrint}, {@link PdfPermission.AllowModify} to be
2177
+ * restricted.
2178
+ */
2179
+ private async internal_setOwnerPassword(ownerPassword: string): Promise<void> {
2180
+ if (!this.pdfPassword)
2181
+ this.pdfPassword = {ownerPassword: ownerPassword};
2182
+ else this.pdfPassword.ownerPassword = ownerPassword;
2183
+ this.pdfDocumentId = await setOwnerPasswords(
2184
+ await this.internal_getId(),
2185
+ ownerPassword
2186
+ );
2187
+ }
2188
+
2189
+ /**
2190
+ * Sets the permissions of this PdfDocument
2191
+ * @param permissions see {@link PdfPermission}
2192
+ */
2193
+ private async internal_setPermission(permissions: PdfPermission): Promise<void> {
2194
+ this.pdfDocumentId = await setSecurity(await this.internal_getId(), permissions);
2195
+ }
2196
+
2197
+ /**
2198
+ * Gets the current permissions of this PdfDocument
2199
+ * @return {@link PdfPermission}
2200
+ */
2201
+ private async internal_getPermission(): Promise<PdfPermission> {
2202
+ return await getPermission(await this.internal_getId());
2203
+ }
2204
+
2205
+ /**
2206
+ * Makes this PDF document read only such that: Content is encrypted at 128 bit. Copy and paste of
2207
+ * content is disallowed. Annotations and form editing are disabled.
2208
+ * @param ownerPassword The owner password for the PDF. A string for owner password is required to enable PDF encryption and
2209
+ * all document security options.
2210
+ */
2211
+ private async internal_makePdfDocumentReadOnly(ownerPassword: string): Promise<void> {
2212
+ await this.internal_setOwnerPassword(ownerPassword);
2213
+ await this.internal_setPermission({
2214
+ AllowExtractContent: false,
2215
+ AllowAccessibilityExtractContent: false,
2216
+ AllowAnnotations: false,
2217
+ AllowModify: false,
2218
+ AllowAssembleDocument: false,
2219
+ AllowFillForms: false,
2220
+ });
2221
+ }
2222
+
2223
+ //#endregion
2224
+
2225
+ //#endregion
2226
+ }