document.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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(handler, task, intent, renderInteractiveForms) {
  188. var _this2 = this;
  189. var pdfManager = this.pdfManager;
  190. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream', []);
  191. var resourcesPromise = this.loadResources(['ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font']);
  192. var partialEvaluator = new PartialEvaluator(pdfManager, this.xref, handler, this.pageIndex, this.idFactory, this.fontCache, this.builtInCMapCache, this.evaluatorOptions);
  193. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  194. var pageListPromise = dataPromises.then(function (_ref) {
  195. var _ref2 = _slicedToArray(_ref, 1),
  196. contentStream = _ref2[0];
  197. var opList = new OperatorList(intent, handler, _this2.pageIndex);
  198. handler.send('StartRenderPage', {
  199. transparency: partialEvaluator.hasBlendModes(_this2.resources),
  200. pageIndex: _this2.pageIndex,
  201. intent: intent
  202. });
  203. return partialEvaluator.getOperatorList(contentStream, task, _this2.resources, opList).then(function () {
  204. return opList;
  205. });
  206. });
  207. var annotationsPromise = pdfManager.ensure(this, 'annotations');
  208. return Promise.all([pageListPromise, annotationsPromise]).then(function (_ref3) {
  209. var _ref4 = _slicedToArray(_ref3, 2),
  210. pageOpList = _ref4[0],
  211. annotations = _ref4[1];
  212. if (annotations.length === 0) {
  213. pageOpList.flush(true);
  214. return pageOpList;
  215. }
  216. var i,
  217. ii,
  218. opListPromises = [];
  219. for (i = 0, ii = annotations.length; i < ii; i++) {
  220. if (isAnnotationRenderable(annotations[i], intent)) {
  221. opListPromises.push(annotations[i].getOperatorList(partialEvaluator, task, renderInteractiveForms));
  222. }
  223. }
  224. return Promise.all(opListPromises).then(function (opLists) {
  225. pageOpList.addOp(OPS.beginAnnotations, []);
  226. for (i = 0, ii = opLists.length; i < ii; i++) {
  227. pageOpList.addOpList(opLists[i]);
  228. }
  229. pageOpList.addOp(OPS.endAnnotations, []);
  230. pageOpList.flush(true);
  231. return pageOpList;
  232. });
  233. });
  234. },
  235. extractTextContent: function extractTextContent(handler, task, normalizeWhitespace, combineTextItems) {
  236. var _this3 = this;
  237. var pdfManager = this.pdfManager;
  238. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream', []);
  239. var resourcesPromise = this.loadResources(['ExtGState', 'XObject', 'Font']);
  240. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  241. return dataPromises.then(function (_ref5) {
  242. var _ref6 = _slicedToArray(_ref5, 1),
  243. contentStream = _ref6[0];
  244. var partialEvaluator = new PartialEvaluator(pdfManager, _this3.xref, handler, _this3.pageIndex, _this3.idFactory, _this3.fontCache, _this3.builtInCMapCache, _this3.evaluatorOptions);
  245. return partialEvaluator.getTextContent(contentStream, task, _this3.resources, null, normalizeWhitespace, combineTextItems);
  246. });
  247. },
  248. getAnnotationsData: function Page_getAnnotationsData(intent) {
  249. var annotations = this.annotations;
  250. var annotationsData = [];
  251. for (var i = 0, n = annotations.length; i < n; ++i) {
  252. if (!intent || isAnnotationRenderable(annotations[i], intent)) {
  253. annotationsData.push(annotations[i].data);
  254. }
  255. }
  256. return annotationsData;
  257. },
  258. get annotations() {
  259. var annotations = [];
  260. var annotationRefs = this.getInheritedPageProp('Annots') || [];
  261. var annotationFactory = new AnnotationFactory();
  262. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  263. var annotationRef = annotationRefs[i];
  264. var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory);
  265. if (annotation) {
  266. annotations.push(annotation);
  267. }
  268. }
  269. return shadow(this, 'annotations', annotations);
  270. }
  271. };
  272. return Page;
  273. }();
  274. var PDFDocument = function PDFDocumentClosure() {
  275. var FINGERPRINT_FIRST_BYTES = 1024;
  276. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  277. function PDFDocument(pdfManager, arg) {
  278. var stream;
  279. if (isStream(arg)) {
  280. stream = arg;
  281. } else if (isArrayBuffer(arg)) {
  282. stream = new Stream(arg);
  283. } else {
  284. error('PDFDocument: Unknown argument type');
  285. }
  286. assert(stream.length > 0, 'stream must have data');
  287. this.pdfManager = pdfManager;
  288. this.stream = stream;
  289. this.xref = new XRef(stream, pdfManager);
  290. }
  291. function find(stream, needle, limit, backwards) {
  292. var pos = stream.pos;
  293. var end = stream.end;
  294. var strBuf = [];
  295. if (pos + limit > end) {
  296. limit = end - pos;
  297. }
  298. for (var n = 0; n < limit; ++n) {
  299. strBuf.push(String.fromCharCode(stream.getByte()));
  300. }
  301. var str = strBuf.join('');
  302. stream.pos = pos;
  303. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  304. if (index === -1) {
  305. return false;
  306. }
  307. stream.pos += index;
  308. return true;
  309. }
  310. var DocumentInfoValidators = {
  311. get entries() {
  312. return shadow(this, 'entries', {
  313. Title: isString,
  314. Author: isString,
  315. Subject: isString,
  316. Keywords: isString,
  317. Creator: isString,
  318. Producer: isString,
  319. CreationDate: isString,
  320. ModDate: isString,
  321. Trapped: isName
  322. });
  323. }
  324. };
  325. PDFDocument.prototype = {
  326. parse: function PDFDocument_parse(recoveryMode) {
  327. this.setup(recoveryMode);
  328. var version = this.catalog.catDict.get('Version');
  329. if (isName(version)) {
  330. this.pdfFormatVersion = version.name;
  331. }
  332. try {
  333. this.acroForm = this.catalog.catDict.get('AcroForm');
  334. if (this.acroForm) {
  335. this.xfa = this.acroForm.get('XFA');
  336. var fields = this.acroForm.get('Fields');
  337. if ((!fields || !isArray(fields) || fields.length === 0) && !this.xfa) {
  338. this.acroForm = null;
  339. }
  340. }
  341. } catch (ex) {
  342. if (ex instanceof MissingDataException) {
  343. throw ex;
  344. }
  345. info('Something wrong with AcroForm entry');
  346. this.acroForm = null;
  347. }
  348. },
  349. get linearization() {
  350. var linearization = null;
  351. if (this.stream.length) {
  352. try {
  353. linearization = Linearization.create(this.stream);
  354. } catch (err) {
  355. if (err instanceof MissingDataException) {
  356. throw err;
  357. }
  358. info(err);
  359. }
  360. }
  361. return shadow(this, 'linearization', linearization);
  362. },
  363. get startXRef() {
  364. var stream = this.stream;
  365. var startXRef = 0;
  366. var linearization = this.linearization;
  367. if (linearization) {
  368. stream.reset();
  369. if (find(stream, 'endobj', 1024)) {
  370. startXRef = stream.pos + 6;
  371. }
  372. } else {
  373. var step = 1024;
  374. var found = false,
  375. pos = stream.end;
  376. while (!found && pos > 0) {
  377. pos -= step - 'startxref'.length;
  378. if (pos < 0) {
  379. pos = 0;
  380. }
  381. stream.pos = pos;
  382. found = find(stream, 'startxref', step, true);
  383. }
  384. if (found) {
  385. stream.skip(9);
  386. var ch;
  387. do {
  388. ch = stream.getByte();
  389. } while (isSpace(ch));
  390. var str = '';
  391. while (ch >= 0x20 && ch <= 0x39) {
  392. str += String.fromCharCode(ch);
  393. ch = stream.getByte();
  394. }
  395. startXRef = parseInt(str, 10);
  396. if (isNaN(startXRef)) {
  397. startXRef = 0;
  398. }
  399. }
  400. }
  401. return shadow(this, 'startXRef', startXRef);
  402. },
  403. get mainXRefEntriesOffset() {
  404. var mainXRefEntriesOffset = 0;
  405. var linearization = this.linearization;
  406. if (linearization) {
  407. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  408. }
  409. return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  410. },
  411. checkHeader: function PDFDocument_checkHeader() {
  412. var stream = this.stream;
  413. stream.reset();
  414. if (find(stream, '%PDF-', 1024)) {
  415. stream.moveStart();
  416. var MAX_VERSION_LENGTH = 12;
  417. var version = '',
  418. ch;
  419. while ((ch = stream.getByte()) > 0x20) {
  420. if (version.length >= MAX_VERSION_LENGTH) {
  421. break;
  422. }
  423. version += String.fromCharCode(ch);
  424. }
  425. if (!this.pdfFormatVersion) {
  426. this.pdfFormatVersion = version.substring(5);
  427. }
  428. return;
  429. }
  430. },
  431. parseStartXRef: function PDFDocument_parseStartXRef() {
  432. var startXRef = this.startXRef;
  433. this.xref.setStartXRef(startXRef);
  434. },
  435. setup: function PDFDocument_setup(recoveryMode) {
  436. var _this4 = this;
  437. this.xref.parse(recoveryMode);
  438. var pageFactory = {
  439. createPage: function createPage(pageIndex, dict, ref, fontCache, builtInCMapCache) {
  440. return new Page(_this4.pdfManager, _this4.xref, pageIndex, dict, ref, fontCache, builtInCMapCache);
  441. }
  442. };
  443. this.catalog = new Catalog(this.pdfManager, this.xref, pageFactory);
  444. },
  445. get numPages() {
  446. var linearization = this.linearization;
  447. var num = linearization ? linearization.numPages : this.catalog.numPages;
  448. return shadow(this, 'numPages', num);
  449. },
  450. get documentInfo() {
  451. var docInfo = {
  452. PDFFormatVersion: this.pdfFormatVersion,
  453. IsAcroFormPresent: !!this.acroForm,
  454. IsXFAPresent: !!this.xfa
  455. };
  456. var infoDict;
  457. try {
  458. infoDict = this.xref.trailer.get('Info');
  459. } catch (err) {
  460. if (err instanceof MissingDataException) {
  461. throw err;
  462. }
  463. info('The document information dictionary is invalid.');
  464. }
  465. if (infoDict) {
  466. var validEntries = DocumentInfoValidators.entries;
  467. for (var key in validEntries) {
  468. if (infoDict.has(key)) {
  469. var value = infoDict.get(key);
  470. if (validEntries[key](value)) {
  471. docInfo[key] = typeof value !== 'string' ? value : stringToPDFString(value);
  472. } else {
  473. info('Bad value in document info for "' + key + '"');
  474. }
  475. }
  476. }
  477. }
  478. return shadow(this, 'documentInfo', docInfo);
  479. },
  480. get fingerprint() {
  481. var xref = this.xref,
  482. hash,
  483. fileID = '';
  484. var idArray = xref.trailer.get('ID');
  485. if (idArray && isArray(idArray) && idArray[0] && isString(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
  486. hash = stringToBytes(idArray[0]);
  487. } else {
  488. if (this.stream.ensureRange) {
  489. this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  490. }
  491. hash = calculateMD5(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  492. }
  493. for (var i = 0, n = hash.length; i < n; i++) {
  494. var hex = hash[i].toString(16);
  495. fileID += hex.length === 1 ? '0' + hex : hex;
  496. }
  497. return shadow(this, 'fingerprint', fileID);
  498. },
  499. getPage: function PDFDocument_getPage(pageIndex) {
  500. return this.catalog.getPage(pageIndex);
  501. },
  502. cleanup: function PDFDocument_cleanup() {
  503. return this.catalog.cleanup();
  504. }
  505. };
  506. return PDFDocument;
  507. }();
  508. exports.Page = Page;
  509. exports.PDFDocument = PDFDocument;