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