document.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2019 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");
  28. var _obj = require("./obj");
  29. var _primitives = require("./primitives");
  30. var _core_utils = require("./core_utils");
  31. var _stream2 = require("./stream");
  32. var _annotation = require("./annotation");
  33. var _crypto = require("./crypto");
  34. var _parser = require("./parser");
  35. var _operator_list = require("./operator_list");
  36. var _evaluator = require("./evaluator");
  37. var _function = require("./function");
  38. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
  39. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
  40. function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  41. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  42. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  43. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  44. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  45. var DEFAULT_USER_UNIT = 1.0;
  46. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  47. function isAnnotationRenderable(annotation, intent) {
  48. return intent === 'display' && annotation.viewable || intent === 'print' && annotation.printable;
  49. }
  50. var Page =
  51. /*#__PURE__*/
  52. function () {
  53. function Page(_ref) {
  54. var pdfManager = _ref.pdfManager,
  55. xref = _ref.xref,
  56. pageIndex = _ref.pageIndex,
  57. pageDict = _ref.pageDict,
  58. ref = _ref.ref,
  59. fontCache = _ref.fontCache,
  60. builtInCMapCache = _ref.builtInCMapCache,
  61. pdfFunctionFactory = _ref.pdfFunctionFactory;
  62. _classCallCheck(this, Page);
  63. this.pdfManager = pdfManager;
  64. this.pageIndex = pageIndex;
  65. this.pageDict = pageDict;
  66. this.xref = xref;
  67. this.ref = ref;
  68. this.fontCache = fontCache;
  69. this.builtInCMapCache = builtInCMapCache;
  70. this.pdfFunctionFactory = pdfFunctionFactory;
  71. this.evaluatorOptions = pdfManager.evaluatorOptions;
  72. this.resourcesPromise = null;
  73. var idCounters = {
  74. obj: 0
  75. };
  76. this.idFactory = {
  77. createObjId: function createObjId() {
  78. return "p".concat(pageIndex, "_").concat(++idCounters.obj);
  79. },
  80. getDocId: function getDocId() {
  81. return "g_".concat(pdfManager.docId);
  82. }
  83. };
  84. }
  85. _createClass(Page, [{
  86. key: "_getInheritableProperty",
  87. value: function _getInheritableProperty(key) {
  88. var getArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  89. var value = (0, _core_utils.getInheritableProperty)({
  90. dict: this.pageDict,
  91. key: key,
  92. getArray: getArray,
  93. stopWhenFound: false
  94. });
  95. if (!Array.isArray(value)) {
  96. return value;
  97. }
  98. if (value.length === 1 || !(0, _primitives.isDict)(value[0])) {
  99. return value[0];
  100. }
  101. return _primitives.Dict.merge(this.xref, value);
  102. }
  103. }, {
  104. key: "_getBoundingBox",
  105. value: function _getBoundingBox(name) {
  106. var box = this._getInheritableProperty(name, true);
  107. if (Array.isArray(box) && box.length === 4) {
  108. if (box[2] - box[0] !== 0 && box[3] - box[1] !== 0) {
  109. return box;
  110. }
  111. (0, _util.warn)("Empty /".concat(name, " entry."));
  112. }
  113. return null;
  114. }
  115. }, {
  116. key: "getContentStream",
  117. value: function getContentStream() {
  118. var content = this.content;
  119. var stream;
  120. if (Array.isArray(content)) {
  121. var xref = this.xref;
  122. var streams = [];
  123. var _iteratorNormalCompletion = true;
  124. var _didIteratorError = false;
  125. var _iteratorError = undefined;
  126. try {
  127. for (var _iterator = content[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  128. var _stream = _step.value;
  129. streams.push(xref.fetchIfRef(_stream));
  130. }
  131. } catch (err) {
  132. _didIteratorError = true;
  133. _iteratorError = err;
  134. } finally {
  135. try {
  136. if (!_iteratorNormalCompletion && _iterator["return"] != null) {
  137. _iterator["return"]();
  138. }
  139. } finally {
  140. if (_didIteratorError) {
  141. throw _iteratorError;
  142. }
  143. }
  144. }
  145. stream = new _stream2.StreamsSequenceStream(streams);
  146. } else if ((0, _primitives.isStream)(content)) {
  147. stream = content;
  148. } else {
  149. stream = new _stream2.NullStream();
  150. }
  151. return stream;
  152. }
  153. }, {
  154. key: "loadResources",
  155. value: function loadResources(keys) {
  156. var _this = this;
  157. if (!this.resourcesPromise) {
  158. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  159. }
  160. return this.resourcesPromise.then(function () {
  161. var objectLoader = new _obj.ObjectLoader(_this.resources, keys, _this.xref);
  162. return objectLoader.load();
  163. });
  164. }
  165. }, {
  166. key: "getOperatorList",
  167. value: function getOperatorList(_ref2) {
  168. var _this2 = this;
  169. var handler = _ref2.handler,
  170. sink = _ref2.sink,
  171. task = _ref2.task,
  172. intent = _ref2.intent,
  173. renderInteractiveForms = _ref2.renderInteractiveForms;
  174. var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream');
  175. var resourcesPromise = this.loadResources(['ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font']);
  176. var partialEvaluator = new _evaluator.PartialEvaluator({
  177. xref: this.xref,
  178. handler: handler,
  179. pageIndex: this.pageIndex,
  180. idFactory: this.idFactory,
  181. fontCache: this.fontCache,
  182. builtInCMapCache: this.builtInCMapCache,
  183. options: this.evaluatorOptions,
  184. pdfFunctionFactory: this.pdfFunctionFactory
  185. });
  186. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  187. var pageListPromise = dataPromises.then(function (_ref3) {
  188. var _ref4 = _slicedToArray(_ref3, 1),
  189. contentStream = _ref4[0];
  190. var opList = new _operator_list.OperatorList(intent, sink, _this2.pageIndex);
  191. handler.send('StartRenderPage', {
  192. transparency: partialEvaluator.hasBlendModes(_this2.resources),
  193. pageIndex: _this2.pageIndex,
  194. intent: intent
  195. });
  196. return partialEvaluator.getOperatorList({
  197. stream: contentStream,
  198. task: task,
  199. resources: _this2.resources,
  200. operatorList: opList
  201. }).then(function () {
  202. return opList;
  203. });
  204. });
  205. return Promise.all([pageListPromise, this._parsedAnnotations]).then(function (_ref5) {
  206. var _ref6 = _slicedToArray(_ref5, 2),
  207. pageOpList = _ref6[0],
  208. annotations = _ref6[1];
  209. if (annotations.length === 0) {
  210. pageOpList.flush(true);
  211. return {
  212. length: pageOpList.totalLength
  213. };
  214. }
  215. var opListPromises = [];
  216. var _iteratorNormalCompletion2 = true;
  217. var _didIteratorError2 = false;
  218. var _iteratorError2 = undefined;
  219. try {
  220. for (var _iterator2 = annotations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  221. var annotation = _step2.value;
  222. if (isAnnotationRenderable(annotation, intent)) {
  223. opListPromises.push(annotation.getOperatorList(partialEvaluator, task, renderInteractiveForms));
  224. }
  225. }
  226. } catch (err) {
  227. _didIteratorError2 = true;
  228. _iteratorError2 = err;
  229. } finally {
  230. try {
  231. if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
  232. _iterator2["return"]();
  233. }
  234. } finally {
  235. if (_didIteratorError2) {
  236. throw _iteratorError2;
  237. }
  238. }
  239. }
  240. return Promise.all(opListPromises).then(function (opLists) {
  241. pageOpList.addOp(_util.OPS.beginAnnotations, []);
  242. var _iteratorNormalCompletion3 = true;
  243. var _didIteratorError3 = false;
  244. var _iteratorError3 = undefined;
  245. try {
  246. for (var _iterator3 = opLists[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  247. var opList = _step3.value;
  248. pageOpList.addOpList(opList);
  249. }
  250. } catch (err) {
  251. _didIteratorError3 = true;
  252. _iteratorError3 = err;
  253. } finally {
  254. try {
  255. if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
  256. _iterator3["return"]();
  257. }
  258. } finally {
  259. if (_didIteratorError3) {
  260. throw _iteratorError3;
  261. }
  262. }
  263. }
  264. pageOpList.addOp(_util.OPS.endAnnotations, []);
  265. pageOpList.flush(true);
  266. return {
  267. length: pageOpList.totalLength
  268. };
  269. });
  270. });
  271. }
  272. }, {
  273. key: "extractTextContent",
  274. value: function extractTextContent(_ref7) {
  275. var _this3 = this;
  276. var handler = _ref7.handler,
  277. task = _ref7.task,
  278. normalizeWhitespace = _ref7.normalizeWhitespace,
  279. sink = _ref7.sink,
  280. combineTextItems = _ref7.combineTextItems;
  281. var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream');
  282. var resourcesPromise = this.loadResources(['ExtGState', 'XObject', 'Font']);
  283. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  284. return dataPromises.then(function (_ref8) {
  285. var _ref9 = _slicedToArray(_ref8, 1),
  286. contentStream = _ref9[0];
  287. var partialEvaluator = new _evaluator.PartialEvaluator({
  288. xref: _this3.xref,
  289. handler: handler,
  290. pageIndex: _this3.pageIndex,
  291. idFactory: _this3.idFactory,
  292. fontCache: _this3.fontCache,
  293. builtInCMapCache: _this3.builtInCMapCache,
  294. options: _this3.evaluatorOptions,
  295. pdfFunctionFactory: _this3.pdfFunctionFactory
  296. });
  297. return partialEvaluator.getTextContent({
  298. stream: contentStream,
  299. task: task,
  300. resources: _this3.resources,
  301. normalizeWhitespace: normalizeWhitespace,
  302. combineTextItems: combineTextItems,
  303. sink: sink
  304. });
  305. });
  306. }
  307. }, {
  308. key: "getAnnotationsData",
  309. value: function getAnnotationsData(intent) {
  310. return this._parsedAnnotations.then(function (annotations) {
  311. var annotationsData = [];
  312. for (var i = 0, ii = annotations.length; i < ii; i++) {
  313. if (!intent || isAnnotationRenderable(annotations[i], intent)) {
  314. annotationsData.push(annotations[i].data);
  315. }
  316. }
  317. return annotationsData;
  318. });
  319. }
  320. }, {
  321. key: "content",
  322. get: function get() {
  323. return this.pageDict.get('Contents');
  324. }
  325. }, {
  326. key: "resources",
  327. get: function get() {
  328. return (0, _util.shadow)(this, 'resources', this._getInheritableProperty('Resources') || _primitives.Dict.empty);
  329. }
  330. }, {
  331. key: "mediaBox",
  332. get: function get() {
  333. return (0, _util.shadow)(this, 'mediaBox', this._getBoundingBox('MediaBox') || LETTER_SIZE_MEDIABOX);
  334. }
  335. }, {
  336. key: "cropBox",
  337. get: function get() {
  338. return (0, _util.shadow)(this, 'cropBox', this._getBoundingBox('CropBox') || this.mediaBox);
  339. }
  340. }, {
  341. key: "userUnit",
  342. get: function get() {
  343. var obj = this.pageDict.get('UserUnit');
  344. if (!(0, _util.isNum)(obj) || obj <= 0) {
  345. obj = DEFAULT_USER_UNIT;
  346. }
  347. return (0, _util.shadow)(this, 'userUnit', obj);
  348. }
  349. }, {
  350. key: "view",
  351. get: function get() {
  352. var cropBox = this.cropBox,
  353. mediaBox = this.mediaBox;
  354. var view;
  355. if (cropBox === mediaBox || (0, _util.isArrayEqual)(cropBox, mediaBox)) {
  356. view = mediaBox;
  357. } else {
  358. var box = _util.Util.intersect(cropBox, mediaBox);
  359. if (box && box[2] - box[0] !== 0 && box[3] - box[1] !== 0) {
  360. view = box;
  361. } else {
  362. (0, _util.warn)('Empty /CropBox and /MediaBox intersection.');
  363. }
  364. }
  365. return (0, _util.shadow)(this, 'view', view || mediaBox);
  366. }
  367. }, {
  368. key: "rotate",
  369. get: function get() {
  370. var rotate = this._getInheritableProperty('Rotate') || 0;
  371. if (rotate % 90 !== 0) {
  372. rotate = 0;
  373. } else if (rotate >= 360) {
  374. rotate = rotate % 360;
  375. } else if (rotate < 0) {
  376. rotate = (rotate % 360 + 360) % 360;
  377. }
  378. return (0, _util.shadow)(this, 'rotate', rotate);
  379. }
  380. }, {
  381. key: "annotations",
  382. get: function get() {
  383. return (0, _util.shadow)(this, 'annotations', this._getInheritableProperty('Annots') || []);
  384. }
  385. }, {
  386. key: "_parsedAnnotations",
  387. get: function get() {
  388. var _this4 = this;
  389. var parsedAnnotations = this.pdfManager.ensure(this, 'annotations').then(function () {
  390. var annotationRefs = _this4.annotations;
  391. var annotationPromises = [];
  392. for (var i = 0, ii = annotationRefs.length; i < ii; i++) {
  393. annotationPromises.push(_annotation.AnnotationFactory.create(_this4.xref, annotationRefs[i], _this4.pdfManager, _this4.idFactory));
  394. }
  395. return Promise.all(annotationPromises).then(function (annotations) {
  396. return annotations.filter(function isDefined(annotation) {
  397. return !!annotation;
  398. });
  399. }, function (reason) {
  400. (0, _util.warn)("_parsedAnnotations: \"".concat(reason, "\"."));
  401. return [];
  402. });
  403. });
  404. return (0, _util.shadow)(this, '_parsedAnnotations', parsedAnnotations);
  405. }
  406. }]);
  407. return Page;
  408. }();
  409. exports.Page = Page;
  410. var FINGERPRINT_FIRST_BYTES = 1024;
  411. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  412. function find(stream, needle, limit) {
  413. var backwards = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  414. (0, _util.assert)(limit > 0, 'The "limit" must be a positive integer.');
  415. var str = (0, _util.bytesToString)(stream.peekBytes(limit));
  416. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  417. if (index === -1) {
  418. return false;
  419. }
  420. stream.pos += index;
  421. return true;
  422. }
  423. var PDFDocument =
  424. /*#__PURE__*/
  425. function () {
  426. function PDFDocument(pdfManager, arg) {
  427. _classCallCheck(this, PDFDocument);
  428. var stream;
  429. if ((0, _primitives.isStream)(arg)) {
  430. stream = arg;
  431. } else if ((0, _util.isArrayBuffer)(arg)) {
  432. stream = new _stream2.Stream(arg);
  433. } else {
  434. throw new Error('PDFDocument: Unknown argument type');
  435. }
  436. if (stream.length <= 0) {
  437. throw new Error('PDFDocument: Stream must have data');
  438. }
  439. this.pdfManager = pdfManager;
  440. this.stream = stream;
  441. this.xref = new _obj.XRef(stream, pdfManager);
  442. this.pdfFunctionFactory = new _function.PDFFunctionFactory({
  443. xref: this.xref,
  444. isEvalSupported: pdfManager.evaluatorOptions.isEvalSupported
  445. });
  446. this._pagePromises = [];
  447. }
  448. _createClass(PDFDocument, [{
  449. key: "parse",
  450. value: function parse(recoveryMode) {
  451. this.setup(recoveryMode);
  452. var version = this.catalog.catDict.get('Version');
  453. if ((0, _primitives.isName)(version)) {
  454. this.pdfFormatVersion = version.name;
  455. }
  456. try {
  457. this.acroForm = this.catalog.catDict.get('AcroForm');
  458. if (this.acroForm) {
  459. this.xfa = this.acroForm.get('XFA');
  460. var fields = this.acroForm.get('Fields');
  461. if ((!Array.isArray(fields) || fields.length === 0) && !this.xfa) {
  462. this.acroForm = null;
  463. }
  464. }
  465. } catch (ex) {
  466. if (ex instanceof _core_utils.MissingDataException) {
  467. throw ex;
  468. }
  469. (0, _util.info)('Cannot fetch AcroForm entry; assuming no AcroForms are present');
  470. this.acroForm = null;
  471. }
  472. try {
  473. var collection = this.catalog.catDict.get('Collection');
  474. if ((0, _primitives.isDict)(collection) && collection.getKeys().length > 0) {
  475. this.collection = collection;
  476. }
  477. } catch (ex) {
  478. if (ex instanceof _core_utils.MissingDataException) {
  479. throw ex;
  480. }
  481. (0, _util.info)('Cannot fetch Collection dictionary.');
  482. }
  483. }
  484. }, {
  485. key: "checkHeader",
  486. value: function checkHeader() {
  487. var stream = this.stream;
  488. stream.reset();
  489. if (!find(stream, '%PDF-', 1024)) {
  490. return;
  491. }
  492. stream.moveStart();
  493. var MAX_PDF_VERSION_LENGTH = 12;
  494. var version = '',
  495. ch;
  496. while ((ch = stream.getByte()) > 0x20) {
  497. if (version.length >= MAX_PDF_VERSION_LENGTH) {
  498. break;
  499. }
  500. version += String.fromCharCode(ch);
  501. }
  502. if (!this.pdfFormatVersion) {
  503. this.pdfFormatVersion = version.substring(5);
  504. }
  505. }
  506. }, {
  507. key: "parseStartXRef",
  508. value: function parseStartXRef() {
  509. this.xref.setStartXRef(this.startXRef);
  510. }
  511. }, {
  512. key: "setup",
  513. value: function setup(recoveryMode) {
  514. this.xref.parse(recoveryMode);
  515. this.catalog = new _obj.Catalog(this.pdfManager, this.xref);
  516. }
  517. }, {
  518. key: "_getLinearizationPage",
  519. value: function _getLinearizationPage(pageIndex) {
  520. var catalog = this.catalog,
  521. linearization = this.linearization;
  522. (0, _util.assert)(linearization && linearization.pageFirst === pageIndex);
  523. var ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
  524. return this.xref.fetchAsync(ref).then(function (obj) {
  525. if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Type') && obj.has('Contents')) {
  526. if (ref && !catalog.pageKidsCountCache.has(ref)) {
  527. catalog.pageKidsCountCache.put(ref, 1);
  528. }
  529. return [obj, ref];
  530. }
  531. throw new _util.FormatError('The Linearization dictionary doesn\'t point ' + 'to a valid Page dictionary.');
  532. })["catch"](function (reason) {
  533. (0, _util.info)(reason);
  534. return catalog.getPageDict(pageIndex);
  535. });
  536. }
  537. }, {
  538. key: "getPage",
  539. value: function getPage(pageIndex) {
  540. var _this5 = this;
  541. if (this._pagePromises[pageIndex] !== undefined) {
  542. return this._pagePromises[pageIndex];
  543. }
  544. var catalog = this.catalog,
  545. linearization = this.linearization;
  546. var promise = linearization && linearization.pageFirst === pageIndex ? this._getLinearizationPage(pageIndex) : catalog.getPageDict(pageIndex);
  547. return this._pagePromises[pageIndex] = promise.then(function (_ref10) {
  548. var _ref11 = _slicedToArray(_ref10, 2),
  549. pageDict = _ref11[0],
  550. ref = _ref11[1];
  551. return new Page({
  552. pdfManager: _this5.pdfManager,
  553. xref: _this5.xref,
  554. pageIndex: pageIndex,
  555. pageDict: pageDict,
  556. ref: ref,
  557. fontCache: catalog.fontCache,
  558. builtInCMapCache: catalog.builtInCMapCache,
  559. pdfFunctionFactory: _this5.pdfFunctionFactory
  560. });
  561. });
  562. }
  563. }, {
  564. key: "checkFirstPage",
  565. value: function checkFirstPage() {
  566. var _this6 = this;
  567. return this.getPage(0)["catch"](function (reason) {
  568. if (reason instanceof _core_utils.XRefEntryException) {
  569. _this6._pagePromises.length = 0;
  570. _this6.cleanup();
  571. throw new _core_utils.XRefParseException();
  572. }
  573. });
  574. }
  575. }, {
  576. key: "fontFallback",
  577. value: function fontFallback(id, handler) {
  578. return this.catalog.fontFallback(id, handler);
  579. }
  580. }, {
  581. key: "cleanup",
  582. value: function cleanup() {
  583. return this.catalog.cleanup();
  584. }
  585. }, {
  586. key: "linearization",
  587. get: function get() {
  588. var linearization = null;
  589. try {
  590. linearization = _parser.Linearization.create(this.stream);
  591. } catch (err) {
  592. if (err instanceof _core_utils.MissingDataException) {
  593. throw err;
  594. }
  595. (0, _util.info)(err);
  596. }
  597. return (0, _util.shadow)(this, 'linearization', linearization);
  598. }
  599. }, {
  600. key: "startXRef",
  601. get: function get() {
  602. var stream = this.stream;
  603. var startXRef = 0;
  604. if (this.linearization) {
  605. stream.reset();
  606. if (find(stream, 'endobj', 1024)) {
  607. startXRef = stream.pos + 6;
  608. }
  609. } else {
  610. var step = 1024;
  611. var startXRefLength = 'startxref'.length;
  612. var found = false,
  613. pos = stream.end;
  614. while (!found && pos > 0) {
  615. pos -= step - startXRefLength;
  616. if (pos < 0) {
  617. pos = 0;
  618. }
  619. stream.pos = pos;
  620. found = find(stream, 'startxref', step, true);
  621. }
  622. if (found) {
  623. stream.skip(9);
  624. var ch;
  625. do {
  626. ch = stream.getByte();
  627. } while ((0, _util.isSpace)(ch));
  628. var str = '';
  629. while (ch >= 0x20 && ch <= 0x39) {
  630. str += String.fromCharCode(ch);
  631. ch = stream.getByte();
  632. }
  633. startXRef = parseInt(str, 10);
  634. if (isNaN(startXRef)) {
  635. startXRef = 0;
  636. }
  637. }
  638. }
  639. return (0, _util.shadow)(this, 'startXRef', startXRef);
  640. }
  641. }, {
  642. key: "numPages",
  643. get: function get() {
  644. var linearization = this.linearization;
  645. var num = linearization ? linearization.numPages : this.catalog.numPages;
  646. return (0, _util.shadow)(this, 'numPages', num);
  647. }
  648. }, {
  649. key: "documentInfo",
  650. get: function get() {
  651. var DocumentInfoValidators = {
  652. Title: _util.isString,
  653. Author: _util.isString,
  654. Subject: _util.isString,
  655. Keywords: _util.isString,
  656. Creator: _util.isString,
  657. Producer: _util.isString,
  658. CreationDate: _util.isString,
  659. ModDate: _util.isString,
  660. Trapped: _primitives.isName
  661. };
  662. var docInfo = {
  663. PDFFormatVersion: this.pdfFormatVersion,
  664. IsLinearized: !!this.linearization,
  665. IsAcroFormPresent: !!this.acroForm,
  666. IsXFAPresent: !!this.xfa,
  667. IsCollectionPresent: !!this.collection
  668. };
  669. var infoDict;
  670. try {
  671. infoDict = this.xref.trailer.get('Info');
  672. } catch (err) {
  673. if (err instanceof _core_utils.MissingDataException) {
  674. throw err;
  675. }
  676. (0, _util.info)('The document information dictionary is invalid.');
  677. }
  678. if ((0, _primitives.isDict)(infoDict)) {
  679. var _iteratorNormalCompletion4 = true;
  680. var _didIteratorError4 = false;
  681. var _iteratorError4 = undefined;
  682. try {
  683. for (var _iterator4 = infoDict.getKeys()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
  684. var key = _step4.value;
  685. var value = infoDict.get(key);
  686. if (DocumentInfoValidators[key]) {
  687. if (DocumentInfoValidators[key](value)) {
  688. docInfo[key] = typeof value !== 'string' ? value : (0, _util.stringToPDFString)(value);
  689. } else {
  690. (0, _util.info)("Bad value in document info for \"".concat(key, "\"."));
  691. }
  692. } else if (typeof key === 'string') {
  693. var customValue = void 0;
  694. if ((0, _util.isString)(value)) {
  695. customValue = (0, _util.stringToPDFString)(value);
  696. } else if ((0, _primitives.isName)(value) || (0, _util.isNum)(value) || (0, _util.isBool)(value)) {
  697. customValue = value;
  698. } else {
  699. (0, _util.info)("Unsupported value in document info for (custom) \"".concat(key, "\"."));
  700. continue;
  701. }
  702. if (!docInfo['Custom']) {
  703. docInfo['Custom'] = Object.create(null);
  704. }
  705. docInfo['Custom'][key] = customValue;
  706. }
  707. }
  708. } catch (err) {
  709. _didIteratorError4 = true;
  710. _iteratorError4 = err;
  711. } finally {
  712. try {
  713. if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
  714. _iterator4["return"]();
  715. }
  716. } finally {
  717. if (_didIteratorError4) {
  718. throw _iteratorError4;
  719. }
  720. }
  721. }
  722. }
  723. return (0, _util.shadow)(this, 'documentInfo', docInfo);
  724. }
  725. }, {
  726. key: "fingerprint",
  727. get: function get() {
  728. var hash;
  729. var idArray = this.xref.trailer.get('ID');
  730. if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
  731. hash = (0, _util.stringToBytes)(idArray[0]);
  732. } else {
  733. hash = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  734. }
  735. var fingerprintBuf = [];
  736. for (var i = 0, ii = hash.length; i < ii; i++) {
  737. var hex = hash[i].toString(16);
  738. fingerprintBuf.push(hex.padStart(2, '0'));
  739. }
  740. return (0, _util.shadow)(this, 'fingerprint', fingerprintBuf.join(''));
  741. }
  742. }]);
  743. return PDFDocument;
  744. }();
  745. exports.PDFDocument = PDFDocument;