-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathpdf.ts
More file actions
3252 lines (2810 loc) · 99.9 KB
/
pdf.ts
File metadata and controls
3252 lines (2810 loc) · 99.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* High-level PDF document API.
*
* Provides a user-friendly interface for loading, modifying, and saving PDFs.
* Wraps the low-level parsing and writing infrastructure.
*/
import { AnnotationFlattener } from "#src/annotations/flattener";
import type { FlattenAnnotationsOptions } from "#src/annotations/types";
import type { AddAttachmentOptions, AttachmentInfo } from "#src/attachments/types";
import { hasChanges } from "#src/document/change-collector";
import type { FlattenOptions } from "#src/document/forms/form-flattener";
import { isLinearizationDict } from "#src/document/linearization";
import { ObjectCopier } from "#src/document/object-copier";
import { ObjectRegistry } from "#src/document/object-registry";
import {
PDFExtGState,
PDFFormXObject,
PDFShading,
PDFShadingPattern,
PDFTilingPattern,
type AxialShadingOptions,
type ExtGStateOptions,
type FormXObjectOptions,
type ImagePatternOptions,
type LinearGradientOptions,
type RadialShadingOptions,
type ShadingPatternOptions,
type TilingPatternOptions,
} from "#src/drawing/resources/index";
import { serializeOperators } from "#src/drawing/serialize";
import type { EmbeddedFont, EmbedFontOptions } from "#src/fonts/embedded-font";
import { formatPdfDate, parsePdfDate } from "#src/helpers/format";
import { resolvePageSize } from "#src/helpers/page-size";
import { checkIncrementalSaveBlocker, type IncrementalSaveBlocker } from "#src/helpers/save-utils";
import { isJpeg, parseJpegHeader } from "#src/images/jpeg";
import { PDFImage } from "#src/images/pdf-image";
import { isPng, parsePng } from "#src/images/png";
import { Scanner } from "#src/io/scanner";
import * as LayerUtils from "#src/layers/index";
import type { FlattenLayersResult, LayerInfo } from "#src/layers/types";
import { PdfArray } from "#src/objects/pdf-array";
import { PdfBool } from "#src/objects/pdf-bool";
import { PdfDict } from "#src/objects/pdf-dict";
import { PdfName } from "#src/objects/pdf-name";
import { PdfNumber } from "#src/objects/pdf-number";
import type { PdfObject } from "#src/objects/pdf-object";
import { PdfRef } from "#src/objects/pdf-ref";
import { PdfStream } from "#src/objects/pdf-stream";
import { PdfString } from "#src/objects/pdf-string";
import { DocumentParser, type ParseOptions } from "#src/parser/document-parser";
import { XRefParser } from "#src/parser/xref-parser";
import { generateEncryption, reconstructEncryptDict } from "#src/security/encryption-generator";
import { PermissionDeniedError } from "#src/security/errors";
import { DEFAULT_PERMISSIONS, type Permissions } from "#src/security/permissions";
import type { StandardSecurityHandler } from "#src/security/standard-handler.ts";
import type { SignOptions, SignResult } from "#src/signatures/types";
import { layoutTable } from "#src/tables/layout";
import { normalizeTable } from "#src/tables/normalize";
import { renderTable } from "#src/tables/render";
import type { DrawTableOptions, DrawTableResult, TableDefinition } from "#src/tables/types";
import type { FindTextOptions, PageText, TextMatch } from "#src/text/types";
import { writeComplete, writeIncremental } from "#src/writer/pdf-writer";
import { randomBytes } from "@noble/ciphers/utils.js";
import { deflate } from "pako";
import { PDFAttachments } from "./pdf-attachments";
import { PDFCatalog } from "./pdf-catalog";
import { PDFContext, type DocumentInfo } from "./pdf-context";
import { PDFEmbeddedPage } from "./pdf-embedded-page";
import { PDFFonts } from "./pdf-fonts";
import { PDFForm } from "./pdf-form";
import { PDFPage } from "./pdf-page";
import { PDFPageTree } from "./pdf-page-tree";
import type {
AuthenticationResult,
EncryptionAlgorithmOption,
PendingSecurityState,
ProtectionOptions,
SecurityInfo,
} from "./pdf-security";
import { PDFSignature } from "./pdf-signature";
/**
* Options for loading a PDF.
*/
export interface LoadOptions extends ParseOptions {
// Inherits credentials, lenient from ParseOptions
}
/**
* Options for flattening all interactive content.
*/
export interface FlattenAllOptions {
/** Options for form field flattening */
form?: FlattenOptions;
/** Options for annotation flattening */
annotations?: FlattenAnnotationsOptions;
}
/**
* Result of flattening all interactive content.
*/
export interface FlattenAllResult {
/** Number of layers (OCGs) flattened */
layers: number;
/** Number of form fields flattened */
formFields: number;
/** Number of annotations flattened */
annotations: number;
}
/**
* Options for saving a PDF.
*/
export interface SaveOptions {
/** Save incrementally (append only). Default: false */
incremental?: boolean;
/** Use XRef stream instead of table. Default: matches original format */
useXRefStream?: boolean;
/**
* Subset embedded fonts to include only used glyphs.
*
* Reduces file size but takes additional processing time.
* Fonts used in form fields are never subsetted (users may type any character).
*
* @default false
*/
subsetFonts?: boolean;
/**
* Compress uncompressed streams with FlateDecode (default: true).
*
* When enabled, streams without a /Filter entry will be compressed
* before writing. Streams that already have filters (including image
* formats like DCTDecode/JPXDecode) are left unchanged.
*/
compressStreams?: boolean;
/**
* Minimum stream size in bytes to attempt compression (default: 512).
*
* Streams smaller than this threshold are written uncompressed.
* Deflate initialization has a fixed overhead that dominates for small
* payloads, and tiny streams rarely achieve meaningful compression.
*
* Set to 0 to compress all streams regardless of size.
*/
compressionThreshold?: number;
}
/**
* Options for adding a new page.
*/
export interface AddPageOptions {
/** Page width in points (default: 612 = US Letter) */
width?: number;
/** Page height in points (default: 792 = US Letter) */
height?: number;
/** Use a preset size */
size?: "letter" | "a4" | "legal";
/** Page orientation (default: "portrait") */
orientation?: "portrait" | "landscape";
/** Rotation in degrees (0, 90, 180, 270) */
rotate?: number;
/** Insert at index instead of appending */
insertAt?: number;
}
/**
* Options for copying pages from another document.
*/
export interface CopyPagesOptions {
/** Insert copied pages at this index (default: append to end) */
insertAt?: number;
/** Include annotations (default: true) */
includeAnnotations?: boolean;
/** Include article thread beads (default: false) */
includeBeads?: boolean;
/** Include thumbnail images (default: false) */
includeThumbnails?: boolean;
/** Include structure tree references (default: false) */
includeStructure?: boolean;
}
/**
* Options for merging multiple PDFs.
*/
export interface MergeOptions extends LoadOptions {
/** Include annotations from source documents (default: true) */
includeAnnotations?: boolean;
}
/**
* Options for extracting pages to a new document.
*/
export interface ExtractPagesOptions {
/** Include annotations (default: true) */
includeAnnotations?: boolean;
}
// ─────────────────────────────────────────────────────────────────────────────
// Metadata Types
// ─────────────────────────────────────────────────────────────────────────────
/**
* Trapped status indicating whether trapping has been applied.
* - "True": Document has been trapped
* - "False": Document has not been trapped
* - "Unknown": Unknown trapping status
*/
export type TrappedStatus = "True" | "False" | "Unknown";
/**
* Options for setTitle().
*/
export interface SetTitleOptions {
/**
* If true, PDF viewers should display the title in the window's title bar
* instead of the filename. Sets ViewerPreferences.DisplayDocTitle.
*/
showInWindowTitleBar?: boolean;
}
/**
* Document metadata that can be read or written in bulk.
*/
export interface DocumentMetadata {
/** Document title */
title?: string;
/** Name of the person who created the document content */
author?: string;
/** Subject/description of the document */
subject?: string;
/** Keywords associated with the document */
keywords?: string[];
/** Application that created the original content */
creator?: string;
/** Application that produced the PDF */
producer?: string;
/** Date the document was created */
creationDate?: Date;
/** Date the document was last modified */
modificationDate?: Date;
/** Whether the document has been trapped for printing */
trapped?: TrappedStatus;
/** RFC 3066 language tag (e.g., "en-US", "de-DE") */
language?: string;
}
/**
* High-level PDF document class.
*
* @example
* ```typescript
* // Load a PDF
* const pdf = await PDF.load(bytes);
*
* // Modify it
* const catalog = await pdf.getCatalog();
* catalog.set("ModDate", PdfString.fromString("D:20240101"));
*
* // Save with incremental update (preserves signatures)
* const saved = await pdf.save({ incremental: true });
*
* // Or save with full rewrite
* const rewritten = await pdf.save();
* ```
*/
export class PDF {
/** Central context for document operations */
private ctx: PDFContext;
private originalBytes: Uint8Array;
private originalXRefOffset: number;
/** Font operations manager (created lazily) */
private _fonts: PDFFonts | null = null;
/** Attachment operations manager (created lazily) */
private _attachments: PDFAttachments | null = null;
/** Cached form (loaded lazily via getForm()) */
private _form: PDFForm | null | undefined;
/** Whether this document was recovered via brute-force parsing */
private _recoveredViaBruteForce: boolean;
/** Whether this document was recovered via brute-force parsing */
get recoveredViaBruteForce(): boolean {
return this._recoveredViaBruteForce;
}
/** Whether this document is linearized */
private _isLinearized: boolean;
/** Whether this document is linearized */
get isLinearized(): boolean {
return this._isLinearized;
}
/** Whether the original document uses XRef streams (PDF 1.5+) */
private _usesXRefStreams: boolean;
/** Whether the document uses XRef streams (PDF 1.5+) */
get usesXRefStreams(): boolean {
return this._usesXRefStreams;
}
/**
* Whether this document was newly created (not loaded from bytes).
* Newly created documents cannot use incremental save.
*/
private _isNewlyCreated!: boolean;
/**
* Pending security state for save.
* Tracks whether encryption should be added, removed, or unchanged.
*/
private _pendingSecurity: PendingSecurityState = { action: "none" };
/** Warnings from parsing and operations */
get warnings(): string[] {
return this.ctx.warnings;
}
/**
* Access the internal PDF context.
*
* @internal Used by related API classes (PDFSignature, etc.)
*/
get context(): PDFContext {
return this.ctx;
}
private constructor(
ctx: PDFContext,
originalBytes: Uint8Array,
originalXRefOffset: number,
options: {
isNewlyCreated: boolean;
recoveredViaBruteForce: boolean;
isLinearized: boolean;
usesXRefStreams: boolean;
},
) {
this.ctx = ctx;
this.originalBytes = originalBytes;
this.originalXRefOffset = originalXRefOffset;
this._isNewlyCreated = options.isNewlyCreated;
this._recoveredViaBruteForce = options.recoveredViaBruteForce;
this._isLinearized = options.isLinearized;
this._usesXRefStreams = options.usesXRefStreams;
// Set up font resolver for the context
// Refs are pre-allocated, so this is synchronous
this.ctx.setFontRefResolver(font => {
return this.fonts.getRef(font);
});
}
// ─────────────────────────────────────────────────────────────────────────────
// Loading
// ─────────────────────────────────────────────────────────────────────────────
/**
* Load a PDF from bytes.
*
* @param bytes - The PDF file bytes
* @param options - Load options (credentials, lenient mode)
* @returns The loaded PDF document
* @throws {Error} If the document has no catalog (missing /Root in trailer)
* @throws {Error} If parsing fails and lenient mode is disabled
*/
// oxlint-disable-next-line typescript/require-await
static async load(bytes: Uint8Array, options?: LoadOptions): Promise<PDF> {
const scanner = new Scanner(bytes);
const parser = new DocumentParser(scanner, options);
const parsed = parser.parse();
// Create registry from xref
const registry = new ObjectRegistry(parsed.xref);
// Detect linearization by checking first object
let isLinearized = false;
try {
// Find the first object (lowest object number)
const firstObjNum = Math.min(...parsed.xref.keys());
if (firstObjNum > 0) {
const firstObj = parsed.getObject(PdfRef.of(firstObjNum, 0));
if (firstObj instanceof PdfDict && isLinearizationDict(firstObj)) {
isLinearized = true;
}
}
} catch {
// Ignore errors during linearization detection
}
// Find original xref offset and detect format
const xrefParser = new XRefParser(scanner);
let originalXRefOffset: number;
let usesXRefStreams = false;
try {
originalXRefOffset = xrefParser.findStartXRef();
// Detect if the original uses XRef streams
const format = xrefParser.detectXRefFormat(originalXRefOffset);
usesXRefStreams = format === true;
} catch {
originalXRefOffset = 0;
}
// Set up resolver on registry before loading anything
registry.setResolver(ref => parsed.getObject(ref));
// Load catalog through registry so it's tracked for changes
const rootRef = parsed.trailer.getRef("Root");
if (!rootRef) {
throw new Error("Document has no catalog (missing /Root in trailer)");
}
const catalogDict = registry.resolve(rootRef);
if (!catalogDict || !(catalogDict instanceof PdfDict)) {
throw new Error("Document has no catalog");
}
const pdfCatalog = new PDFCatalog(catalogDict, registry);
const pagesRef = catalogDict.getRef("Pages");
// Use registry.resolve so page tree objects are tracked for
// modification detection and reachability analysis during save.
const pages = pagesRef
? PDFPageTree.load(pagesRef, registry.resolve.bind(registry))
: PDFPageTree.empty();
// Load Info dictionary if present (for metadata access)
const infoRef = parsed.trailer.getRef("Info");
if (infoRef) {
registry.resolve(infoRef);
}
// Extract document info from parsed document
const info: DocumentInfo = {
version: parsed.version,
securityHandler: parsed.securityHandler,
isEncrypted: parsed.isEncrypted,
isAuthenticated: parsed.isAuthenticated,
trailer: parsed.trailer,
};
const ctx = new PDFContext(registry, pdfCatalog, pages, info);
return new PDF(ctx, bytes, originalXRefOffset, {
isNewlyCreated: false,
recoveredViaBruteForce: parsed.recoveredViaBruteForce,
isLinearized,
usesXRefStreams,
});
}
/**
* Reload the PDF from new bytes.
*
* Updates internal state after an incremental save. This allows
* continued use of the PDF instance after operations like signing.
*
* @param bytes - The new PDF bytes to reload from
* @throws {Error} If the document has no catalog
*/
// oxlint-disable-next-line typescript/require-await
async reload(bytes: Uint8Array): Promise<void> {
const scanner = new Scanner(bytes);
const parser = new DocumentParser(scanner);
const parsed = parser.parse();
// Create new registry from xref
const registry = new ObjectRegistry(parsed.xref);
registry.setResolver(ref => parsed.getObject(ref));
// Detect linearization by checking first object
let isLinearized = false;
try {
const firstObjNum = Math.min(...parsed.xref.keys());
if (firstObjNum > 0) {
const firstObj = parsed.getObject(PdfRef.of(firstObjNum, 0));
if (firstObj instanceof PdfDict && isLinearizationDict(firstObj)) {
isLinearized = true;
}
}
} catch {
// Ignore errors during linearization detection
}
// Find xref offset and detect format
const xrefParser = new XRefParser(scanner);
let xrefOffset: number;
let usesXRefStreams = false;
try {
xrefOffset = xrefParser.findStartXRef();
// Detect if the document uses XRef streams
const format = xrefParser.detectXRefFormat(xrefOffset);
usesXRefStreams = format === true;
} catch {
xrefOffset = 0;
}
// Load catalog
const rootRef = parsed.trailer.getRef("Root");
if (!rootRef) {
throw new Error("Document has no catalog");
}
const catalogDict = registry.resolve(rootRef);
if (!(catalogDict instanceof PdfDict)) {
throw new Error("Document has no catalog");
}
const pdfCatalog = new PDFCatalog(catalogDict, registry);
const pagesRef = catalogDict.getRef("Pages");
const pages = pagesRef
? PDFPageTree.load(pagesRef, registry.resolve.bind(registry))
: PDFPageTree.empty();
// Load Info dictionary if present (for metadata change tracking)
const infoRef = parsed.trailer.getRef("Info");
if (infoRef) {
registry.resolve(infoRef);
}
const info: DocumentInfo = {
version: parsed.version,
securityHandler: parsed.securityHandler,
isEncrypted: parsed.isEncrypted,
isAuthenticated: parsed.isAuthenticated,
trailer: parsed.trailer,
};
// Update internal state
this.ctx = new PDFContext(registry, pdfCatalog, pages, info);
this.originalBytes = bytes;
this.originalXRefOffset = xrefOffset;
// Reset flags - after reload, document is no longer "newly created"
// and any pending security changes have been applied
this._isNewlyCreated = false;
this._recoveredViaBruteForce = parsed.recoveredViaBruteForce;
this._isLinearized = isLinearized;
this._usesXRefStreams = usesXRefStreams;
this._pendingSecurity = { action: "none" };
// Clear cached managers so they get recreated with the new context
this._fonts = null;
this._attachments = null;
this._form = undefined;
// Re-setup font resolver for the new context
this.ctx.setFontRefResolver(font => {
return this.fonts.getRef(font);
});
}
/**
* Create a new empty PDF document.
*
* @returns A new PDF document with no pages
*
* @example
* ```typescript
* const pdf = PDF.create();
* pdf.addPage({ size: "letter" });
* const bytes = await pdf.save();
* ```
*/
static create(): PDF {
// Create minimal PDF structure
const registry = new ObjectRegistry(new Map());
// Create empty pages tree
const pagesDict = PdfDict.of({
Type: PdfName.of("Pages"),
Kids: new PdfArray([]),
Count: PdfNumber.of(0),
});
const pagesRef = registry.register(pagesDict);
// Create catalog
const catalogDict = PdfDict.of({
Type: PdfName.of("Catalog"),
Pages: pagesRef,
});
const catalogRef = registry.register(catalogDict);
// Create trailer pointing to catalog
const trailer = PdfDict.of({
Root: catalogRef,
});
// Set resolver (returns from registry)
registry.setResolver((ref: PdfRef) => registry.getObject(ref));
const pdfCatalog = new PDFCatalog(catalogDict, registry);
const pages = PDFPageTree.fromRoot(pagesRef, pagesDict, ref => {
const obj = registry.getObject(ref);
if (obj instanceof PdfDict) {
return obj;
}
return null;
});
// Create document info for a new document
const info: DocumentInfo = {
version: "1.7",
securityHandler: null,
isEncrypted: false,
isAuthenticated: true,
trailer,
};
const ctx = new PDFContext(registry, pdfCatalog, pages, info);
const pdf = new PDF(ctx, new Uint8Array(0), 0, {
isNewlyCreated: true,
recoveredViaBruteForce: false,
isLinearized: false,
usesXRefStreams: false,
});
// Set default metadata for new documents
pdf.setMetadata({
title: "Untitled",
author: "Unknown",
creator: "@libpdf/core",
producer: "@libpdf/core",
creationDate: new Date(),
modificationDate: new Date(),
});
return pdf;
}
/**
* Merge multiple PDF documents into one.
*
* Creates a new document containing all pages from the source documents
* in order. The resulting document is a fresh copy — original documents
* are not modified.
*
* @param sources Array of PDF bytes to merge
* @param options Load and merge options
* @returns A new PDF containing all pages from the sources
*
* @example
* ```typescript
* const merged = await PDF.merge([pdfBytes1, pdfBytes2, pdfBytes3]);
* const bytes = await merged.save();
* ```
*/
static async merge(sources: Uint8Array[], options: MergeOptions = {}): Promise<PDF> {
if (sources.length === 0) {
return PDF.create();
}
// Load first document as the base
const result = await PDF.load(sources[0], options);
// Copy pages from remaining documents
for (let i = 1; i < sources.length; i++) {
const source = await PDF.load(sources[i], options);
const pageCount = source.getPageCount();
if (pageCount > 0) {
const indices = Array.from({ length: pageCount }, (_, j) => j);
await result.copyPagesFrom(source, indices, {
includeAnnotations: options.includeAnnotations ?? true,
});
}
}
return result;
}
// ─────────────────────────────────────────────────────────────────────────────
// Document info
// ─────────────────────────────────────────────────────────────────────────────
/** PDF version string (e.g., "1.7", "2.0") */
get version(): string {
return this.ctx.info.version;
}
/**
* Upgrade the PDF version.
*
* Sets the /Version entry in the catalog dictionary. This is the standard
* way to upgrade PDF version in incremental updates since the header
* cannot be modified.
*
* The version will only be upgraded if the new version is higher than
* the current version.
*
* @param version - Target version (e.g., "1.7", "2.0")
*
* @example
* ```typescript
* pdf.upgradeVersion("1.7");
* ```
*/
upgradeVersion(version: string): void {
// Parse versions for comparison
const parseVersion = (v: string): number => {
const [major, minor] = v.split(".").map(Number);
return major * 10 + (minor || 0);
};
const currentVersion = parseVersion(this.ctx.info.version);
const targetVersion = parseVersion(version);
// Only upgrade, never downgrade
if (targetVersion <= currentVersion) {
return;
}
// Set the version in the catalog
const catalog = this.ctx.catalog.getDict();
catalog.set("Version", PdfName.of(version));
// Update internal version tracking
this.ctx.info.version = version;
}
/** Whether the document is encrypted */
get isEncrypted(): boolean {
return this.ctx.info.isEncrypted;
}
/** Whether authentication succeeded (for encrypted docs) */
get isAuthenticated(): boolean {
return this.ctx.info.isAuthenticated;
}
// ─────────────────────────────────────────────────────────────────────────────
// Security
// ─────────────────────────────────────────────────────────────────────────────
/**
* Get detailed security information about the document.
*
* @returns Security information including encryption details and permissions
*
* @example
* ```typescript
* const security = pdf.getSecurity();
* console.log(`Algorithm: ${security.algorithm}`);
* console.log(`Can copy: ${security.permissions.copy}`);
* ```
*/
getSecurity(): SecurityInfo {
const handler = this.ctx.info.securityHandler;
if (!this.isEncrypted || !handler) {
return {
isEncrypted: false,
permissions: DEFAULT_PERMISSIONS,
};
}
const encryption = handler.encryption;
// Map internal algorithm to public API type
let algorithm: EncryptionAlgorithmOption | undefined;
switch (encryption.algorithm) {
case "RC4":
algorithm = encryption.keyLengthBits <= 40 ? "RC4-40" : "RC4-128";
break;
case "AES-128":
algorithm = "AES-128";
break;
case "AES-256":
algorithm = "AES-256";
break;
}
// Determine how the document was authenticated
let authenticatedAs: "user" | "owner" | null = null;
if (handler.isAuthenticated) {
authenticatedAs = handler.hasOwnerAccess ? "owner" : "user";
}
// For owner access, all permissions are granted regardless of flags
const permissions = handler.hasOwnerAccess ? DEFAULT_PERMISSIONS : handler.permissions;
return {
isEncrypted: true,
algorithm,
keyLength: encryption.keyLengthBits,
revision: encryption.revision,
hasUserPassword: true, // We can't easily detect empty user password after the fact
hasOwnerPassword: true,
authenticatedAs,
permissions,
encryptMetadata: encryption.encryptMetadata,
};
}
/**
* Get the current permission flags.
*
* Returns all permissions as true for unencrypted documents.
* For encrypted documents authenticated with owner password, all are true.
*
* @returns Current permission flags
*
* @example
* ```typescript
* const perms = pdf.getPermissions();
* if (!perms.copy) {
* console.log("Copy/paste is restricted");
* }
* ```
*/
getPermissions(): Permissions {
const handler = this.ctx.info.securityHandler;
if (!this.isEncrypted || !handler) {
return DEFAULT_PERMISSIONS;
}
// Owner access grants all permissions
if (handler.hasOwnerAccess) {
return DEFAULT_PERMISSIONS;
}
return handler.permissions;
}
/**
* Check if the document was authenticated with owner-level access.
*
* Owner access grants all permissions regardless of permission flags.
* Returns true for unencrypted documents.
*
* @returns true if owner access is available
*/
hasOwnerAccess(): boolean {
if (!this.isEncrypted) {
return true;
}
const handler = this.ctx.info.securityHandler;
return handler?.hasOwnerAccess ?? false;
}
/**
* Attempt to authenticate with a password.
*
* Use this to upgrade access (e.g., from user to owner) or to
* try a different password without reloading the document.
*
* @param password - Password to try
* @returns Authentication result
*
* @example
* ```typescript
* // Try to get owner access
* const result = pdf.authenticate("ownerPassword");
* if (result.isOwner) {
* pdf.removeProtection();
* }
* ```
*/
authenticate(password: string): AuthenticationResult {
const handler = this.ctx.info.securityHandler;
if (!this.isEncrypted || !handler) {
return {
authenticated: true,
isOwner: true,
permissions: DEFAULT_PERMISSIONS,
};
}
const result = handler.authenticateWithString(password);
// For owner access, all permissions are granted
const permissions = result.isOwner ? DEFAULT_PERMISSIONS : result.permissions;
return {
authenticated: result.authenticated,
passwordType: result.passwordType,
isOwner: result.isOwner,
permissions,
};
}
/**
* Remove all encryption from the document.
*
* After calling this, the document will be saved without encryption.
* Requires owner access, or user access with modify permission.
*
* @throws {PermissionDeniedError} If insufficient permissions to remove protection
*
* @example
* ```typescript
* // Remove encryption from a document
* const pdf = await PDF.load(bytes, { credentials: "ownerPassword" });
* pdf.removeProtection();
* const unprotectedBytes = await pdf.save();
* ```
*/
removeProtection(): void {
// For unencrypted documents, this is a no-op
if (!this.isEncrypted) {
return;
}
const handler = this.ctx.info.securityHandler;
if (!handler) {
return;
}
// Check permissions
if (!handler.hasOwnerAccess && !handler.permissions.modify) {
throw new PermissionDeniedError(
"Cannot remove protection: requires owner access or modify permission",
"modify",
);
}
// Mark that encryption should be removed on save
this._pendingSecurity = { action: "remove" };
}
/**
* Add or change document encryption.
*
* If the document is already encrypted, requires owner access to change.
* If unencrypted, can be called without restrictions.
*
* @param options - Protection options (passwords, permissions, algorithm)
* @throws {PermissionDeniedError} If insufficient permissions to change protection
*
* @example
* ```typescript
* // Add protection to unencrypted document
* pdf.setProtection({
* userPassword: "secret",
* ownerPassword: "admin",
* permissions: { copy: false, print: true },
* });
*
* // Change to stronger algorithm
* pdf.setProtection({
* algorithm: "AES-256",
* });
* ```
*/
setProtection(options: ProtectionOptions): void {
// If encrypted, need owner access to change
if (this.isEncrypted) {
const handler = this.ctx.info.securityHandler;
if (handler && !handler.hasOwnerAccess) {
throw new PermissionDeniedError("Cannot change protection: requires owner access");
}
}
// Mark that encryption should be applied on save
this._pendingSecurity = { action: "encrypt", options };
}
// ─────────────────────────────────────────────────────────────────────────────
// Metadata
// ─────────────────────────────────────────────────────────────────────────────
/** Cached Info dictionary */
private _infoDict: PdfDict | null = null;