2
0

document.js 18 KB

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