2
0

document.js 19 KB

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