document.js 35 KB

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