forked from mozilla/pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.js
More file actions
1683 lines (1520 loc) · 45.9 KB
/
document.js
File metadata and controls
1683 lines (1520 loc) · 45.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
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
assert,
FormatError,
info,
InvalidPDFException,
isArrayEqual,
PageActionEventType,
RenderingIntentFlag,
shadow,
stringToBytes,
stringToPDFString,
stringToUTF8String,
unreachable,
UNSUPPORTED_FEATURES,
Util,
warn,
} from "../shared/util.js";
import {
collectActions,
getInheritableProperty,
getNewAnnotationsMap,
isWhiteSpace,
MissingDataException,
validateCSSFont,
XRefEntryException,
XRefParseException,
} from "./core_utils.js";
import { Dict, isName, Name, Ref } from "./primitives.js";
import { getXfaFontDict, getXfaFontName } from "./xfa_fonts.js";
import { AnnotationFactory } from "./annotation.js";
import { BaseStream } from "./base_stream.js";
import { calculateMD5 } from "./crypto.js";
import { Catalog } from "./catalog.js";
import { clearGlobalCaches } from "./cleanup_helper.js";
import { DatasetReader } from "./dataset_reader.js";
import { Linearization } from "./parser.js";
import { NullStream } from "./stream.js";
import { ObjectLoader } from "./object_loader.js";
import { OperatorList } from "./operator_list.js";
import { PartialEvaluator } from "./evaluator.js";
import { StreamsSequenceStream } from "./decode_stream.js";
import { StructTreePage } from "./struct_tree.js";
import { writeObject } from "./writer.js";
import { XFAFactory } from "./xfa/factory.js";
import { XRef } from "./xref.js";
const DEFAULT_USER_UNIT = 1.0;
const LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
class Page {
constructor({
pdfManager,
xref,
pageIndex,
pageDict,
ref,
globalIdFactory,
fontCache,
builtInCMapCache,
standardFontDataCache,
globalImageCache,
nonBlendModesSet,
xfaFactory,
}) {
this.pdfManager = pdfManager;
this.pageIndex = pageIndex;
this.pageDict = pageDict;
this.xref = xref;
this.ref = ref;
this.fontCache = fontCache;
this.builtInCMapCache = builtInCMapCache;
this.standardFontDataCache = standardFontDataCache;
this.globalImageCache = globalImageCache;
this.nonBlendModesSet = nonBlendModesSet;
this.evaluatorOptions = pdfManager.evaluatorOptions;
this.resourcesPromise = null;
this.xfaFactory = xfaFactory;
const idCounters = {
obj: 0,
};
this._localIdFactory = class extends globalIdFactory {
static createObjId() {
return `p${pageIndex}_${++idCounters.obj}`;
}
static getPageObjId() {
return `page${ref.toString()}`;
}
};
}
/**
* @private
*/
_getInheritableProperty(key, getArray = false) {
const value = getInheritableProperty({
dict: this.pageDict,
key,
getArray,
stopWhenFound: false,
});
if (!Array.isArray(value)) {
return value;
}
if (value.length === 1 || !(value[0] instanceof Dict)) {
return value[0];
}
return Dict.merge({ xref: this.xref, dictArray: value });
}
get content() {
return this.pageDict.getArray("Contents");
}
get resources() {
// For robustness: The spec states that a \Resources entry has to be
// present, but can be empty. Some documents still omit it; in this case
// we return an empty dictionary.
const resources = this._getInheritableProperty("Resources");
return shadow(
this,
"resources",
resources instanceof Dict ? resources : Dict.empty
);
}
_getBoundingBox(name) {
if (this.xfaData) {
return this.xfaData.bbox;
}
const box = this._getInheritableProperty(name, /* getArray = */ true);
if (Array.isArray(box) && box.length === 4) {
if (box[2] - box[0] !== 0 && box[3] - box[1] !== 0) {
return box;
}
warn(`Empty /${name} entry.`);
}
return null;
}
get mediaBox() {
// Reset invalid media box to letter size.
return shadow(
this,
"mediaBox",
this._getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX
);
}
get cropBox() {
// Reset invalid crop box to media box.
return shadow(
this,
"cropBox",
this._getBoundingBox("CropBox") || this.mediaBox
);
}
get userUnit() {
let obj = this.pageDict.get("UserUnit");
if (typeof obj !== "number" || obj <= 0) {
obj = DEFAULT_USER_UNIT;
}
return shadow(this, "userUnit", obj);
}
get view() {
// From the spec, 6th ed., p.963:
// "The crop, bleed, trim, and art boxes should not ordinarily
// extend beyond the boundaries of the media box. If they do, they are
// effectively reduced to their intersection with the media box."
const { cropBox, mediaBox } = this;
let view;
if (cropBox === mediaBox || isArrayEqual(cropBox, mediaBox)) {
view = mediaBox;
} else {
const box = Util.intersect(cropBox, mediaBox);
if (box && box[2] - box[0] !== 0 && box[3] - box[1] !== 0) {
view = box;
} else {
warn("Empty /CropBox and /MediaBox intersection.");
}
}
return shadow(this, "view", view || mediaBox);
}
get rotate() {
let rotate = this._getInheritableProperty("Rotate") || 0;
// Normalize rotation so it's a multiple of 90 and between 0 and 270.
if (rotate % 90 !== 0) {
rotate = 0;
} else if (rotate >= 360) {
rotate %= 360;
} else if (rotate < 0) {
// The spec doesn't cover negatives. Assume it's counterclockwise
// rotation. The following is the other implementation of modulo.
rotate = ((rotate % 360) + 360) % 360;
}
return shadow(this, "rotate", rotate);
}
/**
* @private
*/
_onSubStreamError(handler, reason, objId) {
if (this.evaluatorOptions.ignoreErrors) {
// Error(s) when reading one of the /Contents sub-streams -- sending
// unsupported feature notification and allow parsing to continue.
handler.send("UnsupportedFeature", {
featureId: UNSUPPORTED_FEATURES.errorContentSubStream,
});
warn(`getContentStream - ignoring sub-stream (${objId}): "${reason}".`);
return;
}
throw reason;
}
/**
* @returns {Promise<BaseStream>}
*/
getContentStream(handler) {
return this.pdfManager.ensure(this, "content").then(content => {
if (content instanceof BaseStream) {
return content;
}
if (Array.isArray(content)) {
return new StreamsSequenceStream(
content,
this._onSubStreamError.bind(this, handler)
);
}
// Replace non-existent page content with empty content.
return new NullStream();
});
}
get xfaData() {
return shadow(
this,
"xfaData",
this.xfaFactory
? { bbox: this.xfaFactory.getBoundingBox(this.pageIndex) }
: null
);
}
async saveNewAnnotations(handler, task, annotations) {
if (this.xfaFactory) {
throw new Error("XFA: Cannot save new annotations.");
}
const partialEvaluator = new PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
});
const pageDict = this.pageDict;
const annotationsArray = this.annotations.slice();
const newData = await AnnotationFactory.saveNewAnnotations(
partialEvaluator,
task,
annotations
);
for (const { ref } of newData.annotations) {
annotationsArray.push(ref);
}
const savedDict = pageDict.get("Annots");
pageDict.set("Annots", annotationsArray);
const buffer = [];
let transform = null;
if (this.xref.encrypt) {
transform = this.xref.encrypt.createCipherTransform(
this.ref.num,
this.ref.gen
);
}
writeObject(this.ref, pageDict, buffer, transform);
if (savedDict) {
pageDict.set("Annots", savedDict);
}
const objects = newData.dependencies;
objects.push(
{ ref: this.ref, data: buffer.join("") },
...newData.annotations
);
return objects;
}
save(handler, task, annotationStorage) {
const partialEvaluator = new PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
});
// Fetch the page's annotations and save the content
// in case of interactive form fields.
return this._parsedAnnotations.then(function (annotations) {
const newRefsPromises = [];
for (const annotation of annotations) {
if (!annotation.mustBePrinted(annotationStorage)) {
continue;
}
newRefsPromises.push(
annotation
.save(partialEvaluator, task, annotationStorage)
.catch(function (reason) {
warn(
"save - ignoring annotation data during " +
`"${task.name}" task: "${reason}".`
);
return null;
})
);
}
return Promise.all(newRefsPromises).then(function (newRefs) {
return newRefs.filter(newRef => !!newRef);
});
});
}
loadResources(keys) {
if (!this.resourcesPromise) {
// TODO: add async `_getInheritableProperty` and remove this.
this.resourcesPromise = this.pdfManager.ensure(this, "resources");
}
return this.resourcesPromise.then(() => {
const objectLoader = new ObjectLoader(this.resources, keys, this.xref);
return objectLoader.load();
});
}
getOperatorList({
handler,
sink,
task,
intent,
cacheKey,
annotationStorage = null,
}) {
const contentStreamPromise = this.getContentStream(handler);
const resourcesPromise = this.loadResources([
"ColorSpace",
"ExtGState",
"Font",
"Pattern",
"Properties",
"Shading",
"XObject",
]);
const partialEvaluator = new PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
});
const newAnnotationsByPage = !this.xfaFactory
? getNewAnnotationsMap(annotationStorage)
: null;
let newAnnotationsPromise = Promise.resolve(null);
if (newAnnotationsByPage) {
const newAnnotations = newAnnotationsByPage.get(this.pageIndex);
if (newAnnotations) {
newAnnotationsPromise = AnnotationFactory.printNewAnnotations(
partialEvaluator,
task,
newAnnotations
);
}
}
const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
const pageListPromise = dataPromises.then(([contentStream]) => {
const opList = new OperatorList(intent, sink);
handler.send("StartRenderPage", {
transparency: partialEvaluator.hasBlendModes(
this.resources,
this.nonBlendModesSet
),
pageIndex: this.pageIndex,
cacheKey,
});
return partialEvaluator
.getOperatorList({
stream: contentStream,
task,
resources: this.resources,
operatorList: opList,
})
.then(function () {
return opList;
});
});
// Fetch the page's annotations and add their operator lists to the
// page's operator list to render them.
return Promise.all([
pageListPromise,
this._parsedAnnotations,
newAnnotationsPromise,
]).then(function ([pageOpList, annotations, newAnnotations]) {
if (newAnnotations) {
annotations = annotations.concat(newAnnotations);
}
if (
annotations.length === 0 ||
intent & RenderingIntentFlag.ANNOTATIONS_DISABLE
) {
pageOpList.flush(true);
return { length: pageOpList.totalLength };
}
const renderForms = !!(intent & RenderingIntentFlag.ANNOTATIONS_FORMS),
intentAny = !!(intent & RenderingIntentFlag.ANY),
intentDisplay = !!(intent & RenderingIntentFlag.DISPLAY),
intentPrint = !!(intent & RenderingIntentFlag.PRINT);
// Collect the operator list promises for the annotations. Each promise
// is resolved with the complete operator list for a single annotation.
const opListPromises = [];
for (const annotation of annotations) {
if (
intentAny ||
(intentDisplay && annotation.mustBeViewed(annotationStorage)) ||
(intentPrint && annotation.mustBePrinted(annotationStorage))
) {
opListPromises.push(
annotation
.getOperatorList(
partialEvaluator,
task,
intent,
renderForms,
annotationStorage
)
.catch(function (reason) {
warn(
"getOperatorList - ignoring annotation data during " +
`"${task.name}" task: "${reason}".`
);
return null;
})
);
}
}
return Promise.all(opListPromises).then(function (opLists) {
for (const opList of opLists) {
pageOpList.addOpList(opList);
}
pageOpList.flush(true);
return { length: pageOpList.totalLength };
});
});
}
extractTextContent({
handler,
task,
includeMarkedContent,
sink,
combineTextItems,
}) {
const contentStreamPromise = this.getContentStream(handler);
const resourcesPromise = this.loadResources([
"ExtGState",
"Font",
"Properties",
"XObject",
]);
const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
return dataPromises.then(([contentStream]) => {
const partialEvaluator = new PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
});
return partialEvaluator.getTextContent({
stream: contentStream,
task,
resources: this.resources,
includeMarkedContent,
combineTextItems,
sink,
viewBox: this.view,
});
});
}
async getStructTree() {
const structTreeRoot = await this.pdfManager.ensureCatalog(
"structTreeRoot"
);
if (!structTreeRoot) {
return null;
}
const structTree = await this.pdfManager.ensure(this, "_parseStructTree", [
structTreeRoot,
]);
return structTree.serializable;
}
/**
* @private
*/
_parseStructTree(structTreeRoot) {
const tree = new StructTreePage(structTreeRoot, this.pageDict);
tree.parse();
return tree;
}
getAnnotationsData(intent) {
return this._parsedAnnotations.then(function (annotations) {
const annotationsData = [];
if (annotations.length === 0) {
return annotationsData;
}
const intentAny = !!(intent & RenderingIntentFlag.ANY),
intentDisplay = !!(intent & RenderingIntentFlag.DISPLAY),
intentPrint = !!(intent & RenderingIntentFlag.PRINT);
for (const annotation of annotations) {
// Get the annotation even if it's hidden because
// JS can change its display.
if (
intentAny ||
(intentDisplay && annotation.viewable) ||
(intentPrint && annotation.printable)
) {
annotationsData.push(annotation.data);
}
}
return annotationsData;
});
}
get annotations() {
const annots = this._getInheritableProperty("Annots");
return shadow(this, "annotations", Array.isArray(annots) ? annots : []);
}
get _parsedAnnotations() {
const parsedAnnotations = this.pdfManager
.ensure(this, "annotations")
.then(() => {
const annotationPromises = [];
for (const annotationRef of this.annotations) {
annotationPromises.push(
AnnotationFactory.create(
this.xref,
annotationRef,
this.pdfManager,
this._localIdFactory,
/* collectFields */ false
).catch(function (reason) {
warn(`_parsedAnnotations: "${reason}".`);
return null;
})
);
}
return Promise.all(annotationPromises).then(function (annotations) {
return annotations.filter(annotation => !!annotation);
});
});
return shadow(this, "_parsedAnnotations", parsedAnnotations);
}
get jsActions() {
const actions = collectActions(
this.xref,
this.pageDict,
PageActionEventType
);
return shadow(this, "jsActions", actions);
}
}
const PDF_HEADER_SIGNATURE = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]);
const STARTXREF_SIGNATURE = new Uint8Array([
0x73, 0x74, 0x61, 0x72, 0x74, 0x78, 0x72, 0x65, 0x66,
]);
const ENDOBJ_SIGNATURE = new Uint8Array([0x65, 0x6e, 0x64, 0x6f, 0x62, 0x6a]);
const FINGERPRINT_FIRST_BYTES = 1024;
const EMPTY_FINGERPRINT =
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const PDF_HEADER_VERSION_REGEXP = /^[1-9]\.\d$/;
function find(stream, signature, limit = 1024, backwards = false) {
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || TESTING")
) {
assert(limit > 0, 'The "limit" must be a positive integer.');
}
const signatureLength = signature.length;
const scanBytes = stream.peekBytes(limit);
const scanLength = scanBytes.length - signatureLength;
if (scanLength <= 0) {
return false;
}
if (backwards) {
const signatureEnd = signatureLength - 1;
let pos = scanBytes.length - 1;
while (pos >= signatureEnd) {
let j = 0;
while (
j < signatureLength &&
scanBytes[pos - j] === signature[signatureEnd - j]
) {
j++;
}
if (j >= signatureLength) {
// `signature` found.
stream.pos += pos - signatureEnd;
return true;
}
pos--;
}
} else {
// forwards
let pos = 0;
while (pos <= scanLength) {
let j = 0;
while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
j++;
}
if (j >= signatureLength) {
// `signature` found.
stream.pos += pos;
return true;
}
pos++;
}
}
return false;
}
/**
* The `PDFDocument` class holds all the (worker-thread) data of the PDF file.
*/
class PDFDocument {
constructor(pdfManager, stream) {
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || TESTING")
) {
assert(
stream instanceof BaseStream,
'PDFDocument: Invalid "stream" argument.'
);
}
if (stream.length <= 0) {
throw new InvalidPDFException(
"The PDF file is empty, i.e. its size is zero bytes."
);
}
this.pdfManager = pdfManager;
this.stream = stream;
this.xref = new XRef(stream, pdfManager);
this._pagePromises = new Map();
this._version = null;
const idCounters = {
font: 0,
};
this._globalIdFactory = class {
static getDocId() {
return `g_${pdfManager.docId}`;
}
static createFontId() {
return `f${++idCounters.font}`;
}
static createObjId() {
unreachable("Abstract method `createObjId` called.");
}
static getPageObjId() {
unreachable("Abstract method `getPageObjId` called.");
}
};
}
parse(recoveryMode) {
this.xref.parse(recoveryMode);
this.catalog = new Catalog(this.pdfManager, this.xref);
// The `checkHeader` method is called before this method and parses the
// version from the header. The specification states in section 7.5.2
// that the version from the catalog, if present, should overwrite the
// version from the header.
if (this.catalog.version) {
this._version = this.catalog.version;
}
}
get linearization() {
let linearization = null;
try {
linearization = Linearization.create(this.stream);
} catch (err) {
if (err instanceof MissingDataException) {
throw err;
}
info(err);
}
return shadow(this, "linearization", linearization);
}
get startXRef() {
const stream = this.stream;
let startXRef = 0;
if (this.linearization) {
// Find the end of the first object.
stream.reset();
if (find(stream, ENDOBJ_SIGNATURE)) {
startXRef = stream.pos + 6 - stream.start;
}
} else {
// Find `startxref` by checking backwards from the end of the file.
const step = 1024;
const startXRefLength = STARTXREF_SIGNATURE.length;
let found = false,
pos = stream.end;
while (!found && pos > 0) {
pos -= step - startXRefLength;
if (pos < 0) {
pos = 0;
}
stream.pos = pos;
found = find(stream, STARTXREF_SIGNATURE, step, true);
}
if (found) {
stream.skip(9);
let ch;
do {
ch = stream.getByte();
} while (isWhiteSpace(ch));
let str = "";
while (ch >= /* Space = */ 0x20 && ch <= /* '9' = */ 0x39) {
str += String.fromCharCode(ch);
ch = stream.getByte();
}
startXRef = parseInt(str, 10);
if (isNaN(startXRef)) {
startXRef = 0;
}
}
}
return shadow(this, "startXRef", startXRef);
}
// Find the header, get the PDF format version and setup the
// stream to start from the header.
checkHeader() {
const stream = this.stream;
stream.reset();
if (!find(stream, PDF_HEADER_SIGNATURE)) {
// May not be a PDF file, but don't throw an error and let
// parsing continue.
return;
}
stream.moveStart();
// Read the PDF format version.
const MAX_PDF_VERSION_LENGTH = 12;
let version = "",
ch;
while ((ch = stream.getByte()) > /* Space = */ 0x20) {
if (version.length >= MAX_PDF_VERSION_LENGTH) {
break;
}
version += String.fromCharCode(ch);
}
if (!this._version) {
// Remove the "%PDF-" prefix.
this._version = version.substring(5);
}
}
parseStartXRef() {
this.xref.setStartXRef(this.startXRef);
}
get numPages() {
let num = 0;
if (this.catalog.hasActualNumPages) {
num = this.catalog.numPages;
} else if (this.xfaFactory) {
// num is a Promise.
num = this.xfaFactory.getNumPages();
} else if (this.linearization) {
num = this.linearization.numPages;
} else {
num = this.catalog.numPages;
}
return shadow(this, "numPages", num);
}
/**
* @private
*/
_hasOnlyDocumentSignatures(fields, recursionDepth = 0) {
const RECURSION_LIMIT = 10;
if (!Array.isArray(fields)) {
return false;
}
return fields.every(field => {
field = this.xref.fetchIfRef(field);
if (!(field instanceof Dict)) {
return false;
}
if (field.has("Kids")) {
if (++recursionDepth > RECURSION_LIMIT) {
warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");
return false;
}
return this._hasOnlyDocumentSignatures(
field.get("Kids"),
recursionDepth
);
}
const isSignature = isName(field.get("FT"), "Sig");
const rectangle = field.get("Rect");
const isInvisible =
Array.isArray(rectangle) && rectangle.every(value => value === 0);
return isSignature && isInvisible;
});
}
get _xfaStreams() {
const acroForm = this.catalog.acroForm;
if (!acroForm) {
return null;
}
const xfa = acroForm.get("XFA");
const entries = {
"xdp:xdp": "",
template: "",
datasets: "",
config: "",
connectionSet: "",
localeSet: "",
stylesheet: "",
"/xdp:xdp": "",
};
if (xfa instanceof BaseStream && !xfa.isEmpty) {
entries["xdp:xdp"] = xfa;
return entries;
}
if (!Array.isArray(xfa) || xfa.length === 0) {
return null;
}
for (let i = 0, ii = xfa.length; i < ii; i += 2) {
let name;
if (i === 0) {
name = "xdp:xdp";
} else if (i === ii - 2) {
name = "/xdp:xdp";
} else {
name = xfa[i];
}
if (!entries.hasOwnProperty(name)) {
continue;
}
const data = this.xref.fetchIfRef(xfa[i + 1]);
if (!(data instanceof BaseStream) || data.isEmpty) {
continue;
}
entries[name] = data;
}
return entries;
}
get xfaDatasets() {
const streams = this._xfaStreams;
if (!streams) {
return shadow(this, "xfaDatasets", null);
}
for (const key of ["datasets", "xdp:xdp"]) {
const stream = streams[key];
if (!stream) {
continue;
}
try {
const str = stringToUTF8String(stream.getString());
const data = { [key]: str };
return shadow(this, "xfaDatasets", new DatasetReader(data));
} catch (_) {
warn("XFA - Invalid utf-8 string.");
break;
}
}
return shadow(this, "xfaDatasets", null);
}
get xfaData() {
const streams = this._xfaStreams;
if (!streams) {
return null;
}
const data = Object.create(null);
for (const [key, stream] of Object.entries(streams)) {
if (!stream) {
continue;
}
try {
data[key] = stringToUTF8String(stream.getString());
} catch (_) {
warn("XFA - Invalid utf-8 string.");
return null;
}
}
return data;
}
get xfaFactory() {
let data;
if (
this.pdfManager.enableXfa &&
this.catalog.needsRendering &&
this.formInfo.hasXfa &&
!this.formInfo.hasAcroForm
) {
data = this.xfaData;