document.js 19 KB

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