1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285 |
- /**
- * @licstart The following is the entire license notice for the
- * JavaScript code in this page
- *
- * Copyright 2022 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.
- *
- * @licend The above is the entire license notice for the
- * JavaScript code in this page
- */
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Page = exports.PDFDocument = void 0;
- var _annotation = require("./annotation.js");
- var _util = require("../shared/util.js");
- var _core_utils = require("./core_utils.js");
- var _primitives = require("./primitives.js");
- var _xfa_fonts = require("./xfa_fonts.js");
- var _base_stream = require("./base_stream.js");
- var _crypto = require("./crypto.js");
- var _catalog = require("./catalog.js");
- var _cleanup_helper = require("./cleanup_helper.js");
- var _dataset_reader = require("./dataset_reader.js");
- var _parser = require("./parser.js");
- var _stream = require("./stream.js");
- var _object_loader = require("./object_loader.js");
- var _operator_list = require("./operator_list.js");
- var _evaluator = require("./evaluator.js");
- var _decode_stream = require("./decode_stream.js");
- var _struct_tree = require("./struct_tree.js");
- var _writer = require("./writer.js");
- var _factory = require("./xfa/factory.js");
- var _xref = require("./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()}`;
- }
- };
- }
- _getInheritableProperty(key, getArray = false) {
- const value = (0, _core_utils.getInheritableProperty)({
- dict: this.pageDict,
- key,
- getArray,
- stopWhenFound: false
- });
- if (!Array.isArray(value)) {
- return value;
- }
- if (value.length === 1 || !(value[0] instanceof _primitives.Dict)) {
- return value[0];
- }
- return _primitives.Dict.merge({
- xref: this.xref,
- dictArray: value
- });
- }
- get content() {
- return this.pageDict.getArray("Contents");
- }
- get resources() {
- const resources = this._getInheritableProperty("Resources");
- return (0, _util.shadow)(this, "resources", resources instanceof _primitives.Dict ? resources : _primitives.Dict.empty);
- }
- _getBoundingBox(name) {
- if (this.xfaData) {
- return this.xfaData.bbox;
- }
- let box = this._getInheritableProperty(name, true);
- if (Array.isArray(box) && box.length === 4) {
- box = _util.Util.normalizeRect(box);
- if (box[2] - box[0] > 0 && box[3] - box[1] > 0) {
- return box;
- }
- (0, _util.warn)(`Empty, or invalid, /${name} entry.`);
- }
- return null;
- }
- get mediaBox() {
- return (0, _util.shadow)(this, "mediaBox", this._getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX);
- }
- get cropBox() {
- return (0, _util.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 (0, _util.shadow)(this, "userUnit", obj);
- }
- get view() {
- const {
- cropBox,
- mediaBox
- } = this;
- if (cropBox !== mediaBox && !(0, _util.isArrayEqual)(cropBox, mediaBox)) {
- const box = _util.Util.intersect(cropBox, mediaBox);
- if (box && box[2] - box[0] > 0 && box[3] - box[1] > 0) {
- return (0, _util.shadow)(this, "view", box);
- }
- (0, _util.warn)("Empty /CropBox and /MediaBox intersection.");
- }
- return (0, _util.shadow)(this, "view", mediaBox);
- }
- get rotate() {
- let rotate = this._getInheritableProperty("Rotate") || 0;
- if (rotate % 90 !== 0) {
- rotate = 0;
- } else if (rotate >= 360) {
- rotate %= 360;
- } else if (rotate < 0) {
- rotate = (rotate % 360 + 360) % 360;
- }
- return (0, _util.shadow)(this, "rotate", rotate);
- }
- _onSubStreamError(handler, reason, objId) {
- if (this.evaluatorOptions.ignoreErrors) {
- handler.send("UnsupportedFeature", {
- featureId: _util.UNSUPPORTED_FEATURES.errorContentSubStream
- });
- (0, _util.warn)(`getContentStream - ignoring sub-stream (${objId}): "${reason}".`);
- return;
- }
- throw reason;
- }
- getContentStream(handler) {
- return this.pdfManager.ensure(this, "content").then(content => {
- if (content instanceof _base_stream.BaseStream) {
- return content;
- }
- if (Array.isArray(content)) {
- return new _decode_stream.StreamsSequenceStream(content, this._onSubStreamError.bind(this, handler));
- }
- return new _stream.NullStream();
- });
- }
- get xfaData() {
- return (0, _util.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 _evaluator.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 _annotation.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);
- }
- (0, _writer.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 _evaluator.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 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) {
- (0, _util.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) {
- this.resourcesPromise = this.pdfManager.ensure(this, "resources");
- }
- return this.resourcesPromise.then(() => {
- const objectLoader = new _object_loader.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 _evaluator.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 ? (0, _core_utils.getNewAnnotationsMap)(annotationStorage) : null;
- let newAnnotationsPromise = Promise.resolve(null);
- if (newAnnotationsByPage) {
- const newAnnotations = newAnnotationsByPage.get(this.pageIndex);
- if (newAnnotations) {
- newAnnotationsPromise = _annotation.AnnotationFactory.printNewAnnotations(partialEvaluator, task, newAnnotations);
- }
- }
- const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
- const pageListPromise = dataPromises.then(([contentStream]) => {
- const opList = new _operator_list.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;
- });
- });
- return Promise.all([pageListPromise, this._parsedAnnotations, newAnnotationsPromise]).then(function ([pageOpList, annotations, newAnnotations]) {
- if (newAnnotations) {
- annotations = annotations.concat(newAnnotations);
- }
- if (annotations.length === 0 || intent & _util.RenderingIntentFlag.ANNOTATIONS_DISABLE) {
- pageOpList.flush(true);
- return {
- length: pageOpList.totalLength
- };
- }
- const renderForms = !!(intent & _util.RenderingIntentFlag.ANNOTATIONS_FORMS),
- intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
- intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
- intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
- 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) {
- (0, _util.warn)("getOperatorList - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
- return {
- opList: null,
- separateForm: false,
- separateCanvas: false
- };
- }));
- }
- }
- return Promise.all(opListPromises).then(function (opLists) {
- let form = false,
- canvas = false;
- for (const {
- opList,
- separateForm,
- separateCanvas
- } of opLists) {
- pageOpList.addOpList(opList);
- if (separateForm) {
- form = separateForm;
- }
- if (separateCanvas) {
- canvas = separateCanvas;
- }
- }
- pageOpList.flush(true, {
- form,
- canvas
- });
- 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 _evaluator.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;
- }
- _parseStructTree(structTreeRoot) {
- const tree = new _struct_tree.StructTreePage(structTreeRoot, this.pageDict);
- tree.parse();
- return tree;
- }
- async getAnnotationsData(handler, task, intent) {
- const annotations = await this._parsedAnnotations;
- if (annotations.length === 0) {
- return [];
- }
- const textContentPromises = [];
- const annotationsData = [];
- let partialEvaluator;
- const intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
- intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
- intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
- for (const annotation of annotations) {
- const isVisible = intentAny || intentDisplay && annotation.viewable;
- if (isVisible || intentPrint && annotation.printable) {
- annotationsData.push(annotation.data);
- }
- if (annotation.hasTextContent && isVisible) {
- if (!partialEvaluator) {
- partialEvaluator = new _evaluator.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
- });
- }
- textContentPromises.push(annotation.extractTextContent(partialEvaluator, task, this.view).catch(function (reason) {
- (0, _util.warn)(`getAnnotationsData - ignoring textContent during "${task.name}" task: "${reason}".`);
- }));
- }
- }
- await Promise.all(textContentPromises);
- return annotationsData;
- }
- get annotations() {
- const annots = this._getInheritableProperty("Annots");
- return (0, _util.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(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this._localIdFactory, false).catch(function (reason) {
- (0, _util.warn)(`_parsedAnnotations: "${reason}".`);
- return null;
- }));
- }
- return Promise.all(annotationPromises).then(function (annotations) {
- if (annotations.length === 0) {
- return annotations;
- }
- const sortedAnnotations = [];
- let popupAnnotations;
- for (const annotation of annotations) {
- if (!annotation) {
- continue;
- }
- if (annotation instanceof _annotation.PopupAnnotation) {
- if (!popupAnnotations) {
- popupAnnotations = [];
- }
- popupAnnotations.push(annotation);
- continue;
- }
- sortedAnnotations.push(annotation);
- }
- if (popupAnnotations) {
- sortedAnnotations.push(...popupAnnotations);
- }
- return sortedAnnotations;
- });
- });
- return (0, _util.shadow)(this, "_parsedAnnotations", parsedAnnotations);
- }
- get jsActions() {
- const actions = (0, _core_utils.collectActions)(this.xref, this.pageDict, _util.PageActionEventType);
- return (0, _util.shadow)(this, "jsActions", actions);
- }
- }
- exports.Page = Page;
- 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";
- function find(stream, signature, limit = 1024, backwards = false) {
- 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) {
- stream.pos += pos - signatureEnd;
- return true;
- }
- pos--;
- }
- } else {
- let pos = 0;
- while (pos <= scanLength) {
- let j = 0;
- while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
- j++;
- }
- if (j >= signatureLength) {
- stream.pos += pos;
- return true;
- }
- pos++;
- }
- }
- return false;
- }
- class PDFDocument {
- constructor(pdfManager, stream) {
- if (stream.length <= 0) {
- throw new _util.InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");
- }
- this.pdfManager = pdfManager;
- this.stream = stream;
- this.xref = new _xref.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() {
- (0, _util.unreachable)("Abstract method `createObjId` called.");
- }
- static getPageObjId() {
- (0, _util.unreachable)("Abstract method `getPageObjId` called.");
- }
- };
- }
- parse(recoveryMode) {
- this.xref.parse(recoveryMode);
- this.catalog = new _catalog.Catalog(this.pdfManager, this.xref);
- }
- get linearization() {
- let linearization = null;
- try {
- linearization = _parser.Linearization.create(this.stream);
- } catch (err) {
- if (err instanceof _core_utils.MissingDataException) {
- throw err;
- }
- (0, _util.info)(err);
- }
- return (0, _util.shadow)(this, "linearization", linearization);
- }
- get startXRef() {
- const stream = this.stream;
- let startXRef = 0;
- if (this.linearization) {
- stream.reset();
- if (find(stream, ENDOBJ_SIGNATURE)) {
- startXRef = stream.pos + 6 - stream.start;
- }
- } else {
- 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 ((0, _core_utils.isWhiteSpace)(ch));
- let str = "";
- while (ch >= 0x20 && ch <= 0x39) {
- str += String.fromCharCode(ch);
- ch = stream.getByte();
- }
- startXRef = parseInt(str, 10);
- if (isNaN(startXRef)) {
- startXRef = 0;
- }
- }
- }
- return (0, _util.shadow)(this, "startXRef", startXRef);
- }
- checkHeader() {
- const stream = this.stream;
- stream.reset();
- if (!find(stream, PDF_HEADER_SIGNATURE)) {
- return;
- }
- stream.moveStart();
- stream.skip(PDF_HEADER_SIGNATURE.length);
- let version = "",
- ch;
- while ((ch = stream.getByte()) > 0x20 && version.length < 7) {
- version += String.fromCharCode(ch);
- }
- if (_core_utils.PDF_VERSION_REGEXP.test(version)) {
- this._version = version;
- } else {
- (0, _util.warn)(`Invalid PDF header version: ${version}`);
- }
- }
- parseStartXRef() {
- this.xref.setStartXRef(this.startXRef);
- }
- get numPages() {
- let num = 0;
- if (this.catalog.hasActualNumPages) {
- num = this.catalog.numPages;
- } else if (this.xfaFactory) {
- num = this.xfaFactory.getNumPages();
- } else if (this.linearization) {
- num = this.linearization.numPages;
- } else {
- num = this.catalog.numPages;
- }
- return (0, _util.shadow)(this, "numPages", num);
- }
- _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 _primitives.Dict)) {
- return false;
- }
- if (field.has("Kids")) {
- if (++recursionDepth > RECURSION_LIMIT) {
- (0, _util.warn)("_hasOnlyDocumentSignatures: maximum recursion depth reached");
- return false;
- }
- return this._hasOnlyDocumentSignatures(field.get("Kids"), recursionDepth);
- }
- const isSignature = (0, _primitives.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 _base_stream.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 _base_stream.BaseStream) || data.isEmpty) {
- continue;
- }
- entries[name] = data;
- }
- return entries;
- }
- get xfaDatasets() {
- const streams = this._xfaStreams;
- if (!streams) {
- return (0, _util.shadow)(this, "xfaDatasets", null);
- }
- for (const key of ["datasets", "xdp:xdp"]) {
- const stream = streams[key];
- if (!stream) {
- continue;
- }
- try {
- const str = (0, _util.stringToUTF8String)(stream.getString());
- const data = {
- [key]: str
- };
- return (0, _util.shadow)(this, "xfaDatasets", new _dataset_reader.DatasetReader(data));
- } catch (_) {
- (0, _util.warn)("XFA - Invalid utf-8 string.");
- break;
- }
- }
- return (0, _util.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] = (0, _util.stringToUTF8String)(stream.getString());
- } catch (_) {
- (0, _util.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;
- }
- return (0, _util.shadow)(this, "xfaFactory", data ? new _factory.XFAFactory(data) : null);
- }
- get isPureXfa() {
- return this.xfaFactory ? this.xfaFactory.isValid() : false;
- }
- get htmlForXfa() {
- return this.xfaFactory ? this.xfaFactory.getPages() : null;
- }
- async loadXfaImages() {
- const xfaImagesDict = await this.pdfManager.ensureCatalog("xfaImages");
- if (!xfaImagesDict) {
- return;
- }
- const keys = xfaImagesDict.getKeys();
- const objectLoader = new _object_loader.ObjectLoader(xfaImagesDict, keys, this.xref);
- await objectLoader.load();
- const xfaImages = new Map();
- for (const key of keys) {
- const stream = xfaImagesDict.get(key);
- if (stream instanceof _base_stream.BaseStream) {
- xfaImages.set(key, stream.getBytes());
- }
- }
- this.xfaFactory.setImages(xfaImages);
- }
- async loadXfaFonts(handler, task) {
- const acroForm = await this.pdfManager.ensureCatalog("acroForm");
- if (!acroForm) {
- return;
- }
- const resources = await acroForm.getAsync("DR");
- if (!(resources instanceof _primitives.Dict)) {
- return;
- }
- const objectLoader = new _object_loader.ObjectLoader(resources, ["Font"], this.xref);
- await objectLoader.load();
- const fontRes = resources.get("Font");
- if (!(fontRes instanceof _primitives.Dict)) {
- return;
- }
- const options = Object.assign(Object.create(null), this.pdfManager.evaluatorOptions);
- options.useSystemFonts = false;
- const partialEvaluator = new _evaluator.PartialEvaluator({
- xref: this.xref,
- handler,
- pageIndex: -1,
- idFactory: this._globalIdFactory,
- fontCache: this.catalog.fontCache,
- builtInCMapCache: this.catalog.builtInCMapCache,
- standardFontDataCache: this.catalog.standardFontDataCache,
- options
- });
- const operatorList = new _operator_list.OperatorList();
- const pdfFonts = [];
- const initialState = {
- get font() {
- return pdfFonts.at(-1);
- },
- set font(font) {
- pdfFonts.push(font);
- },
- clone() {
- return this;
- }
- };
- const fonts = new Map();
- fontRes.forEach((fontName, font) => {
- fonts.set(fontName, font);
- });
- const promises = [];
- for (const [fontName, font] of fonts) {
- const descriptor = font.get("FontDescriptor");
- if (!(descriptor instanceof _primitives.Dict)) {
- continue;
- }
- let fontFamily = descriptor.get("FontFamily");
- fontFamily = fontFamily.replace(/[ ]+(\d)/g, "$1");
- const fontWeight = descriptor.get("FontWeight");
- const italicAngle = -descriptor.get("ItalicAngle");
- const cssFontInfo = {
- fontFamily,
- fontWeight,
- italicAngle
- };
- if (!(0, _core_utils.validateCSSFont)(cssFontInfo)) {
- continue;
- }
- promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(fontName), 1], null, operatorList, task, initialState, null, cssFontInfo).catch(function (reason) {
- (0, _util.warn)(`loadXfaFonts: "${reason}".`);
- return null;
- }));
- }
- await Promise.all(promises);
- const missingFonts = this.xfaFactory.setFonts(pdfFonts);
- if (!missingFonts) {
- return;
- }
- options.ignoreErrors = true;
- promises.length = 0;
- pdfFonts.length = 0;
- const reallyMissingFonts = new Set();
- for (const missing of missingFonts) {
- if (!(0, _xfa_fonts.getXfaFontName)(`${missing}-Regular`)) {
- reallyMissingFonts.add(missing);
- }
- }
- if (reallyMissingFonts.size) {
- missingFonts.push("PdfJS-Fallback");
- }
- for (const missing of missingFonts) {
- if (reallyMissingFonts.has(missing)) {
- continue;
- }
- for (const fontInfo of [{
- name: "Regular",
- fontWeight: 400,
- italicAngle: 0
- }, {
- name: "Bold",
- fontWeight: 700,
- italicAngle: 0
- }, {
- name: "Italic",
- fontWeight: 400,
- italicAngle: 12
- }, {
- name: "BoldItalic",
- fontWeight: 700,
- italicAngle: 12
- }]) {
- const name = `${missing}-${fontInfo.name}`;
- const dict = (0, _xfa_fonts.getXfaFontDict)(name);
- promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(name), 1], null, operatorList, task, initialState, dict, {
- fontFamily: missing,
- fontWeight: fontInfo.fontWeight,
- italicAngle: fontInfo.italicAngle
- }).catch(function (reason) {
- (0, _util.warn)(`loadXfaFonts: "${reason}".`);
- return null;
- }));
- }
- }
- await Promise.all(promises);
- this.xfaFactory.appendFonts(pdfFonts, reallyMissingFonts);
- }
- async serializeXfaData(annotationStorage) {
- return this.xfaFactory ? this.xfaFactory.serializeData(annotationStorage) : null;
- }
- get version() {
- return this.catalog.version || this._version;
- }
- get formInfo() {
- const formInfo = {
- hasFields: false,
- hasAcroForm: false,
- hasXfa: false,
- hasSignatures: false
- };
- const acroForm = this.catalog.acroForm;
- if (!acroForm) {
- return (0, _util.shadow)(this, "formInfo", formInfo);
- }
- try {
- const fields = acroForm.get("Fields");
- const hasFields = Array.isArray(fields) && fields.length > 0;
- formInfo.hasFields = hasFields;
- const xfa = acroForm.get("XFA");
- formInfo.hasXfa = Array.isArray(xfa) && xfa.length > 0 || xfa instanceof _base_stream.BaseStream && !xfa.isEmpty;
- const sigFlags = acroForm.get("SigFlags");
- const hasSignatures = !!(sigFlags & 0x1);
- const hasOnlyDocumentSignatures = hasSignatures && this._hasOnlyDocumentSignatures(fields);
- formInfo.hasAcroForm = hasFields && !hasOnlyDocumentSignatures;
- formInfo.hasSignatures = hasSignatures;
- } catch (ex) {
- if (ex instanceof _core_utils.MissingDataException) {
- throw ex;
- }
- (0, _util.warn)(`Cannot fetch form information: "${ex}".`);
- }
- return (0, _util.shadow)(this, "formInfo", formInfo);
- }
- get documentInfo() {
- const docInfo = {
- PDFFormatVersion: this.version,
- Language: this.catalog.lang,
- EncryptFilterName: this.xref.encrypt ? this.xref.encrypt.filterName : null,
- IsLinearized: !!this.linearization,
- IsAcroFormPresent: this.formInfo.hasAcroForm,
- IsXFAPresent: this.formInfo.hasXfa,
- IsCollectionPresent: !!this.catalog.collection,
- IsSignaturesPresent: this.formInfo.hasSignatures
- };
- let infoDict;
- try {
- infoDict = this.xref.trailer.get("Info");
- } catch (err) {
- if (err instanceof _core_utils.MissingDataException) {
- throw err;
- }
- (0, _util.info)("The document information dictionary is invalid.");
- }
- if (!(infoDict instanceof _primitives.Dict)) {
- return (0, _util.shadow)(this, "documentInfo", docInfo);
- }
- for (const key of infoDict.getKeys()) {
- const value = infoDict.get(key);
- switch (key) {
- case "Title":
- case "Author":
- case "Subject":
- case "Keywords":
- case "Creator":
- case "Producer":
- case "CreationDate":
- case "ModDate":
- if (typeof value === "string") {
- docInfo[key] = (0, _util.stringToPDFString)(value);
- continue;
- }
- break;
- case "Trapped":
- if (value instanceof _primitives.Name) {
- docInfo[key] = value;
- continue;
- }
- break;
- default:
- let customValue;
- switch (typeof value) {
- case "string":
- customValue = (0, _util.stringToPDFString)(value);
- break;
- case "number":
- case "boolean":
- customValue = value;
- break;
- default:
- if (value instanceof _primitives.Name) {
- customValue = value;
- }
- break;
- }
- if (customValue === undefined) {
- (0, _util.warn)(`Bad value, for custom key "${key}", in Info: ${value}.`);
- continue;
- }
- if (!docInfo.Custom) {
- docInfo.Custom = Object.create(null);
- }
- docInfo.Custom[key] = customValue;
- continue;
- }
- (0, _util.warn)(`Bad value, for key "${key}", in Info: ${value}.`);
- }
- return (0, _util.shadow)(this, "documentInfo", docInfo);
- }
- get fingerprints() {
- function validate(data) {
- return typeof data === "string" && data.length > 0 && data !== EMPTY_FINGERPRINT;
- }
- function hexString(hash) {
- const buf = [];
- for (const num of hash) {
- const hex = num.toString(16);
- buf.push(hex.padStart(2, "0"));
- }
- return buf.join("");
- }
- const idArray = this.xref.trailer.get("ID");
- let hashOriginal, hashModified;
- if (Array.isArray(idArray) && validate(idArray[0])) {
- hashOriginal = (0, _util.stringToBytes)(idArray[0]);
- if (idArray[1] !== idArray[0] && validate(idArray[1])) {
- hashModified = (0, _util.stringToBytes)(idArray[1]);
- }
- } else {
- hashOriginal = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
- }
- return (0, _util.shadow)(this, "fingerprints", [hexString(hashOriginal), hashModified ? hexString(hashModified) : null]);
- }
- async _getLinearizationPage(pageIndex) {
- const {
- catalog,
- linearization,
- xref
- } = this;
- const ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
- try {
- const obj = await xref.fetchAsync(ref);
- if (obj instanceof _primitives.Dict) {
- let type = obj.getRaw("Type");
- if (type instanceof _primitives.Ref) {
- type = await xref.fetchAsync(type);
- }
- if ((0, _primitives.isName)(type, "Page") || !obj.has("Type") && !obj.has("Kids")) {
- if (!catalog.pageKidsCountCache.has(ref)) {
- catalog.pageKidsCountCache.put(ref, 1);
- }
- if (!catalog.pageIndexCache.has(ref)) {
- catalog.pageIndexCache.put(ref, 0);
- }
- return [obj, ref];
- }
- }
- throw new _util.FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.");
- } catch (reason) {
- (0, _util.warn)(`_getLinearizationPage: "${reason.message}".`);
- return catalog.getPageDict(pageIndex);
- }
- }
- getPage(pageIndex) {
- const cachedPromise = this._pagePromises.get(pageIndex);
- if (cachedPromise) {
- return cachedPromise;
- }
- const {
- catalog,
- linearization,
- xfaFactory
- } = this;
- let promise;
- if (xfaFactory) {
- promise = Promise.resolve([_primitives.Dict.empty, null]);
- } else if (linearization && linearization.pageFirst === pageIndex) {
- promise = this._getLinearizationPage(pageIndex);
- } else {
- promise = catalog.getPageDict(pageIndex);
- }
- promise = promise.then(([pageDict, ref]) => {
- return new Page({
- pdfManager: this.pdfManager,
- xref: this.xref,
- pageIndex,
- pageDict,
- ref,
- globalIdFactory: this._globalIdFactory,
- fontCache: catalog.fontCache,
- builtInCMapCache: catalog.builtInCMapCache,
- standardFontDataCache: catalog.standardFontDataCache,
- globalImageCache: catalog.globalImageCache,
- nonBlendModesSet: catalog.nonBlendModesSet,
- xfaFactory
- });
- });
- this._pagePromises.set(pageIndex, promise);
- return promise;
- }
- async checkFirstPage(recoveryMode = false) {
- if (recoveryMode) {
- return;
- }
- try {
- await this.getPage(0);
- } catch (reason) {
- if (reason instanceof _core_utils.XRefEntryException) {
- this._pagePromises.delete(0);
- await this.cleanup();
- throw new _core_utils.XRefParseException();
- }
- }
- }
- async checkLastPage(recoveryMode = false) {
- const {
- catalog,
- pdfManager
- } = this;
- catalog.setActualNumPages();
- let numPages;
- try {
- await Promise.all([pdfManager.ensureDoc("xfaFactory"), pdfManager.ensureDoc("linearization"), pdfManager.ensureCatalog("numPages")]);
- if (this.xfaFactory) {
- return;
- } else if (this.linearization) {
- numPages = this.linearization.numPages;
- } else {
- numPages = catalog.numPages;
- }
- if (!Number.isInteger(numPages)) {
- throw new _util.FormatError("Page count is not an integer.");
- } else if (numPages <= 1) {
- return;
- }
- await this.getPage(numPages - 1);
- } catch (reason) {
- this._pagePromises.delete(numPages - 1);
- await this.cleanup();
- if (reason instanceof _core_utils.XRefEntryException && !recoveryMode) {
- throw new _core_utils.XRefParseException();
- }
- (0, _util.warn)(`checkLastPage - invalid /Pages tree /Count: ${numPages}.`);
- let pagesTree;
- try {
- pagesTree = await catalog.getAllPageDicts(recoveryMode);
- } catch (reasonAll) {
- if (reasonAll instanceof _core_utils.XRefEntryException && !recoveryMode) {
- throw new _core_utils.XRefParseException();
- }
- catalog.setActualNumPages(1);
- return;
- }
- for (const [pageIndex, [pageDict, ref]] of pagesTree) {
- let promise;
- if (pageDict instanceof Error) {
- promise = Promise.reject(pageDict);
- promise.catch(() => {});
- } else {
- promise = Promise.resolve(new Page({
- pdfManager,
- xref: this.xref,
- pageIndex,
- pageDict,
- ref,
- globalIdFactory: this._globalIdFactory,
- fontCache: catalog.fontCache,
- builtInCMapCache: catalog.builtInCMapCache,
- standardFontDataCache: catalog.standardFontDataCache,
- globalImageCache: catalog.globalImageCache,
- nonBlendModesSet: catalog.nonBlendModesSet,
- xfaFactory: null
- }));
- }
- this._pagePromises.set(pageIndex, promise);
- }
- catalog.setActualNumPages(pagesTree.size);
- }
- }
- fontFallback(id, handler) {
- return this.catalog.fontFallback(id, handler);
- }
- async cleanup(manuallyTriggered = false) {
- return this.catalog ? this.catalog.cleanup(manuallyTriggered) : (0, _cleanup_helper.clearGlobalCaches)();
- }
- _collectFieldObjects(name, fieldRef, promises) {
- const field = this.xref.fetchIfRef(fieldRef);
- if (field.has("T")) {
- const partName = (0, _util.stringToPDFString)(field.get("T"));
- if (name === "") {
- name = partName;
- } else {
- name = `${name}.${partName}`;
- }
- }
- if (!promises.has(name)) {
- promises.set(name, []);
- }
- promises.get(name).push(_annotation.AnnotationFactory.create(this.xref, fieldRef, this.pdfManager, this._localIdFactory, true).then(annotation => annotation && annotation.getFieldObject()).catch(function (reason) {
- (0, _util.warn)(`_collectFieldObjects: "${reason}".`);
- return null;
- }));
- if (field.has("Kids")) {
- const kids = field.get("Kids");
- for (const kid of kids) {
- this._collectFieldObjects(name, kid, promises);
- }
- }
- }
- get fieldObjects() {
- if (!this.formInfo.hasFields) {
- return (0, _util.shadow)(this, "fieldObjects", Promise.resolve(null));
- }
- const allFields = Object.create(null);
- const fieldPromises = new Map();
- for (const fieldRef of this.catalog.acroForm.get("Fields")) {
- this._collectFieldObjects("", fieldRef, fieldPromises);
- }
- const allPromises = [];
- for (const [name, promises] of fieldPromises) {
- allPromises.push(Promise.all(promises).then(fields => {
- fields = fields.filter(field => !!field);
- if (fields.length > 0) {
- allFields[name] = fields;
- }
- }));
- }
- return (0, _util.shadow)(this, "fieldObjects", Promise.all(allPromises).then(() => allFields));
- }
- get hasJSActions() {
- const promise = this.pdfManager.ensureDoc("_parseHasJSActions");
- return (0, _util.shadow)(this, "hasJSActions", promise);
- }
- async _parseHasJSActions() {
- const [catalogJsActions, fieldObjects] = await Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]);
- if (catalogJsActions) {
- return true;
- }
- if (fieldObjects) {
- return Object.values(fieldObjects).some(fieldObject => fieldObject.some(object => object.actions !== null));
- }
- return false;
- }
- get calculationOrderIds() {
- const acroForm = this.catalog.acroForm;
- if (!acroForm || !acroForm.has("CO")) {
- return (0, _util.shadow)(this, "calculationOrderIds", null);
- }
- const calculationOrder = acroForm.get("CO");
- if (!Array.isArray(calculationOrder) || calculationOrder.length === 0) {
- return (0, _util.shadow)(this, "calculationOrderIds", null);
- }
- const ids = [];
- for (const id of calculationOrder) {
- if (id instanceof _primitives.Ref) {
- ids.push(id.toString());
- }
- }
- if (ids.length === 0) {
- return (0, _util.shadow)(this, "calculationOrderIds", null);
- }
- return (0, _util.shadow)(this, "calculationOrderIds", ids);
- }
- }
- exports.PDFDocument = PDFDocument;
|