document.js 26 KB

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