2
0

document.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.Page = exports.PDFDocument = void 0;
  27. var _annotation = require("./annotation.js");
  28. var _util = require("../shared/util.js");
  29. var _core_utils = require("./core_utils.js");
  30. var _primitives = require("./primitives.js");
  31. var _xfa_fonts = require("./xfa_fonts.js");
  32. var _base_stream = require("./base_stream.js");
  33. var _crypto = require("./crypto.js");
  34. var _catalog = require("./catalog.js");
  35. var _cleanup_helper = require("./cleanup_helper.js");
  36. var _dataset_reader = require("./dataset_reader.js");
  37. var _parser = require("./parser.js");
  38. var _stream = require("./stream.js");
  39. var _object_loader = require("./object_loader.js");
  40. var _operator_list = require("./operator_list.js");
  41. var _evaluator = require("./evaluator.js");
  42. var _decode_stream = require("./decode_stream.js");
  43. var _struct_tree = require("./struct_tree.js");
  44. var _writer = require("./writer.js");
  45. var _factory = require("./xfa/factory.js");
  46. var _xref = require("./xref.js");
  47. const DEFAULT_USER_UNIT = 1.0;
  48. const LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  49. class Page {
  50. constructor({
  51. pdfManager,
  52. xref,
  53. pageIndex,
  54. pageDict,
  55. ref,
  56. globalIdFactory,
  57. fontCache,
  58. builtInCMapCache,
  59. standardFontDataCache,
  60. globalImageCache,
  61. nonBlendModesSet,
  62. xfaFactory
  63. }) {
  64. this.pdfManager = pdfManager;
  65. this.pageIndex = pageIndex;
  66. this.pageDict = pageDict;
  67. this.xref = xref;
  68. this.ref = ref;
  69. this.fontCache = fontCache;
  70. this.builtInCMapCache = builtInCMapCache;
  71. this.standardFontDataCache = standardFontDataCache;
  72. this.globalImageCache = globalImageCache;
  73. this.nonBlendModesSet = nonBlendModesSet;
  74. this.evaluatorOptions = pdfManager.evaluatorOptions;
  75. this.resourcesPromise = null;
  76. this.xfaFactory = xfaFactory;
  77. const idCounters = {
  78. obj: 0
  79. };
  80. this._localIdFactory = class extends globalIdFactory {
  81. static createObjId() {
  82. return `p${pageIndex}_${++idCounters.obj}`;
  83. }
  84. static getPageObjId() {
  85. return `page${ref.toString()}`;
  86. }
  87. };
  88. }
  89. _getInheritableProperty(key, getArray = false) {
  90. const value = (0, _core_utils.getInheritableProperty)({
  91. dict: this.pageDict,
  92. key,
  93. getArray,
  94. stopWhenFound: false
  95. });
  96. if (!Array.isArray(value)) {
  97. return value;
  98. }
  99. if (value.length === 1 || !(value[0] instanceof _primitives.Dict)) {
  100. return value[0];
  101. }
  102. return _primitives.Dict.merge({
  103. xref: this.xref,
  104. dictArray: value
  105. });
  106. }
  107. get content() {
  108. return this.pageDict.getArray("Contents");
  109. }
  110. get resources() {
  111. const resources = this._getInheritableProperty("Resources");
  112. return (0, _util.shadow)(this, "resources", resources instanceof _primitives.Dict ? resources : _primitives.Dict.empty);
  113. }
  114. _getBoundingBox(name) {
  115. if (this.xfaData) {
  116. return this.xfaData.bbox;
  117. }
  118. let box = this._getInheritableProperty(name, true);
  119. if (Array.isArray(box) && box.length === 4) {
  120. box = _util.Util.normalizeRect(box);
  121. if (box[2] - box[0] > 0 && box[3] - box[1] > 0) {
  122. return box;
  123. }
  124. (0, _util.warn)(`Empty, or invalid, /${name} entry.`);
  125. }
  126. return null;
  127. }
  128. get mediaBox() {
  129. return (0, _util.shadow)(this, "mediaBox", this._getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX);
  130. }
  131. get cropBox() {
  132. return (0, _util.shadow)(this, "cropBox", this._getBoundingBox("CropBox") || this.mediaBox);
  133. }
  134. get userUnit() {
  135. let obj = this.pageDict.get("UserUnit");
  136. if (typeof obj !== "number" || obj <= 0) {
  137. obj = DEFAULT_USER_UNIT;
  138. }
  139. return (0, _util.shadow)(this, "userUnit", obj);
  140. }
  141. get view() {
  142. const {
  143. cropBox,
  144. mediaBox
  145. } = this;
  146. if (cropBox !== mediaBox && !(0, _util.isArrayEqual)(cropBox, mediaBox)) {
  147. const box = _util.Util.intersect(cropBox, mediaBox);
  148. if (box && box[2] - box[0] > 0 && box[3] - box[1] > 0) {
  149. return (0, _util.shadow)(this, "view", box);
  150. }
  151. (0, _util.warn)("Empty /CropBox and /MediaBox intersection.");
  152. }
  153. return (0, _util.shadow)(this, "view", mediaBox);
  154. }
  155. get rotate() {
  156. let rotate = this._getInheritableProperty("Rotate") || 0;
  157. if (rotate % 90 !== 0) {
  158. rotate = 0;
  159. } else if (rotate >= 360) {
  160. rotate %= 360;
  161. } else if (rotate < 0) {
  162. rotate = (rotate % 360 + 360) % 360;
  163. }
  164. return (0, _util.shadow)(this, "rotate", rotate);
  165. }
  166. _onSubStreamError(handler, reason, objId) {
  167. if (this.evaluatorOptions.ignoreErrors) {
  168. handler.send("UnsupportedFeature", {
  169. featureId: _util.UNSUPPORTED_FEATURES.errorContentSubStream
  170. });
  171. (0, _util.warn)(`getContentStream - ignoring sub-stream (${objId}): "${reason}".`);
  172. return;
  173. }
  174. throw reason;
  175. }
  176. getContentStream(handler) {
  177. return this.pdfManager.ensure(this, "content").then(content => {
  178. if (content instanceof _base_stream.BaseStream) {
  179. return content;
  180. }
  181. if (Array.isArray(content)) {
  182. return new _decode_stream.StreamsSequenceStream(content, this._onSubStreamError.bind(this, handler));
  183. }
  184. return new _stream.NullStream();
  185. });
  186. }
  187. get xfaData() {
  188. return (0, _util.shadow)(this, "xfaData", this.xfaFactory ? {
  189. bbox: this.xfaFactory.getBoundingBox(this.pageIndex)
  190. } : null);
  191. }
  192. async saveNewAnnotations(handler, task, annotations) {
  193. if (this.xfaFactory) {
  194. throw new Error("XFA: Cannot save new annotations.");
  195. }
  196. const partialEvaluator = new _evaluator.PartialEvaluator({
  197. xref: this.xref,
  198. handler,
  199. pageIndex: this.pageIndex,
  200. idFactory: this._localIdFactory,
  201. fontCache: this.fontCache,
  202. builtInCMapCache: this.builtInCMapCache,
  203. standardFontDataCache: this.standardFontDataCache,
  204. globalImageCache: this.globalImageCache,
  205. options: this.evaluatorOptions
  206. });
  207. const pageDict = this.pageDict;
  208. const annotationsArray = this.annotations.slice();
  209. const newData = await _annotation.AnnotationFactory.saveNewAnnotations(partialEvaluator, task, annotations);
  210. for (const {
  211. ref
  212. } of newData.annotations) {
  213. annotationsArray.push(ref);
  214. }
  215. const savedDict = pageDict.get("Annots");
  216. pageDict.set("Annots", annotationsArray);
  217. const buffer = [];
  218. let transform = null;
  219. if (this.xref.encrypt) {
  220. transform = this.xref.encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  221. }
  222. (0, _writer.writeObject)(this.ref, pageDict, buffer, transform);
  223. if (savedDict) {
  224. pageDict.set("Annots", savedDict);
  225. }
  226. const objects = newData.dependencies;
  227. objects.push({
  228. ref: this.ref,
  229. data: buffer.join("")
  230. }, ...newData.annotations);
  231. return objects;
  232. }
  233. save(handler, task, annotationStorage) {
  234. const partialEvaluator = new _evaluator.PartialEvaluator({
  235. xref: this.xref,
  236. handler,
  237. pageIndex: this.pageIndex,
  238. idFactory: this._localIdFactory,
  239. fontCache: this.fontCache,
  240. builtInCMapCache: this.builtInCMapCache,
  241. standardFontDataCache: this.standardFontDataCache,
  242. globalImageCache: this.globalImageCache,
  243. options: this.evaluatorOptions
  244. });
  245. return this._parsedAnnotations.then(function (annotations) {
  246. const newRefsPromises = [];
  247. for (const annotation of annotations) {
  248. if (!annotation.mustBePrinted(annotationStorage)) {
  249. continue;
  250. }
  251. newRefsPromises.push(annotation.save(partialEvaluator, task, annotationStorage).catch(function (reason) {
  252. (0, _util.warn)("save - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
  253. return null;
  254. }));
  255. }
  256. return Promise.all(newRefsPromises).then(function (newRefs) {
  257. return newRefs.filter(newRef => !!newRef);
  258. });
  259. });
  260. }
  261. loadResources(keys) {
  262. if (!this.resourcesPromise) {
  263. this.resourcesPromise = this.pdfManager.ensure(this, "resources");
  264. }
  265. return this.resourcesPromise.then(() => {
  266. const objectLoader = new _object_loader.ObjectLoader(this.resources, keys, this.xref);
  267. return objectLoader.load();
  268. });
  269. }
  270. getOperatorList({
  271. handler,
  272. sink,
  273. task,
  274. intent,
  275. cacheKey,
  276. annotationStorage = null
  277. }) {
  278. const contentStreamPromise = this.getContentStream(handler);
  279. const resourcesPromise = this.loadResources(["ColorSpace", "ExtGState", "Font", "Pattern", "Properties", "Shading", "XObject"]);
  280. const partialEvaluator = new _evaluator.PartialEvaluator({
  281. xref: this.xref,
  282. handler,
  283. pageIndex: this.pageIndex,
  284. idFactory: this._localIdFactory,
  285. fontCache: this.fontCache,
  286. builtInCMapCache: this.builtInCMapCache,
  287. standardFontDataCache: this.standardFontDataCache,
  288. globalImageCache: this.globalImageCache,
  289. options: this.evaluatorOptions
  290. });
  291. const newAnnotationsByPage = !this.xfaFactory ? (0, _core_utils.getNewAnnotationsMap)(annotationStorage) : null;
  292. let newAnnotationsPromise = Promise.resolve(null);
  293. if (newAnnotationsByPage) {
  294. const newAnnotations = newAnnotationsByPage.get(this.pageIndex);
  295. if (newAnnotations) {
  296. newAnnotationsPromise = _annotation.AnnotationFactory.printNewAnnotations(partialEvaluator, task, newAnnotations);
  297. }
  298. }
  299. const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  300. const pageListPromise = dataPromises.then(([contentStream]) => {
  301. const opList = new _operator_list.OperatorList(intent, sink);
  302. handler.send("StartRenderPage", {
  303. transparency: partialEvaluator.hasBlendModes(this.resources, this.nonBlendModesSet),
  304. pageIndex: this.pageIndex,
  305. cacheKey
  306. });
  307. return partialEvaluator.getOperatorList({
  308. stream: contentStream,
  309. task,
  310. resources: this.resources,
  311. operatorList: opList
  312. }).then(function () {
  313. return opList;
  314. });
  315. });
  316. return Promise.all([pageListPromise, this._parsedAnnotations, newAnnotationsPromise]).then(function ([pageOpList, annotations, newAnnotations]) {
  317. if (newAnnotations) {
  318. annotations = annotations.concat(newAnnotations);
  319. }
  320. if (annotations.length === 0 || intent & _util.RenderingIntentFlag.ANNOTATIONS_DISABLE) {
  321. pageOpList.flush(true);
  322. return {
  323. length: pageOpList.totalLength
  324. };
  325. }
  326. const renderForms = !!(intent & _util.RenderingIntentFlag.ANNOTATIONS_FORMS),
  327. intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
  328. intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
  329. intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
  330. const opListPromises = [];
  331. for (const annotation of annotations) {
  332. if (intentAny || intentDisplay && annotation.mustBeViewed(annotationStorage) || intentPrint && annotation.mustBePrinted(annotationStorage)) {
  333. opListPromises.push(annotation.getOperatorList(partialEvaluator, task, intent, renderForms, annotationStorage).catch(function (reason) {
  334. (0, _util.warn)("getOperatorList - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
  335. return {
  336. opList: null,
  337. separateForm: false,
  338. separateCanvas: false
  339. };
  340. }));
  341. }
  342. }
  343. return Promise.all(opListPromises).then(function (opLists) {
  344. let form = false,
  345. canvas = false;
  346. for (const {
  347. opList,
  348. separateForm,
  349. separateCanvas
  350. } of opLists) {
  351. pageOpList.addOpList(opList);
  352. if (separateForm) {
  353. form = separateForm;
  354. }
  355. if (separateCanvas) {
  356. canvas = separateCanvas;
  357. }
  358. }
  359. pageOpList.flush(true, {
  360. form,
  361. canvas
  362. });
  363. return {
  364. length: pageOpList.totalLength
  365. };
  366. });
  367. });
  368. }
  369. extractTextContent({
  370. handler,
  371. task,
  372. includeMarkedContent,
  373. sink,
  374. combineTextItems
  375. }) {
  376. const contentStreamPromise = this.getContentStream(handler);
  377. const resourcesPromise = this.loadResources(["ExtGState", "Font", "Properties", "XObject"]);
  378. const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  379. return dataPromises.then(([contentStream]) => {
  380. const partialEvaluator = new _evaluator.PartialEvaluator({
  381. xref: this.xref,
  382. handler,
  383. pageIndex: this.pageIndex,
  384. idFactory: this._localIdFactory,
  385. fontCache: this.fontCache,
  386. builtInCMapCache: this.builtInCMapCache,
  387. standardFontDataCache: this.standardFontDataCache,
  388. globalImageCache: this.globalImageCache,
  389. options: this.evaluatorOptions
  390. });
  391. return partialEvaluator.getTextContent({
  392. stream: contentStream,
  393. task,
  394. resources: this.resources,
  395. includeMarkedContent,
  396. combineTextItems,
  397. sink,
  398. viewBox: this.view
  399. });
  400. });
  401. }
  402. async getStructTree() {
  403. const structTreeRoot = await this.pdfManager.ensureCatalog("structTreeRoot");
  404. if (!structTreeRoot) {
  405. return null;
  406. }
  407. const structTree = await this.pdfManager.ensure(this, "_parseStructTree", [structTreeRoot]);
  408. return structTree.serializable;
  409. }
  410. _parseStructTree(structTreeRoot) {
  411. const tree = new _struct_tree.StructTreePage(structTreeRoot, this.pageDict);
  412. tree.parse();
  413. return tree;
  414. }
  415. async getAnnotationsData(handler, task, intent) {
  416. const annotations = await this._parsedAnnotations;
  417. if (annotations.length === 0) {
  418. return [];
  419. }
  420. const textContentPromises = [];
  421. const annotationsData = [];
  422. let partialEvaluator;
  423. const intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
  424. intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
  425. intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
  426. for (const annotation of annotations) {
  427. const isVisible = intentAny || intentDisplay && annotation.viewable;
  428. if (isVisible || intentPrint && annotation.printable) {
  429. annotationsData.push(annotation.data);
  430. }
  431. if (annotation.hasTextContent && isVisible) {
  432. if (!partialEvaluator) {
  433. partialEvaluator = new _evaluator.PartialEvaluator({
  434. xref: this.xref,
  435. handler,
  436. pageIndex: this.pageIndex,
  437. idFactory: this._localIdFactory,
  438. fontCache: this.fontCache,
  439. builtInCMapCache: this.builtInCMapCache,
  440. standardFontDataCache: this.standardFontDataCache,
  441. globalImageCache: this.globalImageCache,
  442. options: this.evaluatorOptions
  443. });
  444. }
  445. textContentPromises.push(annotation.extractTextContent(partialEvaluator, task, this.view).catch(function (reason) {
  446. (0, _util.warn)(`getAnnotationsData - ignoring textContent during "${task.name}" task: "${reason}".`);
  447. }));
  448. }
  449. }
  450. await Promise.all(textContentPromises);
  451. return annotationsData;
  452. }
  453. get annotations() {
  454. const annots = this._getInheritableProperty("Annots");
  455. return (0, _util.shadow)(this, "annotations", Array.isArray(annots) ? annots : []);
  456. }
  457. get _parsedAnnotations() {
  458. const parsedAnnotations = this.pdfManager.ensure(this, "annotations").then(() => {
  459. const annotationPromises = [];
  460. for (const annotationRef of this.annotations) {
  461. annotationPromises.push(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this._localIdFactory, false).catch(function (reason) {
  462. (0, _util.warn)(`_parsedAnnotations: "${reason}".`);
  463. return null;
  464. }));
  465. }
  466. return Promise.all(annotationPromises).then(function (annotations) {
  467. if (annotations.length === 0) {
  468. return annotations;
  469. }
  470. const sortedAnnotations = [];
  471. let popupAnnotations;
  472. for (const annotation of annotations) {
  473. if (!annotation) {
  474. continue;
  475. }
  476. if (annotation instanceof _annotation.PopupAnnotation) {
  477. if (!popupAnnotations) {
  478. popupAnnotations = [];
  479. }
  480. popupAnnotations.push(annotation);
  481. continue;
  482. }
  483. sortedAnnotations.push(annotation);
  484. }
  485. if (popupAnnotations) {
  486. sortedAnnotations.push(...popupAnnotations);
  487. }
  488. return sortedAnnotations;
  489. });
  490. });
  491. return (0, _util.shadow)(this, "_parsedAnnotations", parsedAnnotations);
  492. }
  493. get jsActions() {
  494. const actions = (0, _core_utils.collectActions)(this.xref, this.pageDict, _util.PageActionEventType);
  495. return (0, _util.shadow)(this, "jsActions", actions);
  496. }
  497. }
  498. exports.Page = Page;
  499. const PDF_HEADER_SIGNATURE = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]);
  500. const STARTXREF_SIGNATURE = new Uint8Array([0x73, 0x74, 0x61, 0x72, 0x74, 0x78, 0x72, 0x65, 0x66]);
  501. const ENDOBJ_SIGNATURE = new Uint8Array([0x65, 0x6e, 0x64, 0x6f, 0x62, 0x6a]);
  502. const FINGERPRINT_FIRST_BYTES = 1024;
  503. const EMPTY_FINGERPRINT = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
  504. function find(stream, signature, limit = 1024, backwards = false) {
  505. const signatureLength = signature.length;
  506. const scanBytes = stream.peekBytes(limit);
  507. const scanLength = scanBytes.length - signatureLength;
  508. if (scanLength <= 0) {
  509. return false;
  510. }
  511. if (backwards) {
  512. const signatureEnd = signatureLength - 1;
  513. let pos = scanBytes.length - 1;
  514. while (pos >= signatureEnd) {
  515. let j = 0;
  516. while (j < signatureLength && scanBytes[pos - j] === signature[signatureEnd - j]) {
  517. j++;
  518. }
  519. if (j >= signatureLength) {
  520. stream.pos += pos - signatureEnd;
  521. return true;
  522. }
  523. pos--;
  524. }
  525. } else {
  526. let pos = 0;
  527. while (pos <= scanLength) {
  528. let j = 0;
  529. while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
  530. j++;
  531. }
  532. if (j >= signatureLength) {
  533. stream.pos += pos;
  534. return true;
  535. }
  536. pos++;
  537. }
  538. }
  539. return false;
  540. }
  541. class PDFDocument {
  542. constructor(pdfManager, stream) {
  543. if (stream.length <= 0) {
  544. throw new _util.InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");
  545. }
  546. this.pdfManager = pdfManager;
  547. this.stream = stream;
  548. this.xref = new _xref.XRef(stream, pdfManager);
  549. this._pagePromises = new Map();
  550. this._version = null;
  551. const idCounters = {
  552. font: 0
  553. };
  554. this._globalIdFactory = class {
  555. static getDocId() {
  556. return `g_${pdfManager.docId}`;
  557. }
  558. static createFontId() {
  559. return `f${++idCounters.font}`;
  560. }
  561. static createObjId() {
  562. (0, _util.unreachable)("Abstract method `createObjId` called.");
  563. }
  564. static getPageObjId() {
  565. (0, _util.unreachable)("Abstract method `getPageObjId` called.");
  566. }
  567. };
  568. }
  569. parse(recoveryMode) {
  570. this.xref.parse(recoveryMode);
  571. this.catalog = new _catalog.Catalog(this.pdfManager, this.xref);
  572. }
  573. get linearization() {
  574. let linearization = null;
  575. try {
  576. linearization = _parser.Linearization.create(this.stream);
  577. } catch (err) {
  578. if (err instanceof _core_utils.MissingDataException) {
  579. throw err;
  580. }
  581. (0, _util.info)(err);
  582. }
  583. return (0, _util.shadow)(this, "linearization", linearization);
  584. }
  585. get startXRef() {
  586. const stream = this.stream;
  587. let startXRef = 0;
  588. if (this.linearization) {
  589. stream.reset();
  590. if (find(stream, ENDOBJ_SIGNATURE)) {
  591. startXRef = stream.pos + 6 - stream.start;
  592. }
  593. } else {
  594. const step = 1024;
  595. const startXRefLength = STARTXREF_SIGNATURE.length;
  596. let found = false,
  597. pos = stream.end;
  598. while (!found && pos > 0) {
  599. pos -= step - startXRefLength;
  600. if (pos < 0) {
  601. pos = 0;
  602. }
  603. stream.pos = pos;
  604. found = find(stream, STARTXREF_SIGNATURE, step, true);
  605. }
  606. if (found) {
  607. stream.skip(9);
  608. let ch;
  609. do {
  610. ch = stream.getByte();
  611. } while ((0, _core_utils.isWhiteSpace)(ch));
  612. let str = "";
  613. while (ch >= 0x20 && ch <= 0x39) {
  614. str += String.fromCharCode(ch);
  615. ch = stream.getByte();
  616. }
  617. startXRef = parseInt(str, 10);
  618. if (isNaN(startXRef)) {
  619. startXRef = 0;
  620. }
  621. }
  622. }
  623. return (0, _util.shadow)(this, "startXRef", startXRef);
  624. }
  625. checkHeader() {
  626. const stream = this.stream;
  627. stream.reset();
  628. if (!find(stream, PDF_HEADER_SIGNATURE)) {
  629. return;
  630. }
  631. stream.moveStart();
  632. stream.skip(PDF_HEADER_SIGNATURE.length);
  633. let version = "",
  634. ch;
  635. while ((ch = stream.getByte()) > 0x20 && version.length < 7) {
  636. version += String.fromCharCode(ch);
  637. }
  638. if (_core_utils.PDF_VERSION_REGEXP.test(version)) {
  639. this._version = version;
  640. } else {
  641. (0, _util.warn)(`Invalid PDF header version: ${version}`);
  642. }
  643. }
  644. parseStartXRef() {
  645. this.xref.setStartXRef(this.startXRef);
  646. }
  647. get numPages() {
  648. let num = 0;
  649. if (this.catalog.hasActualNumPages) {
  650. num = this.catalog.numPages;
  651. } else if (this.xfaFactory) {
  652. num = this.xfaFactory.getNumPages();
  653. } else if (this.linearization) {
  654. num = this.linearization.numPages;
  655. } else {
  656. num = this.catalog.numPages;
  657. }
  658. return (0, _util.shadow)(this, "numPages", num);
  659. }
  660. _hasOnlyDocumentSignatures(fields, recursionDepth = 0) {
  661. const RECURSION_LIMIT = 10;
  662. if (!Array.isArray(fields)) {
  663. return false;
  664. }
  665. return fields.every(field => {
  666. field = this.xref.fetchIfRef(field);
  667. if (!(field instanceof _primitives.Dict)) {
  668. return false;
  669. }
  670. if (field.has("Kids")) {
  671. if (++recursionDepth > RECURSION_LIMIT) {
  672. (0, _util.warn)("_hasOnlyDocumentSignatures: maximum recursion depth reached");
  673. return false;
  674. }
  675. return this._hasOnlyDocumentSignatures(field.get("Kids"), recursionDepth);
  676. }
  677. const isSignature = (0, _primitives.isName)(field.get("FT"), "Sig");
  678. const rectangle = field.get("Rect");
  679. const isInvisible = Array.isArray(rectangle) && rectangle.every(value => value === 0);
  680. return isSignature && isInvisible;
  681. });
  682. }
  683. get _xfaStreams() {
  684. const acroForm = this.catalog.acroForm;
  685. if (!acroForm) {
  686. return null;
  687. }
  688. const xfa = acroForm.get("XFA");
  689. const entries = {
  690. "xdp:xdp": "",
  691. template: "",
  692. datasets: "",
  693. config: "",
  694. connectionSet: "",
  695. localeSet: "",
  696. stylesheet: "",
  697. "/xdp:xdp": ""
  698. };
  699. if (xfa instanceof _base_stream.BaseStream && !xfa.isEmpty) {
  700. entries["xdp:xdp"] = xfa;
  701. return entries;
  702. }
  703. if (!Array.isArray(xfa) || xfa.length === 0) {
  704. return null;
  705. }
  706. for (let i = 0, ii = xfa.length; i < ii; i += 2) {
  707. let name;
  708. if (i === 0) {
  709. name = "xdp:xdp";
  710. } else if (i === ii - 2) {
  711. name = "/xdp:xdp";
  712. } else {
  713. name = xfa[i];
  714. }
  715. if (!entries.hasOwnProperty(name)) {
  716. continue;
  717. }
  718. const data = this.xref.fetchIfRef(xfa[i + 1]);
  719. if (!(data instanceof _base_stream.BaseStream) || data.isEmpty) {
  720. continue;
  721. }
  722. entries[name] = data;
  723. }
  724. return entries;
  725. }
  726. get xfaDatasets() {
  727. const streams = this._xfaStreams;
  728. if (!streams) {
  729. return (0, _util.shadow)(this, "xfaDatasets", null);
  730. }
  731. for (const key of ["datasets", "xdp:xdp"]) {
  732. const stream = streams[key];
  733. if (!stream) {
  734. continue;
  735. }
  736. try {
  737. const str = (0, _util.stringToUTF8String)(stream.getString());
  738. const data = {
  739. [key]: str
  740. };
  741. return (0, _util.shadow)(this, "xfaDatasets", new _dataset_reader.DatasetReader(data));
  742. } catch (_) {
  743. (0, _util.warn)("XFA - Invalid utf-8 string.");
  744. break;
  745. }
  746. }
  747. return (0, _util.shadow)(this, "xfaDatasets", null);
  748. }
  749. get xfaData() {
  750. const streams = this._xfaStreams;
  751. if (!streams) {
  752. return null;
  753. }
  754. const data = Object.create(null);
  755. for (const [key, stream] of Object.entries(streams)) {
  756. if (!stream) {
  757. continue;
  758. }
  759. try {
  760. data[key] = (0, _util.stringToUTF8String)(stream.getString());
  761. } catch (_) {
  762. (0, _util.warn)("XFA - Invalid utf-8 string.");
  763. return null;
  764. }
  765. }
  766. return data;
  767. }
  768. get xfaFactory() {
  769. let data;
  770. if (this.pdfManager.enableXfa && this.catalog.needsRendering && this.formInfo.hasXfa && !this.formInfo.hasAcroForm) {
  771. data = this.xfaData;
  772. }
  773. return (0, _util.shadow)(this, "xfaFactory", data ? new _factory.XFAFactory(data) : null);
  774. }
  775. get isPureXfa() {
  776. return this.xfaFactory ? this.xfaFactory.isValid() : false;
  777. }
  778. get htmlForXfa() {
  779. return this.xfaFactory ? this.xfaFactory.getPages() : null;
  780. }
  781. async loadXfaImages() {
  782. const xfaImagesDict = await this.pdfManager.ensureCatalog("xfaImages");
  783. if (!xfaImagesDict) {
  784. return;
  785. }
  786. const keys = xfaImagesDict.getKeys();
  787. const objectLoader = new _object_loader.ObjectLoader(xfaImagesDict, keys, this.xref);
  788. await objectLoader.load();
  789. const xfaImages = new Map();
  790. for (const key of keys) {
  791. const stream = xfaImagesDict.get(key);
  792. if (stream instanceof _base_stream.BaseStream) {
  793. xfaImages.set(key, stream.getBytes());
  794. }
  795. }
  796. this.xfaFactory.setImages(xfaImages);
  797. }
  798. async loadXfaFonts(handler, task) {
  799. const acroForm = await this.pdfManager.ensureCatalog("acroForm");
  800. if (!acroForm) {
  801. return;
  802. }
  803. const resources = await acroForm.getAsync("DR");
  804. if (!(resources instanceof _primitives.Dict)) {
  805. return;
  806. }
  807. const objectLoader = new _object_loader.ObjectLoader(resources, ["Font"], this.xref);
  808. await objectLoader.load();
  809. const fontRes = resources.get("Font");
  810. if (!(fontRes instanceof _primitives.Dict)) {
  811. return;
  812. }
  813. const options = Object.assign(Object.create(null), this.pdfManager.evaluatorOptions);
  814. options.useSystemFonts = false;
  815. const partialEvaluator = new _evaluator.PartialEvaluator({
  816. xref: this.xref,
  817. handler,
  818. pageIndex: -1,
  819. idFactory: this._globalIdFactory,
  820. fontCache: this.catalog.fontCache,
  821. builtInCMapCache: this.catalog.builtInCMapCache,
  822. standardFontDataCache: this.catalog.standardFontDataCache,
  823. options
  824. });
  825. const operatorList = new _operator_list.OperatorList();
  826. const pdfFonts = [];
  827. const initialState = {
  828. get font() {
  829. return pdfFonts.at(-1);
  830. },
  831. set font(font) {
  832. pdfFonts.push(font);
  833. },
  834. clone() {
  835. return this;
  836. }
  837. };
  838. const fonts = new Map();
  839. fontRes.forEach((fontName, font) => {
  840. fonts.set(fontName, font);
  841. });
  842. const promises = [];
  843. for (const [fontName, font] of fonts) {
  844. const descriptor = font.get("FontDescriptor");
  845. if (!(descriptor instanceof _primitives.Dict)) {
  846. continue;
  847. }
  848. let fontFamily = descriptor.get("FontFamily");
  849. fontFamily = fontFamily.replace(/[ ]+(\d)/g, "$1");
  850. const fontWeight = descriptor.get("FontWeight");
  851. const italicAngle = -descriptor.get("ItalicAngle");
  852. const cssFontInfo = {
  853. fontFamily,
  854. fontWeight,
  855. italicAngle
  856. };
  857. if (!(0, _core_utils.validateCSSFont)(cssFontInfo)) {
  858. continue;
  859. }
  860. promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(fontName), 1], null, operatorList, task, initialState, null, cssFontInfo).catch(function (reason) {
  861. (0, _util.warn)(`loadXfaFonts: "${reason}".`);
  862. return null;
  863. }));
  864. }
  865. await Promise.all(promises);
  866. const missingFonts = this.xfaFactory.setFonts(pdfFonts);
  867. if (!missingFonts) {
  868. return;
  869. }
  870. options.ignoreErrors = true;
  871. promises.length = 0;
  872. pdfFonts.length = 0;
  873. const reallyMissingFonts = new Set();
  874. for (const missing of missingFonts) {
  875. if (!(0, _xfa_fonts.getXfaFontName)(`${missing}-Regular`)) {
  876. reallyMissingFonts.add(missing);
  877. }
  878. }
  879. if (reallyMissingFonts.size) {
  880. missingFonts.push("PdfJS-Fallback");
  881. }
  882. for (const missing of missingFonts) {
  883. if (reallyMissingFonts.has(missing)) {
  884. continue;
  885. }
  886. for (const fontInfo of [{
  887. name: "Regular",
  888. fontWeight: 400,
  889. italicAngle: 0
  890. }, {
  891. name: "Bold",
  892. fontWeight: 700,
  893. italicAngle: 0
  894. }, {
  895. name: "Italic",
  896. fontWeight: 400,
  897. italicAngle: 12
  898. }, {
  899. name: "BoldItalic",
  900. fontWeight: 700,
  901. italicAngle: 12
  902. }]) {
  903. const name = `${missing}-${fontInfo.name}`;
  904. const dict = (0, _xfa_fonts.getXfaFontDict)(name);
  905. promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(name), 1], null, operatorList, task, initialState, dict, {
  906. fontFamily: missing,
  907. fontWeight: fontInfo.fontWeight,
  908. italicAngle: fontInfo.italicAngle
  909. }).catch(function (reason) {
  910. (0, _util.warn)(`loadXfaFonts: "${reason}".`);
  911. return null;
  912. }));
  913. }
  914. }
  915. await Promise.all(promises);
  916. this.xfaFactory.appendFonts(pdfFonts, reallyMissingFonts);
  917. }
  918. async serializeXfaData(annotationStorage) {
  919. return this.xfaFactory ? this.xfaFactory.serializeData(annotationStorage) : null;
  920. }
  921. get version() {
  922. return this.catalog.version || this._version;
  923. }
  924. get formInfo() {
  925. const formInfo = {
  926. hasFields: false,
  927. hasAcroForm: false,
  928. hasXfa: false,
  929. hasSignatures: false
  930. };
  931. const acroForm = this.catalog.acroForm;
  932. if (!acroForm) {
  933. return (0, _util.shadow)(this, "formInfo", formInfo);
  934. }
  935. try {
  936. const fields = acroForm.get("Fields");
  937. const hasFields = Array.isArray(fields) && fields.length > 0;
  938. formInfo.hasFields = hasFields;
  939. const xfa = acroForm.get("XFA");
  940. formInfo.hasXfa = Array.isArray(xfa) && xfa.length > 0 || xfa instanceof _base_stream.BaseStream && !xfa.isEmpty;
  941. const sigFlags = acroForm.get("SigFlags");
  942. const hasSignatures = !!(sigFlags & 0x1);
  943. const hasOnlyDocumentSignatures = hasSignatures && this._hasOnlyDocumentSignatures(fields);
  944. formInfo.hasAcroForm = hasFields && !hasOnlyDocumentSignatures;
  945. formInfo.hasSignatures = hasSignatures;
  946. } catch (ex) {
  947. if (ex instanceof _core_utils.MissingDataException) {
  948. throw ex;
  949. }
  950. (0, _util.warn)(`Cannot fetch form information: "${ex}".`);
  951. }
  952. return (0, _util.shadow)(this, "formInfo", formInfo);
  953. }
  954. get documentInfo() {
  955. const docInfo = {
  956. PDFFormatVersion: this.version,
  957. Language: this.catalog.lang,
  958. EncryptFilterName: this.xref.encrypt ? this.xref.encrypt.filterName : null,
  959. IsLinearized: !!this.linearization,
  960. IsAcroFormPresent: this.formInfo.hasAcroForm,
  961. IsXFAPresent: this.formInfo.hasXfa,
  962. IsCollectionPresent: !!this.catalog.collection,
  963. IsSignaturesPresent: this.formInfo.hasSignatures
  964. };
  965. let infoDict;
  966. try {
  967. infoDict = this.xref.trailer.get("Info");
  968. } catch (err) {
  969. if (err instanceof _core_utils.MissingDataException) {
  970. throw err;
  971. }
  972. (0, _util.info)("The document information dictionary is invalid.");
  973. }
  974. if (!(infoDict instanceof _primitives.Dict)) {
  975. return (0, _util.shadow)(this, "documentInfo", docInfo);
  976. }
  977. for (const key of infoDict.getKeys()) {
  978. const value = infoDict.get(key);
  979. switch (key) {
  980. case "Title":
  981. case "Author":
  982. case "Subject":
  983. case "Keywords":
  984. case "Creator":
  985. case "Producer":
  986. case "CreationDate":
  987. case "ModDate":
  988. if (typeof value === "string") {
  989. docInfo[key] = (0, _util.stringToPDFString)(value);
  990. continue;
  991. }
  992. break;
  993. case "Trapped":
  994. if (value instanceof _primitives.Name) {
  995. docInfo[key] = value;
  996. continue;
  997. }
  998. break;
  999. default:
  1000. let customValue;
  1001. switch (typeof value) {
  1002. case "string":
  1003. customValue = (0, _util.stringToPDFString)(value);
  1004. break;
  1005. case "number":
  1006. case "boolean":
  1007. customValue = value;
  1008. break;
  1009. default:
  1010. if (value instanceof _primitives.Name) {
  1011. customValue = value;
  1012. }
  1013. break;
  1014. }
  1015. if (customValue === undefined) {
  1016. (0, _util.warn)(`Bad value, for custom key "${key}", in Info: ${value}.`);
  1017. continue;
  1018. }
  1019. if (!docInfo.Custom) {
  1020. docInfo.Custom = Object.create(null);
  1021. }
  1022. docInfo.Custom[key] = customValue;
  1023. continue;
  1024. }
  1025. (0, _util.warn)(`Bad value, for key "${key}", in Info: ${value}.`);
  1026. }
  1027. return (0, _util.shadow)(this, "documentInfo", docInfo);
  1028. }
  1029. get fingerprints() {
  1030. function validate(data) {
  1031. return typeof data === "string" && data.length > 0 && data !== EMPTY_FINGERPRINT;
  1032. }
  1033. function hexString(hash) {
  1034. const buf = [];
  1035. for (const num of hash) {
  1036. const hex = num.toString(16);
  1037. buf.push(hex.padStart(2, "0"));
  1038. }
  1039. return buf.join("");
  1040. }
  1041. const idArray = this.xref.trailer.get("ID");
  1042. let hashOriginal, hashModified;
  1043. if (Array.isArray(idArray) && validate(idArray[0])) {
  1044. hashOriginal = (0, _util.stringToBytes)(idArray[0]);
  1045. if (idArray[1] !== idArray[0] && validate(idArray[1])) {
  1046. hashModified = (0, _util.stringToBytes)(idArray[1]);
  1047. }
  1048. } else {
  1049. hashOriginal = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  1050. }
  1051. return (0, _util.shadow)(this, "fingerprints", [hexString(hashOriginal), hashModified ? hexString(hashModified) : null]);
  1052. }
  1053. async _getLinearizationPage(pageIndex) {
  1054. const {
  1055. catalog,
  1056. linearization,
  1057. xref
  1058. } = this;
  1059. const ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
  1060. try {
  1061. const obj = await xref.fetchAsync(ref);
  1062. if (obj instanceof _primitives.Dict) {
  1063. let type = obj.getRaw("Type");
  1064. if (type instanceof _primitives.Ref) {
  1065. type = await xref.fetchAsync(type);
  1066. }
  1067. if ((0, _primitives.isName)(type, "Page") || !obj.has("Type") && !obj.has("Kids")) {
  1068. if (!catalog.pageKidsCountCache.has(ref)) {
  1069. catalog.pageKidsCountCache.put(ref, 1);
  1070. }
  1071. if (!catalog.pageIndexCache.has(ref)) {
  1072. catalog.pageIndexCache.put(ref, 0);
  1073. }
  1074. return [obj, ref];
  1075. }
  1076. }
  1077. throw new _util.FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.");
  1078. } catch (reason) {
  1079. (0, _util.warn)(`_getLinearizationPage: "${reason.message}".`);
  1080. return catalog.getPageDict(pageIndex);
  1081. }
  1082. }
  1083. getPage(pageIndex) {
  1084. const cachedPromise = this._pagePromises.get(pageIndex);
  1085. if (cachedPromise) {
  1086. return cachedPromise;
  1087. }
  1088. const {
  1089. catalog,
  1090. linearization,
  1091. xfaFactory
  1092. } = this;
  1093. let promise;
  1094. if (xfaFactory) {
  1095. promise = Promise.resolve([_primitives.Dict.empty, null]);
  1096. } else if (linearization && linearization.pageFirst === pageIndex) {
  1097. promise = this._getLinearizationPage(pageIndex);
  1098. } else {
  1099. promise = catalog.getPageDict(pageIndex);
  1100. }
  1101. promise = promise.then(([pageDict, ref]) => {
  1102. return new Page({
  1103. pdfManager: this.pdfManager,
  1104. xref: this.xref,
  1105. pageIndex,
  1106. pageDict,
  1107. ref,
  1108. globalIdFactory: this._globalIdFactory,
  1109. fontCache: catalog.fontCache,
  1110. builtInCMapCache: catalog.builtInCMapCache,
  1111. standardFontDataCache: catalog.standardFontDataCache,
  1112. globalImageCache: catalog.globalImageCache,
  1113. nonBlendModesSet: catalog.nonBlendModesSet,
  1114. xfaFactory
  1115. });
  1116. });
  1117. this._pagePromises.set(pageIndex, promise);
  1118. return promise;
  1119. }
  1120. async checkFirstPage(recoveryMode = false) {
  1121. if (recoveryMode) {
  1122. return;
  1123. }
  1124. try {
  1125. await this.getPage(0);
  1126. } catch (reason) {
  1127. if (reason instanceof _core_utils.XRefEntryException) {
  1128. this._pagePromises.delete(0);
  1129. await this.cleanup();
  1130. throw new _core_utils.XRefParseException();
  1131. }
  1132. }
  1133. }
  1134. async checkLastPage(recoveryMode = false) {
  1135. const {
  1136. catalog,
  1137. pdfManager
  1138. } = this;
  1139. catalog.setActualNumPages();
  1140. let numPages;
  1141. try {
  1142. await Promise.all([pdfManager.ensureDoc("xfaFactory"), pdfManager.ensureDoc("linearization"), pdfManager.ensureCatalog("numPages")]);
  1143. if (this.xfaFactory) {
  1144. return;
  1145. } else if (this.linearization) {
  1146. numPages = this.linearization.numPages;
  1147. } else {
  1148. numPages = catalog.numPages;
  1149. }
  1150. if (!Number.isInteger(numPages)) {
  1151. throw new _util.FormatError("Page count is not an integer.");
  1152. } else if (numPages <= 1) {
  1153. return;
  1154. }
  1155. await this.getPage(numPages - 1);
  1156. } catch (reason) {
  1157. this._pagePromises.delete(numPages - 1);
  1158. await this.cleanup();
  1159. if (reason instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1160. throw new _core_utils.XRefParseException();
  1161. }
  1162. (0, _util.warn)(`checkLastPage - invalid /Pages tree /Count: ${numPages}.`);
  1163. let pagesTree;
  1164. try {
  1165. pagesTree = await catalog.getAllPageDicts(recoveryMode);
  1166. } catch (reasonAll) {
  1167. if (reasonAll instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1168. throw new _core_utils.XRefParseException();
  1169. }
  1170. catalog.setActualNumPages(1);
  1171. return;
  1172. }
  1173. for (const [pageIndex, [pageDict, ref]] of pagesTree) {
  1174. let promise;
  1175. if (pageDict instanceof Error) {
  1176. promise = Promise.reject(pageDict);
  1177. promise.catch(() => {});
  1178. } else {
  1179. promise = Promise.resolve(new Page({
  1180. pdfManager,
  1181. xref: this.xref,
  1182. pageIndex,
  1183. pageDict,
  1184. ref,
  1185. globalIdFactory: this._globalIdFactory,
  1186. fontCache: catalog.fontCache,
  1187. builtInCMapCache: catalog.builtInCMapCache,
  1188. standardFontDataCache: catalog.standardFontDataCache,
  1189. globalImageCache: catalog.globalImageCache,
  1190. nonBlendModesSet: catalog.nonBlendModesSet,
  1191. xfaFactory: null
  1192. }));
  1193. }
  1194. this._pagePromises.set(pageIndex, promise);
  1195. }
  1196. catalog.setActualNumPages(pagesTree.size);
  1197. }
  1198. }
  1199. fontFallback(id, handler) {
  1200. return this.catalog.fontFallback(id, handler);
  1201. }
  1202. async cleanup(manuallyTriggered = false) {
  1203. return this.catalog ? this.catalog.cleanup(manuallyTriggered) : (0, _cleanup_helper.clearGlobalCaches)();
  1204. }
  1205. _collectFieldObjects(name, fieldRef, promises) {
  1206. const field = this.xref.fetchIfRef(fieldRef);
  1207. if (field.has("T")) {
  1208. const partName = (0, _util.stringToPDFString)(field.get("T"));
  1209. if (name === "") {
  1210. name = partName;
  1211. } else {
  1212. name = `${name}.${partName}`;
  1213. }
  1214. }
  1215. if (!promises.has(name)) {
  1216. promises.set(name, []);
  1217. }
  1218. promises.get(name).push(_annotation.AnnotationFactory.create(this.xref, fieldRef, this.pdfManager, this._localIdFactory, true).then(annotation => annotation && annotation.getFieldObject()).catch(function (reason) {
  1219. (0, _util.warn)(`_collectFieldObjects: "${reason}".`);
  1220. return null;
  1221. }));
  1222. if (field.has("Kids")) {
  1223. const kids = field.get("Kids");
  1224. for (const kid of kids) {
  1225. this._collectFieldObjects(name, kid, promises);
  1226. }
  1227. }
  1228. }
  1229. get fieldObjects() {
  1230. if (!this.formInfo.hasFields) {
  1231. return (0, _util.shadow)(this, "fieldObjects", Promise.resolve(null));
  1232. }
  1233. const allFields = Object.create(null);
  1234. const fieldPromises = new Map();
  1235. for (const fieldRef of this.catalog.acroForm.get("Fields")) {
  1236. this._collectFieldObjects("", fieldRef, fieldPromises);
  1237. }
  1238. const allPromises = [];
  1239. for (const [name, promises] of fieldPromises) {
  1240. allPromises.push(Promise.all(promises).then(fields => {
  1241. fields = fields.filter(field => !!field);
  1242. if (fields.length > 0) {
  1243. allFields[name] = fields;
  1244. }
  1245. }));
  1246. }
  1247. return (0, _util.shadow)(this, "fieldObjects", Promise.all(allPromises).then(() => allFields));
  1248. }
  1249. get hasJSActions() {
  1250. const promise = this.pdfManager.ensureDoc("_parseHasJSActions");
  1251. return (0, _util.shadow)(this, "hasJSActions", promise);
  1252. }
  1253. async _parseHasJSActions() {
  1254. const [catalogJsActions, fieldObjects] = await Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]);
  1255. if (catalogJsActions) {
  1256. return true;
  1257. }
  1258. if (fieldObjects) {
  1259. return Object.values(fieldObjects).some(fieldObject => fieldObject.some(object => object.actions !== null));
  1260. }
  1261. return false;
  1262. }
  1263. get calculationOrderIds() {
  1264. const acroForm = this.catalog.acroForm;
  1265. if (!acroForm || !acroForm.has("CO")) {
  1266. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1267. }
  1268. const calculationOrder = acroForm.get("CO");
  1269. if (!Array.isArray(calculationOrder) || calculationOrder.length === 0) {
  1270. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1271. }
  1272. const ids = [];
  1273. for (const id of calculationOrder) {
  1274. if (id instanceof _primitives.Ref) {
  1275. ids.push(id.toString());
  1276. }
  1277. }
  1278. if (ids.length === 0) {
  1279. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1280. }
  1281. return (0, _util.shadow)(this, "calculationOrderIds", ids);
  1282. }
  1283. }
  1284. exports.PDFDocument = PDFDocument;