2
0

document.js 19 KB

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