document.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 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 = undefined;
  27. var _slicedToArray = function () { function sliceIterator(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"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  28. var _obj = require('./obj');
  29. var _primitives = require('./primitives');
  30. var _util = require('../shared/util');
  31. var _stream = 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. var Page = function PageClosure() {
  39. var DEFAULT_USER_UNIT = 1.0;
  40. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  41. function isAnnotationRenderable(annotation, intent) {
  42. return intent === 'display' && annotation.viewable || intent === 'print' && annotation.printable;
  43. }
  44. function Page(_ref) {
  45. var pdfManager = _ref.pdfManager,
  46. xref = _ref.xref,
  47. pageIndex = _ref.pageIndex,
  48. pageDict = _ref.pageDict,
  49. ref = _ref.ref,
  50. fontCache = _ref.fontCache,
  51. builtInCMapCache = _ref.builtInCMapCache,
  52. pdfFunctionFactory = _ref.pdfFunctionFactory;
  53. this.pdfManager = pdfManager;
  54. this.pageIndex = pageIndex;
  55. this.pageDict = pageDict;
  56. this.xref = xref;
  57. this.ref = ref;
  58. this.fontCache = fontCache;
  59. this.builtInCMapCache = builtInCMapCache;
  60. this.pdfFunctionFactory = pdfFunctionFactory;
  61. this.evaluatorOptions = pdfManager.evaluatorOptions;
  62. this.resourcesPromise = null;
  63. var uniquePrefix = 'p' + this.pageIndex + '_';
  64. var idCounters = { obj: 0 };
  65. this.idFactory = {
  66. createObjId: function createObjId() {
  67. return uniquePrefix + ++idCounters.obj;
  68. }
  69. };
  70. }
  71. Page.prototype = {
  72. getPageProp: function Page_getPageProp(key) {
  73. return this.pageDict.get(key);
  74. },
  75. getInheritedPageProp: function Page_getInheritedPageProp(key, getArray) {
  76. var dict = this.pageDict,
  77. valueArray = null,
  78. loopCount = 0;
  79. var MAX_LOOP_COUNT = 100;
  80. getArray = getArray || false;
  81. while (dict) {
  82. var value = getArray ? dict.getArray(key) : dict.get(key);
  83. if (value !== undefined) {
  84. if (!valueArray) {
  85. valueArray = [];
  86. }
  87. valueArray.push(value);
  88. }
  89. if (++loopCount > MAX_LOOP_COUNT) {
  90. (0, _util.warn)('getInheritedPageProp: maximum loop count exceeded for ' + key);
  91. return valueArray ? valueArray[0] : undefined;
  92. }
  93. dict = dict.get('Parent');
  94. }
  95. if (!valueArray) {
  96. return undefined;
  97. }
  98. if (valueArray.length === 1 || !(0, _primitives.isDict)(valueArray[0])) {
  99. return valueArray[0];
  100. }
  101. return _primitives.Dict.merge(this.xref, valueArray);
  102. },
  103. get content() {
  104. return this.getPageProp('Contents');
  105. },
  106. get resources() {
  107. return (0, _util.shadow)(this, 'resources', this.getInheritedPageProp('Resources') || _primitives.Dict.empty);
  108. },
  109. get mediaBox() {
  110. var mediaBox = this.getInheritedPageProp('MediaBox', true);
  111. if (!Array.isArray(mediaBox) || mediaBox.length !== 4) {
  112. return (0, _util.shadow)(this, 'mediaBox', LETTER_SIZE_MEDIABOX);
  113. }
  114. return (0, _util.shadow)(this, 'mediaBox', mediaBox);
  115. },
  116. get cropBox() {
  117. var cropBox = this.getInheritedPageProp('CropBox', true);
  118. if (!Array.isArray(cropBox) || cropBox.length !== 4) {
  119. return (0, _util.shadow)(this, 'cropBox', this.mediaBox);
  120. }
  121. return (0, _util.shadow)(this, 'cropBox', cropBox);
  122. },
  123. get userUnit() {
  124. var obj = this.getPageProp('UserUnit');
  125. if (!(0, _util.isNum)(obj) || obj <= 0) {
  126. obj = DEFAULT_USER_UNIT;
  127. }
  128. return (0, _util.shadow)(this, 'userUnit', obj);
  129. },
  130. get view() {
  131. var mediaBox = this.mediaBox,
  132. cropBox = this.cropBox;
  133. if (mediaBox === cropBox) {
  134. return (0, _util.shadow)(this, 'view', mediaBox);
  135. }
  136. var intersection = _util.Util.intersect(cropBox, mediaBox);
  137. return (0, _util.shadow)(this, 'view', intersection || mediaBox);
  138. },
  139. get rotate() {
  140. var rotate = this.getInheritedPageProp('Rotate') || 0;
  141. if (rotate % 90 !== 0) {
  142. rotate = 0;
  143. } else if (rotate >= 360) {
  144. rotate = rotate % 360;
  145. } else if (rotate < 0) {
  146. rotate = (rotate % 360 + 360) % 360;
  147. }
  148. return (0, _util.shadow)(this, 'rotate', rotate);
  149. },
  150. getContentStream: function Page_getContentStream() {
  151. var content = this.content;
  152. var stream;
  153. if (Array.isArray(content)) {
  154. var xref = this.xref;
  155. var i,
  156. n = content.length;
  157. var streams = [];
  158. for (i = 0; i < n; ++i) {
  159. streams.push(xref.fetchIfRef(content[i]));
  160. }
  161. stream = new _stream.StreamsSequenceStream(streams);
  162. } else if ((0, _primitives.isStream)(content)) {
  163. stream = content;
  164. } else {
  165. stream = new _stream.NullStream();
  166. }
  167. return stream;
  168. },
  169. loadResources: function Page_loadResources(keys) {
  170. var _this = this;
  171. if (!this.resourcesPromise) {
  172. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  173. }
  174. return this.resourcesPromise.then(function () {
  175. var objectLoader = new _obj.ObjectLoader(_this.resources, keys, _this.xref);
  176. return objectLoader.load();
  177. });
  178. },
  179. getOperatorList: function getOperatorList(_ref2) {
  180. var _this2 = this;
  181. var handler = _ref2.handler,
  182. task = _ref2.task,
  183. intent = _ref2.intent,
  184. renderInteractiveForms = _ref2.renderInteractiveForms;
  185. var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream');
  186. var resourcesPromise = this.loadResources(['ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font']);
  187. var partialEvaluator = new _evaluator.PartialEvaluator({
  188. pdfManager: this.pdfManager,
  189. xref: this.xref,
  190. handler: handler,
  191. pageIndex: this.pageIndex,
  192. idFactory: this.idFactory,
  193. fontCache: this.fontCache,
  194. builtInCMapCache: this.builtInCMapCache,
  195. options: this.evaluatorOptions,
  196. pdfFunctionFactory: this.pdfFunctionFactory
  197. });
  198. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  199. var pageListPromise = dataPromises.then(function (_ref3) {
  200. var _ref4 = _slicedToArray(_ref3, 1),
  201. contentStream = _ref4[0];
  202. var opList = new _operator_list.OperatorList(intent, handler, _this2.pageIndex);
  203. handler.send('StartRenderPage', {
  204. transparency: partialEvaluator.hasBlendModes(_this2.resources),
  205. pageIndex: _this2.pageIndex,
  206. intent: intent
  207. });
  208. return partialEvaluator.getOperatorList({
  209. stream: contentStream,
  210. task: task,
  211. resources: _this2.resources,
  212. operatorList: opList
  213. }).then(function () {
  214. return opList;
  215. });
  216. });
  217. var annotationsPromise = this.pdfManager.ensure(this, 'annotations');
  218. return Promise.all([pageListPromise, annotationsPromise]).then(function (_ref5) {
  219. var _ref6 = _slicedToArray(_ref5, 2),
  220. pageOpList = _ref6[0],
  221. annotations = _ref6[1];
  222. if (annotations.length === 0) {
  223. pageOpList.flush(true);
  224. return pageOpList;
  225. }
  226. var i,
  227. ii,
  228. opListPromises = [];
  229. for (i = 0, ii = annotations.length; i < ii; i++) {
  230. if (isAnnotationRenderable(annotations[i], intent)) {
  231. opListPromises.push(annotations[i].getOperatorList(partialEvaluator, task, renderInteractiveForms));
  232. }
  233. }
  234. return Promise.all(opListPromises).then(function (opLists) {
  235. pageOpList.addOp(_util.OPS.beginAnnotations, []);
  236. for (i = 0, ii = opLists.length; i < ii; i++) {
  237. pageOpList.addOpList(opLists[i]);
  238. }
  239. pageOpList.addOp(_util.OPS.endAnnotations, []);
  240. pageOpList.flush(true);
  241. return pageOpList;
  242. });
  243. });
  244. },
  245. extractTextContent: function extractTextContent(_ref7) {
  246. var _this3 = this;
  247. var handler = _ref7.handler,
  248. task = _ref7.task,
  249. normalizeWhitespace = _ref7.normalizeWhitespace,
  250. sink = _ref7.sink,
  251. combineTextItems = _ref7.combineTextItems;
  252. var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream');
  253. var resourcesPromise = this.loadResources(['ExtGState', 'XObject', 'Font']);
  254. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  255. return dataPromises.then(function (_ref8) {
  256. var _ref9 = _slicedToArray(_ref8, 1),
  257. contentStream = _ref9[0];
  258. var partialEvaluator = new _evaluator.PartialEvaluator({
  259. pdfManager: _this3.pdfManager,
  260. xref: _this3.xref,
  261. handler: handler,
  262. pageIndex: _this3.pageIndex,
  263. idFactory: _this3.idFactory,
  264. fontCache: _this3.fontCache,
  265. builtInCMapCache: _this3.builtInCMapCache,
  266. options: _this3.evaluatorOptions,
  267. pdfFunctionFactory: _this3.pdfFunctionFactory
  268. });
  269. return partialEvaluator.getTextContent({
  270. stream: contentStream,
  271. task: task,
  272. resources: _this3.resources,
  273. normalizeWhitespace: normalizeWhitespace,
  274. combineTextItems: combineTextItems,
  275. sink: sink
  276. });
  277. });
  278. },
  279. getAnnotationsData: function Page_getAnnotationsData(intent) {
  280. var annotations = this.annotations;
  281. var annotationsData = [];
  282. for (var i = 0, n = annotations.length; i < n; ++i) {
  283. if (!intent || isAnnotationRenderable(annotations[i], intent)) {
  284. annotationsData.push(annotations[i].data);
  285. }
  286. }
  287. return annotationsData;
  288. },
  289. get annotations() {
  290. var annotations = [];
  291. var annotationRefs = this.getInheritedPageProp('Annots') || [];
  292. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  293. var annotationRef = annotationRefs[i];
  294. var annotation = _annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory);
  295. if (annotation) {
  296. annotations.push(annotation);
  297. }
  298. }
  299. return (0, _util.shadow)(this, 'annotations', annotations);
  300. }
  301. };
  302. return Page;
  303. }();
  304. var PDFDocument = function PDFDocumentClosure() {
  305. var FINGERPRINT_FIRST_BYTES = 1024;
  306. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  307. function PDFDocument(pdfManager, arg) {
  308. var stream;
  309. if ((0, _primitives.isStream)(arg)) {
  310. stream = arg;
  311. } else if ((0, _util.isArrayBuffer)(arg)) {
  312. stream = new _stream.Stream(arg);
  313. } else {
  314. throw new Error('PDFDocument: Unknown argument type');
  315. }
  316. if (stream.length <= 0) {
  317. throw new Error('PDFDocument: stream must have data');
  318. }
  319. this.pdfManager = pdfManager;
  320. this.stream = stream;
  321. this.xref = new _obj.XRef(stream, pdfManager);
  322. var evaluatorOptions = pdfManager.evaluatorOptions;
  323. this.pdfFunctionFactory = new _function.PDFFunctionFactory({
  324. xref: this.xref,
  325. isEvalSupported: evaluatorOptions.isEvalSupported
  326. });
  327. }
  328. function find(stream, needle, limit, backwards) {
  329. var pos = stream.pos;
  330. var end = stream.end;
  331. var strBuf = [];
  332. if (pos + limit > end) {
  333. limit = end - pos;
  334. }
  335. for (var n = 0; n < limit; ++n) {
  336. strBuf.push(String.fromCharCode(stream.getByte()));
  337. }
  338. var str = strBuf.join('');
  339. stream.pos = pos;
  340. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  341. if (index === -1) {
  342. return false;
  343. }
  344. stream.pos += index;
  345. return true;
  346. }
  347. var DocumentInfoValidators = {
  348. get entries() {
  349. return (0, _util.shadow)(this, 'entries', {
  350. Title: _util.isString,
  351. Author: _util.isString,
  352. Subject: _util.isString,
  353. Keywords: _util.isString,
  354. Creator: _util.isString,
  355. Producer: _util.isString,
  356. CreationDate: _util.isString,
  357. ModDate: _util.isString,
  358. Trapped: _primitives.isName
  359. });
  360. }
  361. };
  362. PDFDocument.prototype = {
  363. parse: function PDFDocument_parse(recoveryMode) {
  364. this.setup(recoveryMode);
  365. var version = this.catalog.catDict.get('Version');
  366. if ((0, _primitives.isName)(version)) {
  367. this.pdfFormatVersion = version.name;
  368. }
  369. try {
  370. this.acroForm = this.catalog.catDict.get('AcroForm');
  371. if (this.acroForm) {
  372. this.xfa = this.acroForm.get('XFA');
  373. var fields = this.acroForm.get('Fields');
  374. if ((!fields || !Array.isArray(fields) || fields.length === 0) && !this.xfa) {
  375. this.acroForm = null;
  376. }
  377. }
  378. } catch (ex) {
  379. if (ex instanceof _util.MissingDataException) {
  380. throw ex;
  381. }
  382. (0, _util.info)('Something wrong with AcroForm entry');
  383. this.acroForm = null;
  384. }
  385. },
  386. get linearization() {
  387. var linearization = null;
  388. if (this.stream.length) {
  389. try {
  390. linearization = _parser.Linearization.create(this.stream);
  391. } catch (err) {
  392. if (err instanceof _util.MissingDataException) {
  393. throw err;
  394. }
  395. (0, _util.info)(err);
  396. }
  397. }
  398. return (0, _util.shadow)(this, 'linearization', linearization);
  399. },
  400. get startXRef() {
  401. var stream = this.stream;
  402. var startXRef = 0;
  403. var linearization = this.linearization;
  404. if (linearization) {
  405. stream.reset();
  406. if (find(stream, 'endobj', 1024)) {
  407. startXRef = stream.pos + 6;
  408. }
  409. } else {
  410. var step = 1024;
  411. var found = false,
  412. pos = stream.end;
  413. while (!found && pos > 0) {
  414. pos -= step - 'startxref'.length;
  415. if (pos < 0) {
  416. pos = 0;
  417. }
  418. stream.pos = pos;
  419. found = find(stream, 'startxref', step, true);
  420. }
  421. if (found) {
  422. stream.skip(9);
  423. var ch;
  424. do {
  425. ch = stream.getByte();
  426. } while ((0, _util.isSpace)(ch));
  427. var str = '';
  428. while (ch >= 0x20 && ch <= 0x39) {
  429. str += String.fromCharCode(ch);
  430. ch = stream.getByte();
  431. }
  432. startXRef = parseInt(str, 10);
  433. if (isNaN(startXRef)) {
  434. startXRef = 0;
  435. }
  436. }
  437. }
  438. return (0, _util.shadow)(this, 'startXRef', startXRef);
  439. },
  440. get mainXRefEntriesOffset() {
  441. var mainXRefEntriesOffset = 0;
  442. var linearization = this.linearization;
  443. if (linearization) {
  444. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  445. }
  446. return (0, _util.shadow)(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  447. },
  448. checkHeader: function PDFDocument_checkHeader() {
  449. var stream = this.stream;
  450. stream.reset();
  451. if (find(stream, '%PDF-', 1024)) {
  452. stream.moveStart();
  453. var MAX_VERSION_LENGTH = 12;
  454. var version = '',
  455. ch;
  456. while ((ch = stream.getByte()) > 0x20) {
  457. if (version.length >= MAX_VERSION_LENGTH) {
  458. break;
  459. }
  460. version += String.fromCharCode(ch);
  461. }
  462. if (!this.pdfFormatVersion) {
  463. this.pdfFormatVersion = version.substring(5);
  464. }
  465. return;
  466. }
  467. },
  468. parseStartXRef: function PDFDocument_parseStartXRef() {
  469. var startXRef = this.startXRef;
  470. this.xref.setStartXRef(startXRef);
  471. },
  472. setup: function PDFDocument_setup(recoveryMode) {
  473. var _this4 = this;
  474. this.xref.parse(recoveryMode);
  475. var pageFactory = {
  476. createPage: function createPage(pageIndex, dict, ref, fontCache, builtInCMapCache) {
  477. return new Page({
  478. pdfManager: _this4.pdfManager,
  479. xref: _this4.xref,
  480. pageIndex: pageIndex,
  481. pageDict: dict,
  482. ref: ref,
  483. fontCache: fontCache,
  484. builtInCMapCache: builtInCMapCache,
  485. pdfFunctionFactory: _this4.pdfFunctionFactory
  486. });
  487. }
  488. };
  489. this.catalog = new _obj.Catalog(this.pdfManager, this.xref, pageFactory);
  490. },
  491. get numPages() {
  492. var linearization = this.linearization;
  493. var num = linearization ? linearization.numPages : this.catalog.numPages;
  494. return (0, _util.shadow)(this, 'numPages', num);
  495. },
  496. get documentInfo() {
  497. var docInfo = {
  498. PDFFormatVersion: this.pdfFormatVersion,
  499. IsAcroFormPresent: !!this.acroForm,
  500. IsXFAPresent: !!this.xfa
  501. };
  502. var infoDict;
  503. try {
  504. infoDict = this.xref.trailer.get('Info');
  505. } catch (err) {
  506. if (err instanceof _util.MissingDataException) {
  507. throw err;
  508. }
  509. (0, _util.info)('The document information dictionary is invalid.');
  510. }
  511. if (infoDict) {
  512. var validEntries = DocumentInfoValidators.entries;
  513. for (var key in validEntries) {
  514. if (infoDict.has(key)) {
  515. var value = infoDict.get(key);
  516. if (validEntries[key](value)) {
  517. docInfo[key] = typeof value !== 'string' ? value : (0, _util.stringToPDFString)(value);
  518. } else {
  519. (0, _util.info)('Bad value in document info for "' + key + '"');
  520. }
  521. }
  522. }
  523. }
  524. return (0, _util.shadow)(this, 'documentInfo', docInfo);
  525. },
  526. get fingerprint() {
  527. var xref = this.xref,
  528. hash,
  529. fileID = '';
  530. var idArray = xref.trailer.get('ID');
  531. if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
  532. hash = (0, _util.stringToBytes)(idArray[0]);
  533. } else {
  534. if (this.stream.ensureRange) {
  535. this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  536. }
  537. hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  538. }
  539. for (var i = 0, n = hash.length; i < n; i++) {
  540. var hex = hash[i].toString(16);
  541. fileID += hex.length === 1 ? '0' + hex : hex;
  542. }
  543. return (0, _util.shadow)(this, 'fingerprint', fileID);
  544. },
  545. getPage: function PDFDocument_getPage(pageIndex) {
  546. return this.catalog.getPage(pageIndex);
  547. },
  548. cleanup: function PDFDocument_cleanup() {
  549. return this.catalog.cleanup();
  550. }
  551. };
  552. return PDFDocument;
  553. }();
  554. exports.Page = Page;
  555. exports.PDFDocument = PDFDocument;