document.js 26 KB

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