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('getInheritedPageProp: maximum loop count exceeded for ' + key);
  101. return valueArray ? valueArray[0] : undefined;
  102. }
  103. dict = dict.get('Parent');
  104. }
  105. if (!valueArray) {
  106. return undefined;
  107. }
  108. if (valueArray.length === 1 || !isDict(valueArray[0])) {
  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') || Dict.empty);
  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(handler, task, normalizeWhitespace, combineTextItems) {
  244. var self = this;
  245. var pdfManager = this.pdfManager;
  246. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream', []);
  247. var resourcesPromise = this.loadResources([
  248. 'ExtGState',
  249. 'XObject',
  250. 'Font'
  251. ]);
  252. var dataPromises = Promise.all([
  253. contentStreamPromise,
  254. resourcesPromise
  255. ]);
  256. return dataPromises.then(function (data) {
  257. var contentStream = data[0];
  258. var partialEvaluator = new PartialEvaluator(pdfManager, self.xref, handler, self.pageIndex, self.idFactory, self.fontCache, self.builtInCMapCache, self.evaluatorOptions);
  259. return partialEvaluator.getTextContent(contentStream, task, self.resources, null, normalizeWhitespace, combineTextItems);
  260. });
  261. },
  262. getAnnotationsData: function Page_getAnnotationsData(intent) {
  263. var annotations = this.annotations;
  264. var annotationsData = [];
  265. for (var i = 0, n = annotations.length; i < n; ++i) {
  266. if (!intent || isAnnotationRenderable(annotations[i], intent)) {
  267. annotationsData.push(annotations[i].data);
  268. }
  269. }
  270. return annotationsData;
  271. },
  272. get annotations() {
  273. var annotations = [];
  274. var annotationRefs = this.getInheritedPageProp('Annots') || [];
  275. var annotationFactory = new AnnotationFactory();
  276. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  277. var annotationRef = annotationRefs[i];
  278. var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory);
  279. if (annotation) {
  280. annotations.push(annotation);
  281. }
  282. }
  283. return shadow(this, 'annotations', annotations);
  284. }
  285. };
  286. return Page;
  287. }();
  288. var PDFDocument = function PDFDocumentClosure() {
  289. var FINGERPRINT_FIRST_BYTES = 1024;
  290. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  291. function PDFDocument(pdfManager, arg) {
  292. var stream;
  293. if (isStream(arg)) {
  294. stream = arg;
  295. } else if (isArrayBuffer(arg)) {
  296. stream = new Stream(arg);
  297. } else {
  298. error('PDFDocument: Unknown argument type');
  299. }
  300. assert(stream.length > 0, 'stream must have data');
  301. this.pdfManager = pdfManager;
  302. this.stream = stream;
  303. this.xref = new XRef(stream, pdfManager);
  304. }
  305. function find(stream, needle, limit, backwards) {
  306. var pos = stream.pos;
  307. var end = stream.end;
  308. var strBuf = [];
  309. if (pos + limit > end) {
  310. limit = end - pos;
  311. }
  312. for (var n = 0; n < limit; ++n) {
  313. strBuf.push(String.fromCharCode(stream.getByte()));
  314. }
  315. var str = strBuf.join('');
  316. stream.pos = pos;
  317. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  318. if (index === -1) {
  319. return false;
  320. }
  321. stream.pos += index;
  322. return true;
  323. }
  324. var DocumentInfoValidators = {
  325. get entries() {
  326. return shadow(this, 'entries', {
  327. Title: isString,
  328. Author: isString,
  329. Subject: isString,
  330. Keywords: isString,
  331. Creator: isString,
  332. Producer: isString,
  333. CreationDate: isString,
  334. ModDate: isString,
  335. Trapped: isName
  336. });
  337. }
  338. };
  339. PDFDocument.prototype = {
  340. parse: function PDFDocument_parse(recoveryMode) {
  341. this.setup(recoveryMode);
  342. var version = this.catalog.catDict.get('Version');
  343. if (isName(version)) {
  344. this.pdfFormatVersion = version.name;
  345. }
  346. try {
  347. this.acroForm = this.catalog.catDict.get('AcroForm');
  348. if (this.acroForm) {
  349. this.xfa = this.acroForm.get('XFA');
  350. var fields = this.acroForm.get('Fields');
  351. if ((!fields || !isArray(fields) || fields.length === 0) && !this.xfa) {
  352. this.acroForm = null;
  353. }
  354. }
  355. } catch (ex) {
  356. if (ex instanceof MissingDataException) {
  357. throw ex;
  358. }
  359. info('Something wrong with AcroForm entry');
  360. this.acroForm = null;
  361. }
  362. },
  363. get linearization() {
  364. var linearization = null;
  365. if (this.stream.length) {
  366. try {
  367. linearization = Linearization.create(this.stream);
  368. } catch (err) {
  369. if (err instanceof MissingDataException) {
  370. throw err;
  371. }
  372. info(err);
  373. }
  374. }
  375. return shadow(this, 'linearization', linearization);
  376. },
  377. get startXRef() {
  378. var stream = this.stream;
  379. var startXRef = 0;
  380. var linearization = this.linearization;
  381. if (linearization) {
  382. stream.reset();
  383. if (find(stream, 'endobj', 1024)) {
  384. startXRef = stream.pos + 6;
  385. }
  386. } else {
  387. var step = 1024;
  388. var found = false, 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 (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 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 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 = '', ch;
  431. while ((ch = stream.getByte()) > 0x20) {
  432. if (version.length >= MAX_VERSION_LENGTH) {
  433. break;
  434. }
  435. version += String.fromCharCode(ch);
  436. }
  437. if (!this.pdfFormatVersion) {
  438. this.pdfFormatVersion = version.substring(5);
  439. }
  440. return;
  441. }
  442. },
  443. parseStartXRef: function PDFDocument_parseStartXRef() {
  444. var startXRef = this.startXRef;
  445. this.xref.setStartXRef(startXRef);
  446. },
  447. setup: function PDFDocument_setup(recoveryMode) {
  448. this.xref.parse(recoveryMode);
  449. var self = this;
  450. var pageFactory = {
  451. createPage: function (pageIndex, dict, ref, fontCache, builtInCMapCache) {
  452. return new Page(self.pdfManager, self.xref, pageIndex, dict, ref, fontCache, builtInCMapCache);
  453. }
  454. };
  455. this.catalog = new Catalog(this.pdfManager, this.xref, pageFactory);
  456. },
  457. get numPages() {
  458. var linearization = this.linearization;
  459. var num = linearization ? linearization.numPages : this.catalog.numPages;
  460. return shadow(this, 'numPages', num);
  461. },
  462. get documentInfo() {
  463. var docInfo = {
  464. PDFFormatVersion: this.pdfFormatVersion,
  465. IsAcroFormPresent: !!this.acroForm,
  466. IsXFAPresent: !!this.xfa
  467. };
  468. var infoDict;
  469. try {
  470. infoDict = this.xref.trailer.get('Info');
  471. } catch (err) {
  472. if (err instanceof MissingDataException) {
  473. throw err;
  474. }
  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;