document.js 20 KB

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