2
0

document.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 _util = require('../shared/util');
  22. var _obj = require('./obj');
  23. var _primitives = require('./primitives');
  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. var annotationFactory = new _annotation.AnnotationFactory();
  273. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  274. var annotationRef = annotationRefs[i];
  275. var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory);
  276. if (annotation) {
  277. annotations.push(annotation);
  278. }
  279. }
  280. return (0, _util.shadow)(this, 'annotations', annotations);
  281. }
  282. };
  283. return Page;
  284. }();
  285. var PDFDocument = function PDFDocumentClosure() {
  286. var FINGERPRINT_FIRST_BYTES = 1024;
  287. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  288. function PDFDocument(pdfManager, arg) {
  289. var stream;
  290. if ((0, _primitives.isStream)(arg)) {
  291. stream = arg;
  292. } else if ((0, _util.isArrayBuffer)(arg)) {
  293. stream = new _stream.Stream(arg);
  294. } else {
  295. (0, _util.error)('PDFDocument: Unknown argument type');
  296. }
  297. (0, _util.assert)(stream.length > 0, 'stream must have data');
  298. this.pdfManager = pdfManager;
  299. this.stream = stream;
  300. this.xref = new _obj.XRef(stream, pdfManager);
  301. }
  302. function find(stream, needle, limit, backwards) {
  303. var pos = stream.pos;
  304. var end = stream.end;
  305. var strBuf = [];
  306. if (pos + limit > end) {
  307. limit = end - pos;
  308. }
  309. for (var n = 0; n < limit; ++n) {
  310. strBuf.push(String.fromCharCode(stream.getByte()));
  311. }
  312. var str = strBuf.join('');
  313. stream.pos = pos;
  314. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  315. if (index === -1) {
  316. return false;
  317. }
  318. stream.pos += index;
  319. return true;
  320. }
  321. var DocumentInfoValidators = {
  322. get entries() {
  323. return (0, _util.shadow)(this, 'entries', {
  324. Title: _util.isString,
  325. Author: _util.isString,
  326. Subject: _util.isString,
  327. Keywords: _util.isString,
  328. Creator: _util.isString,
  329. Producer: _util.isString,
  330. CreationDate: _util.isString,
  331. ModDate: _util.isString,
  332. Trapped: _primitives.isName
  333. });
  334. }
  335. };
  336. PDFDocument.prototype = {
  337. parse: function PDFDocument_parse(recoveryMode) {
  338. this.setup(recoveryMode);
  339. var version = this.catalog.catDict.get('Version');
  340. if ((0, _primitives.isName)(version)) {
  341. this.pdfFormatVersion = version.name;
  342. }
  343. try {
  344. this.acroForm = this.catalog.catDict.get('AcroForm');
  345. if (this.acroForm) {
  346. this.xfa = this.acroForm.get('XFA');
  347. var fields = this.acroForm.get('Fields');
  348. if ((!fields || !(0, _util.isArray)(fields) || fields.length === 0) && !this.xfa) {
  349. this.acroForm = null;
  350. }
  351. }
  352. } catch (ex) {
  353. if (ex instanceof _util.MissingDataException) {
  354. throw ex;
  355. }
  356. (0, _util.info)('Something wrong with AcroForm entry');
  357. this.acroForm = null;
  358. }
  359. },
  360. get linearization() {
  361. var linearization = null;
  362. if (this.stream.length) {
  363. try {
  364. linearization = _parser.Linearization.create(this.stream);
  365. } catch (err) {
  366. if (err instanceof _util.MissingDataException) {
  367. throw err;
  368. }
  369. (0, _util.info)(err);
  370. }
  371. }
  372. return (0, _util.shadow)(this, 'linearization', linearization);
  373. },
  374. get startXRef() {
  375. var stream = this.stream;
  376. var startXRef = 0;
  377. var linearization = this.linearization;
  378. if (linearization) {
  379. stream.reset();
  380. if (find(stream, 'endobj', 1024)) {
  381. startXRef = stream.pos + 6;
  382. }
  383. } else {
  384. var step = 1024;
  385. var found = false,
  386. pos = stream.end;
  387. while (!found && pos > 0) {
  388. pos -= step - 'startxref'.length;
  389. if (pos < 0) {
  390. pos = 0;
  391. }
  392. stream.pos = pos;
  393. found = find(stream, 'startxref', step, true);
  394. }
  395. if (found) {
  396. stream.skip(9);
  397. var ch;
  398. do {
  399. ch = stream.getByte();
  400. } while ((0, _util.isSpace)(ch));
  401. var str = '';
  402. while (ch >= 0x20 && ch <= 0x39) {
  403. str += String.fromCharCode(ch);
  404. ch = stream.getByte();
  405. }
  406. startXRef = parseInt(str, 10);
  407. if (isNaN(startXRef)) {
  408. startXRef = 0;
  409. }
  410. }
  411. }
  412. return (0, _util.shadow)(this, 'startXRef', startXRef);
  413. },
  414. get mainXRefEntriesOffset() {
  415. var mainXRefEntriesOffset = 0;
  416. var linearization = this.linearization;
  417. if (linearization) {
  418. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  419. }
  420. return (0, _util.shadow)(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  421. },
  422. checkHeader: function PDFDocument_checkHeader() {
  423. var stream = this.stream;
  424. stream.reset();
  425. if (find(stream, '%PDF-', 1024)) {
  426. stream.moveStart();
  427. var MAX_VERSION_LENGTH = 12;
  428. var version = '',
  429. ch;
  430. while ((ch = stream.getByte()) > 0x20) {
  431. if (version.length >= MAX_VERSION_LENGTH) {
  432. break;
  433. }
  434. version += String.fromCharCode(ch);
  435. }
  436. if (!this.pdfFormatVersion) {
  437. this.pdfFormatVersion = version.substring(5);
  438. }
  439. return;
  440. }
  441. },
  442. parseStartXRef: function PDFDocument_parseStartXRef() {
  443. var startXRef = this.startXRef;
  444. this.xref.setStartXRef(startXRef);
  445. },
  446. setup: function PDFDocument_setup(recoveryMode) {
  447. var _this4 = this;
  448. this.xref.parse(recoveryMode);
  449. var pageFactory = {
  450. createPage: function createPage(pageIndex, dict, ref, fontCache, builtInCMapCache) {
  451. return new Page(_this4.pdfManager, _this4.xref, pageIndex, dict, ref, fontCache, builtInCMapCache);
  452. }
  453. };
  454. this.catalog = new _obj.Catalog(this.pdfManager, this.xref, pageFactory);
  455. },
  456. get numPages() {
  457. var linearization = this.linearization;
  458. var num = linearization ? linearization.numPages : this.catalog.numPages;
  459. return (0, _util.shadow)(this, 'numPages', num);
  460. },
  461. get documentInfo() {
  462. var docInfo = {
  463. PDFFormatVersion: this.pdfFormatVersion,
  464. IsAcroFormPresent: !!this.acroForm,
  465. IsXFAPresent: !!this.xfa
  466. };
  467. var infoDict;
  468. try {
  469. infoDict = this.xref.trailer.get('Info');
  470. } catch (err) {
  471. if (err instanceof _util.MissingDataException) {
  472. throw err;
  473. }
  474. (0, _util.info)('The document information dictionary is invalid.');
  475. }
  476. if (infoDict) {
  477. var validEntries = DocumentInfoValidators.entries;
  478. for (var key in validEntries) {
  479. if (infoDict.has(key)) {
  480. var value = infoDict.get(key);
  481. if (validEntries[key](value)) {
  482. docInfo[key] = typeof value !== 'string' ? value : (0, _util.stringToPDFString)(value);
  483. } else {
  484. (0, _util.info)('Bad value in document info for "' + key + '"');
  485. }
  486. }
  487. }
  488. }
  489. return (0, _util.shadow)(this, 'documentInfo', docInfo);
  490. },
  491. get fingerprint() {
  492. var xref = this.xref,
  493. hash,
  494. fileID = '';
  495. var idArray = xref.trailer.get('ID');
  496. if (idArray && (0, _util.isArray)(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
  497. hash = (0, _util.stringToBytes)(idArray[0]);
  498. } else {
  499. if (this.stream.ensureRange) {
  500. this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  501. }
  502. hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  503. }
  504. for (var i = 0, n = hash.length; i < n; i++) {
  505. var hex = hash[i].toString(16);
  506. fileID += hex.length === 1 ? '0' + hex : hex;
  507. }
  508. return (0, _util.shadow)(this, 'fingerprint', fileID);
  509. },
  510. getPage: function PDFDocument_getPage(pageIndex) {
  511. return this.catalog.getPage(pageIndex);
  512. },
  513. cleanup: function PDFDocument_cleanup() {
  514. return this.catalog.cleanup();
  515. }
  516. };
  517. return PDFDocument;
  518. }();
  519. exports.Page = Page;
  520. exports.PDFDocument = PDFDocument;