2
0

document.js 42 KB

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