document.js 19 KB

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