document.js 19 KB

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