document.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  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 _util = require("../shared/util.js");
  28. var _core_utils = require("./core_utils.js");
  29. var _primitives = require("./primitives.js");
  30. var _xfa_fonts = require("./xfa_fonts.js");
  31. var _annotation = require("./annotation.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. getAnnotationsData(intent) {
  415. return this._parsedAnnotations.then(function (annotations) {
  416. const annotationsData = [];
  417. if (annotations.length === 0) {
  418. return annotationsData;
  419. }
  420. const intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
  421. intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
  422. intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
  423. for (const annotation of annotations) {
  424. if (intentAny || intentDisplay && annotation.viewable || intentPrint && annotation.printable) {
  425. annotationsData.push(annotation.data);
  426. }
  427. }
  428. return annotationsData;
  429. });
  430. }
  431. get annotations() {
  432. const annots = this._getInheritableProperty("Annots");
  433. return (0, _util.shadow)(this, "annotations", Array.isArray(annots) ? annots : []);
  434. }
  435. get _parsedAnnotations() {
  436. const parsedAnnotations = this.pdfManager.ensure(this, "annotations").then(() => {
  437. const annotationPromises = [];
  438. for (const annotationRef of this.annotations) {
  439. annotationPromises.push(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this._localIdFactory, false).catch(function (reason) {
  440. (0, _util.warn)(`_parsedAnnotations: "${reason}".`);
  441. return null;
  442. }));
  443. }
  444. return Promise.all(annotationPromises).then(function (annotations) {
  445. return annotations.filter(annotation => !!annotation);
  446. });
  447. });
  448. return (0, _util.shadow)(this, "_parsedAnnotations", parsedAnnotations);
  449. }
  450. get jsActions() {
  451. const actions = (0, _core_utils.collectActions)(this.xref, this.pageDict, _util.PageActionEventType);
  452. return (0, _util.shadow)(this, "jsActions", actions);
  453. }
  454. }
  455. exports.Page = Page;
  456. const PDF_HEADER_SIGNATURE = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]);
  457. const STARTXREF_SIGNATURE = new Uint8Array([0x73, 0x74, 0x61, 0x72, 0x74, 0x78, 0x72, 0x65, 0x66]);
  458. const ENDOBJ_SIGNATURE = new Uint8Array([0x65, 0x6e, 0x64, 0x6f, 0x62, 0x6a]);
  459. const FINGERPRINT_FIRST_BYTES = 1024;
  460. const EMPTY_FINGERPRINT = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
  461. const PDF_HEADER_VERSION_REGEXP = /^[1-9]\.\d$/;
  462. function find(stream, signature, limit = 1024, backwards = false) {
  463. const signatureLength = signature.length;
  464. const scanBytes = stream.peekBytes(limit);
  465. const scanLength = scanBytes.length - signatureLength;
  466. if (scanLength <= 0) {
  467. return false;
  468. }
  469. if (backwards) {
  470. const signatureEnd = signatureLength - 1;
  471. let pos = scanBytes.length - 1;
  472. while (pos >= signatureEnd) {
  473. let j = 0;
  474. while (j < signatureLength && scanBytes[pos - j] === signature[signatureEnd - j]) {
  475. j++;
  476. }
  477. if (j >= signatureLength) {
  478. stream.pos += pos - signatureEnd;
  479. return true;
  480. }
  481. pos--;
  482. }
  483. } else {
  484. let pos = 0;
  485. while (pos <= scanLength) {
  486. let j = 0;
  487. while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
  488. j++;
  489. }
  490. if (j >= signatureLength) {
  491. stream.pos += pos;
  492. return true;
  493. }
  494. pos++;
  495. }
  496. }
  497. return false;
  498. }
  499. class PDFDocument {
  500. constructor(pdfManager, stream) {
  501. if (stream.length <= 0) {
  502. throw new _util.InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");
  503. }
  504. this.pdfManager = pdfManager;
  505. this.stream = stream;
  506. this.xref = new _xref.XRef(stream, pdfManager);
  507. this._pagePromises = new Map();
  508. this._version = null;
  509. const idCounters = {
  510. font: 0
  511. };
  512. this._globalIdFactory = class {
  513. static getDocId() {
  514. return `g_${pdfManager.docId}`;
  515. }
  516. static createFontId() {
  517. return `f${++idCounters.font}`;
  518. }
  519. static createObjId() {
  520. (0, _util.unreachable)("Abstract method `createObjId` called.");
  521. }
  522. static getPageObjId() {
  523. (0, _util.unreachable)("Abstract method `getPageObjId` called.");
  524. }
  525. };
  526. }
  527. parse(recoveryMode) {
  528. this.xref.parse(recoveryMode);
  529. this.catalog = new _catalog.Catalog(this.pdfManager, this.xref);
  530. if (this.catalog.version) {
  531. this._version = this.catalog.version;
  532. }
  533. }
  534. get linearization() {
  535. let linearization = null;
  536. try {
  537. linearization = _parser.Linearization.create(this.stream);
  538. } catch (err) {
  539. if (err instanceof _core_utils.MissingDataException) {
  540. throw err;
  541. }
  542. (0, _util.info)(err);
  543. }
  544. return (0, _util.shadow)(this, "linearization", linearization);
  545. }
  546. get startXRef() {
  547. const stream = this.stream;
  548. let startXRef = 0;
  549. if (this.linearization) {
  550. stream.reset();
  551. if (find(stream, ENDOBJ_SIGNATURE)) {
  552. startXRef = stream.pos + 6 - stream.start;
  553. }
  554. } else {
  555. const step = 1024;
  556. const startXRefLength = STARTXREF_SIGNATURE.length;
  557. let found = false,
  558. pos = stream.end;
  559. while (!found && pos > 0) {
  560. pos -= step - startXRefLength;
  561. if (pos < 0) {
  562. pos = 0;
  563. }
  564. stream.pos = pos;
  565. found = find(stream, STARTXREF_SIGNATURE, step, true);
  566. }
  567. if (found) {
  568. stream.skip(9);
  569. let ch;
  570. do {
  571. ch = stream.getByte();
  572. } while ((0, _core_utils.isWhiteSpace)(ch));
  573. let str = "";
  574. while (ch >= 0x20 && ch <= 0x39) {
  575. str += String.fromCharCode(ch);
  576. ch = stream.getByte();
  577. }
  578. startXRef = parseInt(str, 10);
  579. if (isNaN(startXRef)) {
  580. startXRef = 0;
  581. }
  582. }
  583. }
  584. return (0, _util.shadow)(this, "startXRef", startXRef);
  585. }
  586. checkHeader() {
  587. const stream = this.stream;
  588. stream.reset();
  589. if (!find(stream, PDF_HEADER_SIGNATURE)) {
  590. return;
  591. }
  592. stream.moveStart();
  593. const MAX_PDF_VERSION_LENGTH = 12;
  594. let version = "",
  595. ch;
  596. while ((ch = stream.getByte()) > 0x20) {
  597. if (version.length >= MAX_PDF_VERSION_LENGTH) {
  598. break;
  599. }
  600. version += String.fromCharCode(ch);
  601. }
  602. if (!this._version) {
  603. this._version = version.substring(5);
  604. }
  605. }
  606. parseStartXRef() {
  607. this.xref.setStartXRef(this.startXRef);
  608. }
  609. get numPages() {
  610. let num = 0;
  611. if (this.catalog.hasActualNumPages) {
  612. num = this.catalog.numPages;
  613. } else if (this.xfaFactory) {
  614. num = this.xfaFactory.getNumPages();
  615. } else if (this.linearization) {
  616. num = this.linearization.numPages;
  617. } else {
  618. num = this.catalog.numPages;
  619. }
  620. return (0, _util.shadow)(this, "numPages", num);
  621. }
  622. _hasOnlyDocumentSignatures(fields, recursionDepth = 0) {
  623. const RECURSION_LIMIT = 10;
  624. if (!Array.isArray(fields)) {
  625. return false;
  626. }
  627. return fields.every(field => {
  628. field = this.xref.fetchIfRef(field);
  629. if (!(field instanceof _primitives.Dict)) {
  630. return false;
  631. }
  632. if (field.has("Kids")) {
  633. if (++recursionDepth > RECURSION_LIMIT) {
  634. (0, _util.warn)("_hasOnlyDocumentSignatures: maximum recursion depth reached");
  635. return false;
  636. }
  637. return this._hasOnlyDocumentSignatures(field.get("Kids"), recursionDepth);
  638. }
  639. const isSignature = (0, _primitives.isName)(field.get("FT"), "Sig");
  640. const rectangle = field.get("Rect");
  641. const isInvisible = Array.isArray(rectangle) && rectangle.every(value => value === 0);
  642. return isSignature && isInvisible;
  643. });
  644. }
  645. get _xfaStreams() {
  646. const acroForm = this.catalog.acroForm;
  647. if (!acroForm) {
  648. return null;
  649. }
  650. const xfa = acroForm.get("XFA");
  651. const entries = {
  652. "xdp:xdp": "",
  653. template: "",
  654. datasets: "",
  655. config: "",
  656. connectionSet: "",
  657. localeSet: "",
  658. stylesheet: "",
  659. "/xdp:xdp": ""
  660. };
  661. if (xfa instanceof _base_stream.BaseStream && !xfa.isEmpty) {
  662. entries["xdp:xdp"] = xfa;
  663. return entries;
  664. }
  665. if (!Array.isArray(xfa) || xfa.length === 0) {
  666. return null;
  667. }
  668. for (let i = 0, ii = xfa.length; i < ii; i += 2) {
  669. let name;
  670. if (i === 0) {
  671. name = "xdp:xdp";
  672. } else if (i === ii - 2) {
  673. name = "/xdp:xdp";
  674. } else {
  675. name = xfa[i];
  676. }
  677. if (!entries.hasOwnProperty(name)) {
  678. continue;
  679. }
  680. const data = this.xref.fetchIfRef(xfa[i + 1]);
  681. if (!(data instanceof _base_stream.BaseStream) || data.isEmpty) {
  682. continue;
  683. }
  684. entries[name] = data;
  685. }
  686. return entries;
  687. }
  688. get xfaDatasets() {
  689. const streams = this._xfaStreams;
  690. if (!streams) {
  691. return (0, _util.shadow)(this, "xfaDatasets", null);
  692. }
  693. for (const key of ["datasets", "xdp:xdp"]) {
  694. const stream = streams[key];
  695. if (!stream) {
  696. continue;
  697. }
  698. try {
  699. const str = (0, _util.stringToUTF8String)(stream.getString());
  700. const data = {
  701. [key]: str
  702. };
  703. return (0, _util.shadow)(this, "xfaDatasets", new _dataset_reader.DatasetReader(data));
  704. } catch (_) {
  705. (0, _util.warn)("XFA - Invalid utf-8 string.");
  706. break;
  707. }
  708. }
  709. return (0, _util.shadow)(this, "xfaDatasets", null);
  710. }
  711. get xfaData() {
  712. const streams = this._xfaStreams;
  713. if (!streams) {
  714. return null;
  715. }
  716. const data = Object.create(null);
  717. for (const [key, stream] of Object.entries(streams)) {
  718. if (!stream) {
  719. continue;
  720. }
  721. try {
  722. data[key] = (0, _util.stringToUTF8String)(stream.getString());
  723. } catch (_) {
  724. (0, _util.warn)("XFA - Invalid utf-8 string.");
  725. return null;
  726. }
  727. }
  728. return data;
  729. }
  730. get xfaFactory() {
  731. let data;
  732. if (this.pdfManager.enableXfa && this.catalog.needsRendering && this.formInfo.hasXfa && !this.formInfo.hasAcroForm) {
  733. data = this.xfaData;
  734. }
  735. return (0, _util.shadow)(this, "xfaFactory", data ? new _factory.XFAFactory(data) : null);
  736. }
  737. get isPureXfa() {
  738. return this.xfaFactory ? this.xfaFactory.isValid() : false;
  739. }
  740. get htmlForXfa() {
  741. return this.xfaFactory ? this.xfaFactory.getPages() : null;
  742. }
  743. async loadXfaImages() {
  744. const xfaImagesDict = await this.pdfManager.ensureCatalog("xfaImages");
  745. if (!xfaImagesDict) {
  746. return;
  747. }
  748. const keys = xfaImagesDict.getKeys();
  749. const objectLoader = new _object_loader.ObjectLoader(xfaImagesDict, keys, this.xref);
  750. await objectLoader.load();
  751. const xfaImages = new Map();
  752. for (const key of keys) {
  753. const stream = xfaImagesDict.get(key);
  754. if (stream instanceof _base_stream.BaseStream) {
  755. xfaImages.set(key, stream.getBytes());
  756. }
  757. }
  758. this.xfaFactory.setImages(xfaImages);
  759. }
  760. async loadXfaFonts(handler, task) {
  761. const acroForm = await this.pdfManager.ensureCatalog("acroForm");
  762. if (!acroForm) {
  763. return;
  764. }
  765. const resources = await acroForm.getAsync("DR");
  766. if (!(resources instanceof _primitives.Dict)) {
  767. return;
  768. }
  769. const objectLoader = new _object_loader.ObjectLoader(resources, ["Font"], this.xref);
  770. await objectLoader.load();
  771. const fontRes = resources.get("Font");
  772. if (!(fontRes instanceof _primitives.Dict)) {
  773. return;
  774. }
  775. const options = Object.assign(Object.create(null), this.pdfManager.evaluatorOptions);
  776. options.useSystemFonts = false;
  777. const partialEvaluator = new _evaluator.PartialEvaluator({
  778. xref: this.xref,
  779. handler,
  780. pageIndex: -1,
  781. idFactory: this._globalIdFactory,
  782. fontCache: this.catalog.fontCache,
  783. builtInCMapCache: this.catalog.builtInCMapCache,
  784. standardFontDataCache: this.catalog.standardFontDataCache,
  785. options
  786. });
  787. const operatorList = new _operator_list.OperatorList();
  788. const pdfFonts = [];
  789. const initialState = {
  790. get font() {
  791. return pdfFonts.at(-1);
  792. },
  793. set font(font) {
  794. pdfFonts.push(font);
  795. },
  796. clone() {
  797. return this;
  798. }
  799. };
  800. const fonts = new Map();
  801. fontRes.forEach((fontName, font) => {
  802. fonts.set(fontName, font);
  803. });
  804. const promises = [];
  805. for (const [fontName, font] of fonts) {
  806. const descriptor = font.get("FontDescriptor");
  807. if (!(descriptor instanceof _primitives.Dict)) {
  808. continue;
  809. }
  810. let fontFamily = descriptor.get("FontFamily");
  811. fontFamily = fontFamily.replace(/[ ]+(\d)/g, "$1");
  812. const fontWeight = descriptor.get("FontWeight");
  813. const italicAngle = -descriptor.get("ItalicAngle");
  814. const cssFontInfo = {
  815. fontFamily,
  816. fontWeight,
  817. italicAngle
  818. };
  819. if (!(0, _core_utils.validateCSSFont)(cssFontInfo)) {
  820. continue;
  821. }
  822. promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(fontName), 1], null, operatorList, task, initialState, null, cssFontInfo).catch(function (reason) {
  823. (0, _util.warn)(`loadXfaFonts: "${reason}".`);
  824. return null;
  825. }));
  826. }
  827. await Promise.all(promises);
  828. const missingFonts = this.xfaFactory.setFonts(pdfFonts);
  829. if (!missingFonts) {
  830. return;
  831. }
  832. options.ignoreErrors = true;
  833. promises.length = 0;
  834. pdfFonts.length = 0;
  835. const reallyMissingFonts = new Set();
  836. for (const missing of missingFonts) {
  837. if (!(0, _xfa_fonts.getXfaFontName)(`${missing}-Regular`)) {
  838. reallyMissingFonts.add(missing);
  839. }
  840. }
  841. if (reallyMissingFonts.size) {
  842. missingFonts.push("PdfJS-Fallback");
  843. }
  844. for (const missing of missingFonts) {
  845. if (reallyMissingFonts.has(missing)) {
  846. continue;
  847. }
  848. for (const fontInfo of [{
  849. name: "Regular",
  850. fontWeight: 400,
  851. italicAngle: 0
  852. }, {
  853. name: "Bold",
  854. fontWeight: 700,
  855. italicAngle: 0
  856. }, {
  857. name: "Italic",
  858. fontWeight: 400,
  859. italicAngle: 12
  860. }, {
  861. name: "BoldItalic",
  862. fontWeight: 700,
  863. italicAngle: 12
  864. }]) {
  865. const name = `${missing}-${fontInfo.name}`;
  866. const dict = (0, _xfa_fonts.getXfaFontDict)(name);
  867. promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(name), 1], null, operatorList, task, initialState, dict, {
  868. fontFamily: missing,
  869. fontWeight: fontInfo.fontWeight,
  870. italicAngle: fontInfo.italicAngle
  871. }).catch(function (reason) {
  872. (0, _util.warn)(`loadXfaFonts: "${reason}".`);
  873. return null;
  874. }));
  875. }
  876. }
  877. await Promise.all(promises);
  878. this.xfaFactory.appendFonts(pdfFonts, reallyMissingFonts);
  879. }
  880. async serializeXfaData(annotationStorage) {
  881. return this.xfaFactory ? this.xfaFactory.serializeData(annotationStorage) : null;
  882. }
  883. get formInfo() {
  884. const formInfo = {
  885. hasFields: false,
  886. hasAcroForm: false,
  887. hasXfa: false,
  888. hasSignatures: false
  889. };
  890. const acroForm = this.catalog.acroForm;
  891. if (!acroForm) {
  892. return (0, _util.shadow)(this, "formInfo", formInfo);
  893. }
  894. try {
  895. const fields = acroForm.get("Fields");
  896. const hasFields = Array.isArray(fields) && fields.length > 0;
  897. formInfo.hasFields = hasFields;
  898. const xfa = acroForm.get("XFA");
  899. formInfo.hasXfa = Array.isArray(xfa) && xfa.length > 0 || xfa instanceof _base_stream.BaseStream && !xfa.isEmpty;
  900. const sigFlags = acroForm.get("SigFlags");
  901. const hasSignatures = !!(sigFlags & 0x1);
  902. const hasOnlyDocumentSignatures = hasSignatures && this._hasOnlyDocumentSignatures(fields);
  903. formInfo.hasAcroForm = hasFields && !hasOnlyDocumentSignatures;
  904. formInfo.hasSignatures = hasSignatures;
  905. } catch (ex) {
  906. if (ex instanceof _core_utils.MissingDataException) {
  907. throw ex;
  908. }
  909. (0, _util.warn)(`Cannot fetch form information: "${ex}".`);
  910. }
  911. return (0, _util.shadow)(this, "formInfo", formInfo);
  912. }
  913. get documentInfo() {
  914. let version = this._version;
  915. if (typeof version !== "string" || !PDF_HEADER_VERSION_REGEXP.test(version)) {
  916. (0, _util.warn)(`Invalid PDF header version number: ${version}`);
  917. version = null;
  918. }
  919. const docInfo = {
  920. PDFFormatVersion: version,
  921. Language: this.catalog.lang,
  922. EncryptFilterName: this.xref.encrypt ? this.xref.encrypt.filterName : null,
  923. IsLinearized: !!this.linearization,
  924. IsAcroFormPresent: this.formInfo.hasAcroForm,
  925. IsXFAPresent: this.formInfo.hasXfa,
  926. IsCollectionPresent: !!this.catalog.collection,
  927. IsSignaturesPresent: this.formInfo.hasSignatures
  928. };
  929. let infoDict;
  930. try {
  931. infoDict = this.xref.trailer.get("Info");
  932. } catch (err) {
  933. if (err instanceof _core_utils.MissingDataException) {
  934. throw err;
  935. }
  936. (0, _util.info)("The document information dictionary is invalid.");
  937. }
  938. if (!(infoDict instanceof _primitives.Dict)) {
  939. return (0, _util.shadow)(this, "documentInfo", docInfo);
  940. }
  941. for (const key of infoDict.getKeys()) {
  942. const value = infoDict.get(key);
  943. switch (key) {
  944. case "Title":
  945. case "Author":
  946. case "Subject":
  947. case "Keywords":
  948. case "Creator":
  949. case "Producer":
  950. case "CreationDate":
  951. case "ModDate":
  952. if (typeof value === "string") {
  953. docInfo[key] = (0, _util.stringToPDFString)(value);
  954. continue;
  955. }
  956. break;
  957. case "Trapped":
  958. if (value instanceof _primitives.Name) {
  959. docInfo[key] = value;
  960. continue;
  961. }
  962. break;
  963. default:
  964. let customValue;
  965. switch (typeof value) {
  966. case "string":
  967. customValue = (0, _util.stringToPDFString)(value);
  968. break;
  969. case "number":
  970. case "boolean":
  971. customValue = value;
  972. break;
  973. default:
  974. if (value instanceof _primitives.Name) {
  975. customValue = value;
  976. }
  977. break;
  978. }
  979. if (customValue === undefined) {
  980. (0, _util.warn)(`Bad value, for custom key "${key}", in Info: ${value}.`);
  981. continue;
  982. }
  983. if (!docInfo.Custom) {
  984. docInfo.Custom = Object.create(null);
  985. }
  986. docInfo.Custom[key] = customValue;
  987. continue;
  988. }
  989. (0, _util.warn)(`Bad value, for key "${key}", in Info: ${value}.`);
  990. }
  991. return (0, _util.shadow)(this, "documentInfo", docInfo);
  992. }
  993. get fingerprints() {
  994. function validate(data) {
  995. return typeof data === "string" && data.length > 0 && data !== EMPTY_FINGERPRINT;
  996. }
  997. function hexString(hash) {
  998. const buf = [];
  999. for (let i = 0, ii = hash.length; i < ii; i++) {
  1000. const hex = hash[i].toString(16);
  1001. buf.push(hex.padStart(2, "0"));
  1002. }
  1003. return buf.join("");
  1004. }
  1005. const idArray = this.xref.trailer.get("ID");
  1006. let hashOriginal, hashModified;
  1007. if (Array.isArray(idArray) && validate(idArray[0])) {
  1008. hashOriginal = (0, _util.stringToBytes)(idArray[0]);
  1009. if (idArray[1] !== idArray[0] && validate(idArray[1])) {
  1010. hashModified = (0, _util.stringToBytes)(idArray[1]);
  1011. }
  1012. } else {
  1013. hashOriginal = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  1014. }
  1015. return (0, _util.shadow)(this, "fingerprints", [hexString(hashOriginal), hashModified ? hexString(hashModified) : null]);
  1016. }
  1017. async _getLinearizationPage(pageIndex) {
  1018. const {
  1019. catalog,
  1020. linearization,
  1021. xref
  1022. } = this;
  1023. const ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
  1024. try {
  1025. const obj = await xref.fetchAsync(ref);
  1026. if (obj instanceof _primitives.Dict) {
  1027. let type = obj.getRaw("Type");
  1028. if (type instanceof _primitives.Ref) {
  1029. type = await xref.fetchAsync(type);
  1030. }
  1031. if ((0, _primitives.isName)(type, "Page") || !obj.has("Type") && !obj.has("Kids")) {
  1032. if (!catalog.pageKidsCountCache.has(ref)) {
  1033. catalog.pageKidsCountCache.put(ref, 1);
  1034. }
  1035. if (!catalog.pageIndexCache.has(ref)) {
  1036. catalog.pageIndexCache.put(ref, 0);
  1037. }
  1038. return [obj, ref];
  1039. }
  1040. }
  1041. throw new _util.FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.");
  1042. } catch (reason) {
  1043. (0, _util.warn)(`_getLinearizationPage: "${reason.message}".`);
  1044. return catalog.getPageDict(pageIndex);
  1045. }
  1046. }
  1047. getPage(pageIndex) {
  1048. const cachedPromise = this._pagePromises.get(pageIndex);
  1049. if (cachedPromise) {
  1050. return cachedPromise;
  1051. }
  1052. const {
  1053. catalog,
  1054. linearization,
  1055. xfaFactory
  1056. } = this;
  1057. let promise;
  1058. if (xfaFactory) {
  1059. promise = Promise.resolve([_primitives.Dict.empty, null]);
  1060. } else if (linearization && linearization.pageFirst === pageIndex) {
  1061. promise = this._getLinearizationPage(pageIndex);
  1062. } else {
  1063. promise = catalog.getPageDict(pageIndex);
  1064. }
  1065. promise = promise.then(([pageDict, ref]) => {
  1066. return new Page({
  1067. pdfManager: this.pdfManager,
  1068. xref: this.xref,
  1069. pageIndex,
  1070. pageDict,
  1071. ref,
  1072. globalIdFactory: this._globalIdFactory,
  1073. fontCache: catalog.fontCache,
  1074. builtInCMapCache: catalog.builtInCMapCache,
  1075. standardFontDataCache: catalog.standardFontDataCache,
  1076. globalImageCache: catalog.globalImageCache,
  1077. nonBlendModesSet: catalog.nonBlendModesSet,
  1078. xfaFactory
  1079. });
  1080. });
  1081. this._pagePromises.set(pageIndex, promise);
  1082. return promise;
  1083. }
  1084. async checkFirstPage(recoveryMode = false) {
  1085. if (recoveryMode) {
  1086. return;
  1087. }
  1088. try {
  1089. await this.getPage(0);
  1090. } catch (reason) {
  1091. if (reason instanceof _core_utils.XRefEntryException) {
  1092. this._pagePromises.delete(0);
  1093. await this.cleanup();
  1094. throw new _core_utils.XRefParseException();
  1095. }
  1096. }
  1097. }
  1098. async checkLastPage(recoveryMode = false) {
  1099. const {
  1100. catalog,
  1101. pdfManager
  1102. } = this;
  1103. catalog.setActualNumPages();
  1104. let numPages;
  1105. try {
  1106. await Promise.all([pdfManager.ensureDoc("xfaFactory"), pdfManager.ensureDoc("linearization"), pdfManager.ensureCatalog("numPages")]);
  1107. if (this.xfaFactory) {
  1108. return;
  1109. } else if (this.linearization) {
  1110. numPages = this.linearization.numPages;
  1111. } else {
  1112. numPages = catalog.numPages;
  1113. }
  1114. if (!Number.isInteger(numPages)) {
  1115. throw new _util.FormatError("Page count is not an integer.");
  1116. } else if (numPages <= 1) {
  1117. return;
  1118. }
  1119. await this.getPage(numPages - 1);
  1120. } catch (reason) {
  1121. this._pagePromises.delete(numPages - 1);
  1122. await this.cleanup();
  1123. if (reason instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1124. throw new _core_utils.XRefParseException();
  1125. }
  1126. (0, _util.warn)(`checkLastPage - invalid /Pages tree /Count: ${numPages}.`);
  1127. let pagesTree;
  1128. try {
  1129. pagesTree = await catalog.getAllPageDicts(recoveryMode);
  1130. } catch (reasonAll) {
  1131. if (reasonAll instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1132. throw new _core_utils.XRefParseException();
  1133. }
  1134. catalog.setActualNumPages(1);
  1135. return;
  1136. }
  1137. for (const [pageIndex, [pageDict, ref]] of pagesTree) {
  1138. let promise;
  1139. if (pageDict instanceof Error) {
  1140. promise = Promise.reject(pageDict);
  1141. promise.catch(() => {});
  1142. } else {
  1143. promise = Promise.resolve(new Page({
  1144. pdfManager,
  1145. xref: this.xref,
  1146. pageIndex,
  1147. pageDict,
  1148. ref,
  1149. globalIdFactory: this._globalIdFactory,
  1150. fontCache: catalog.fontCache,
  1151. builtInCMapCache: catalog.builtInCMapCache,
  1152. standardFontDataCache: catalog.standardFontDataCache,
  1153. globalImageCache: catalog.globalImageCache,
  1154. nonBlendModesSet: catalog.nonBlendModesSet,
  1155. xfaFactory: null
  1156. }));
  1157. }
  1158. this._pagePromises.set(pageIndex, promise);
  1159. }
  1160. catalog.setActualNumPages(pagesTree.size);
  1161. }
  1162. }
  1163. fontFallback(id, handler) {
  1164. return this.catalog.fontFallback(id, handler);
  1165. }
  1166. async cleanup(manuallyTriggered = false) {
  1167. return this.catalog ? this.catalog.cleanup(manuallyTriggered) : (0, _cleanup_helper.clearGlobalCaches)();
  1168. }
  1169. _collectFieldObjects(name, fieldRef, promises) {
  1170. const field = this.xref.fetchIfRef(fieldRef);
  1171. if (field.has("T")) {
  1172. const partName = (0, _util.stringToPDFString)(field.get("T"));
  1173. if (name === "") {
  1174. name = partName;
  1175. } else {
  1176. name = `${name}.${partName}`;
  1177. }
  1178. }
  1179. if (!promises.has(name)) {
  1180. promises.set(name, []);
  1181. }
  1182. promises.get(name).push(_annotation.AnnotationFactory.create(this.xref, fieldRef, this.pdfManager, this._localIdFactory, true).then(annotation => annotation && annotation.getFieldObject()).catch(function (reason) {
  1183. (0, _util.warn)(`_collectFieldObjects: "${reason}".`);
  1184. return null;
  1185. }));
  1186. if (field.has("Kids")) {
  1187. const kids = field.get("Kids");
  1188. for (const kid of kids) {
  1189. this._collectFieldObjects(name, kid, promises);
  1190. }
  1191. }
  1192. }
  1193. get fieldObjects() {
  1194. if (!this.formInfo.hasFields) {
  1195. return (0, _util.shadow)(this, "fieldObjects", Promise.resolve(null));
  1196. }
  1197. const allFields = Object.create(null);
  1198. const fieldPromises = new Map();
  1199. for (const fieldRef of this.catalog.acroForm.get("Fields")) {
  1200. this._collectFieldObjects("", fieldRef, fieldPromises);
  1201. }
  1202. const allPromises = [];
  1203. for (const [name, promises] of fieldPromises) {
  1204. allPromises.push(Promise.all(promises).then(fields => {
  1205. fields = fields.filter(field => !!field);
  1206. if (fields.length > 0) {
  1207. allFields[name] = fields;
  1208. }
  1209. }));
  1210. }
  1211. return (0, _util.shadow)(this, "fieldObjects", Promise.all(allPromises).then(() => allFields));
  1212. }
  1213. get hasJSActions() {
  1214. const promise = this.pdfManager.ensureDoc("_parseHasJSActions");
  1215. return (0, _util.shadow)(this, "hasJSActions", promise);
  1216. }
  1217. async _parseHasJSActions() {
  1218. const [catalogJsActions, fieldObjects] = await Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]);
  1219. if (catalogJsActions) {
  1220. return true;
  1221. }
  1222. if (fieldObjects) {
  1223. return Object.values(fieldObjects).some(fieldObject => fieldObject.some(object => object.actions !== null));
  1224. }
  1225. return false;
  1226. }
  1227. get calculationOrderIds() {
  1228. const acroForm = this.catalog.acroForm;
  1229. if (!acroForm || !acroForm.has("CO")) {
  1230. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1231. }
  1232. const calculationOrder = acroForm.get("CO");
  1233. if (!Array.isArray(calculationOrder) || calculationOrder.length === 0) {
  1234. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1235. }
  1236. const ids = [];
  1237. for (const id of calculationOrder) {
  1238. if (id instanceof _primitives.Ref) {
  1239. ids.push(id.toString());
  1240. }
  1241. }
  1242. if (ids.length === 0) {
  1243. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1244. }
  1245. return (0, _util.shadow)(this, "calculationOrderIds", ids);
  1246. }
  1247. }
  1248. exports.PDFDocument = PDFDocument;