obj.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.FileSpec = exports.XRef = exports.ObjectLoader = exports.Catalog = undefined;
  20. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  21. 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"); } }; }();
  22. var _util = require('../shared/util');
  23. var _primitives = require('./primitives');
  24. var _parser = require('./parser');
  25. var _chunked_stream = require('./chunked_stream');
  26. var _crypto = require('./crypto');
  27. var _colorspace = require('./colorspace');
  28. var Catalog = function CatalogClosure() {
  29. function Catalog(pdfManager, xref, pageFactory) {
  30. this.pdfManager = pdfManager;
  31. this.xref = xref;
  32. this.catDict = xref.getCatalogObj();
  33. if (!(0, _primitives.isDict)(this.catDict)) {
  34. throw new _util.FormatError('catalog object is not a dictionary');
  35. }
  36. this.fontCache = new _primitives.RefSetCache();
  37. this.builtInCMapCache = Object.create(null);
  38. this.pageKidsCountCache = new _primitives.RefSetCache();
  39. this.pageFactory = pageFactory;
  40. this.pagePromises = [];
  41. }
  42. Catalog.prototype = {
  43. get metadata() {
  44. var streamRef = this.catDict.getRaw('Metadata');
  45. if (!(0, _primitives.isRef)(streamRef)) {
  46. return (0, _util.shadow)(this, 'metadata', null);
  47. }
  48. var encryptMetadata = !this.xref.encrypt ? false : this.xref.encrypt.encryptMetadata;
  49. var stream = this.xref.fetch(streamRef, !encryptMetadata);
  50. var metadata;
  51. if (stream && (0, _primitives.isDict)(stream.dict)) {
  52. var type = stream.dict.get('Type');
  53. var subtype = stream.dict.get('Subtype');
  54. if ((0, _primitives.isName)(type, 'Metadata') && (0, _primitives.isName)(subtype, 'XML')) {
  55. try {
  56. metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
  57. } catch (e) {
  58. if (e instanceof _util.MissingDataException) {
  59. throw e;
  60. }
  61. (0, _util.info)('Skipping invalid metadata.');
  62. }
  63. }
  64. }
  65. return (0, _util.shadow)(this, 'metadata', metadata);
  66. },
  67. get toplevelPagesDict() {
  68. var pagesObj = this.catDict.get('Pages');
  69. if (!(0, _primitives.isDict)(pagesObj)) {
  70. throw new _util.FormatError('invalid top-level pages dictionary');
  71. }
  72. return (0, _util.shadow)(this, 'toplevelPagesDict', pagesObj);
  73. },
  74. get documentOutline() {
  75. var obj = null;
  76. try {
  77. obj = this.readDocumentOutline();
  78. } catch (ex) {
  79. if (ex instanceof _util.MissingDataException) {
  80. throw ex;
  81. }
  82. (0, _util.warn)('Unable to read document outline');
  83. }
  84. return (0, _util.shadow)(this, 'documentOutline', obj);
  85. },
  86. readDocumentOutline: function Catalog_readDocumentOutline() {
  87. var obj = this.catDict.get('Outlines');
  88. if (!(0, _primitives.isDict)(obj)) {
  89. return null;
  90. }
  91. obj = obj.getRaw('First');
  92. if (!(0, _primitives.isRef)(obj)) {
  93. return null;
  94. }
  95. var root = { items: [] };
  96. var queue = [{
  97. obj: obj,
  98. parent: root
  99. }];
  100. var processed = new _primitives.RefSet();
  101. processed.put(obj);
  102. var xref = this.xref,
  103. blackColor = new Uint8Array(3);
  104. while (queue.length > 0) {
  105. var i = queue.shift();
  106. var outlineDict = xref.fetchIfRef(i.obj);
  107. if (outlineDict === null) {
  108. continue;
  109. }
  110. if (!outlineDict.has('Title')) {
  111. throw new _util.FormatError('Invalid outline item');
  112. }
  113. var data = {
  114. url: null,
  115. dest: null
  116. };
  117. Catalog.parseDestDictionary({
  118. destDict: outlineDict,
  119. resultObj: data,
  120. docBaseUrl: this.pdfManager.docBaseUrl
  121. });
  122. var title = outlineDict.get('Title');
  123. var flags = outlineDict.get('F') || 0;
  124. var color = outlineDict.getArray('C'),
  125. rgbColor = blackColor;
  126. if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
  127. rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
  128. }
  129. var outlineItem = {
  130. dest: data.dest,
  131. url: data.url,
  132. unsafeUrl: data.unsafeUrl,
  133. newWindow: data.newWindow,
  134. title: (0, _util.stringToPDFString)(title),
  135. color: rgbColor,
  136. count: outlineDict.get('Count'),
  137. bold: !!(flags & 2),
  138. italic: !!(flags & 1),
  139. items: []
  140. };
  141. i.parent.items.push(outlineItem);
  142. obj = outlineDict.getRaw('First');
  143. if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
  144. queue.push({
  145. obj: obj,
  146. parent: outlineItem
  147. });
  148. processed.put(obj);
  149. }
  150. obj = outlineDict.getRaw('Next');
  151. if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
  152. queue.push({
  153. obj: obj,
  154. parent: i.parent
  155. });
  156. processed.put(obj);
  157. }
  158. }
  159. return root.items.length > 0 ? root.items : null;
  160. },
  161. get numPages() {
  162. var obj = this.toplevelPagesDict.get('Count');
  163. if (!Number.isInteger(obj)) {
  164. throw new _util.FormatError('page count in top level pages object is not an integer');
  165. }
  166. return (0, _util.shadow)(this, 'numPages', obj);
  167. },
  168. get destinations() {
  169. function fetchDestination(dest) {
  170. return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
  171. }
  172. var xref = this.xref;
  173. var dests = {},
  174. nameTreeRef,
  175. nameDictionaryRef;
  176. var obj = this.catDict.get('Names');
  177. if (obj && obj.has('Dests')) {
  178. nameTreeRef = obj.getRaw('Dests');
  179. } else if (this.catDict.has('Dests')) {
  180. nameDictionaryRef = this.catDict.get('Dests');
  181. }
  182. if (nameDictionaryRef) {
  183. obj = nameDictionaryRef;
  184. obj.forEach(function catalogForEach(key, value) {
  185. if (!value) {
  186. return;
  187. }
  188. dests[key] = fetchDestination(value);
  189. });
  190. }
  191. if (nameTreeRef) {
  192. var nameTree = new NameTree(nameTreeRef, xref);
  193. var names = nameTree.getAll();
  194. for (var name in names) {
  195. dests[name] = fetchDestination(names[name]);
  196. }
  197. }
  198. return (0, _util.shadow)(this, 'destinations', dests);
  199. },
  200. getDestination: function Catalog_getDestination(destinationId) {
  201. function fetchDestination(dest) {
  202. return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
  203. }
  204. var xref = this.xref;
  205. var dest = null,
  206. nameTreeRef,
  207. nameDictionaryRef;
  208. var obj = this.catDict.get('Names');
  209. if (obj && obj.has('Dests')) {
  210. nameTreeRef = obj.getRaw('Dests');
  211. } else if (this.catDict.has('Dests')) {
  212. nameDictionaryRef = this.catDict.get('Dests');
  213. }
  214. if (nameDictionaryRef) {
  215. var value = nameDictionaryRef.get(destinationId);
  216. if (value) {
  217. dest = fetchDestination(value);
  218. }
  219. }
  220. if (nameTreeRef) {
  221. var nameTree = new NameTree(nameTreeRef, xref);
  222. dest = fetchDestination(nameTree.get(destinationId));
  223. }
  224. return dest;
  225. },
  226. get pageLabels() {
  227. var obj = null;
  228. try {
  229. obj = this.readPageLabels();
  230. } catch (ex) {
  231. if (ex instanceof _util.MissingDataException) {
  232. throw ex;
  233. }
  234. (0, _util.warn)('Unable to read page labels.');
  235. }
  236. return (0, _util.shadow)(this, 'pageLabels', obj);
  237. },
  238. readPageLabels: function Catalog_readPageLabels() {
  239. var obj = this.catDict.getRaw('PageLabels');
  240. if (!obj) {
  241. return null;
  242. }
  243. var pageLabels = new Array(this.numPages);
  244. var style = null;
  245. var prefix = '';
  246. var numberTree = new NumberTree(obj, this.xref);
  247. var nums = numberTree.getAll();
  248. var currentLabel = '',
  249. currentIndex = 1;
  250. for (var i = 0, ii = this.numPages; i < ii; i++) {
  251. if (i in nums) {
  252. var labelDict = nums[i];
  253. if (!(0, _primitives.isDict)(labelDict)) {
  254. throw new _util.FormatError('The PageLabel is not a dictionary.');
  255. }
  256. var type = labelDict.get('Type');
  257. if (type && !(0, _primitives.isName)(type, 'PageLabel')) {
  258. throw new _util.FormatError('Invalid type in PageLabel dictionary.');
  259. }
  260. var s = labelDict.get('S');
  261. if (s && !(0, _primitives.isName)(s)) {
  262. throw new _util.FormatError('Invalid style in PageLabel dictionary.');
  263. }
  264. style = s ? s.name : null;
  265. var p = labelDict.get('P');
  266. if (p && !(0, _util.isString)(p)) {
  267. throw new _util.FormatError('Invalid prefix in PageLabel dictionary.');
  268. }
  269. prefix = p ? (0, _util.stringToPDFString)(p) : '';
  270. var st = labelDict.get('St');
  271. if (st && !(Number.isInteger(st) && st >= 1)) {
  272. throw new _util.FormatError('Invalid start in PageLabel dictionary.');
  273. }
  274. currentIndex = st || 1;
  275. }
  276. switch (style) {
  277. case 'D':
  278. currentLabel = currentIndex;
  279. break;
  280. case 'R':
  281. case 'r':
  282. currentLabel = _util.Util.toRoman(currentIndex, style === 'r');
  283. break;
  284. case 'A':
  285. case 'a':
  286. var LIMIT = 26;
  287. var A_UPPER_CASE = 0x41,
  288. A_LOWER_CASE = 0x61;
  289. var baseCharCode = style === 'a' ? A_LOWER_CASE : A_UPPER_CASE;
  290. var letterIndex = currentIndex - 1;
  291. var character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
  292. var charBuf = [];
  293. for (var j = 0, jj = letterIndex / LIMIT | 0; j <= jj; j++) {
  294. charBuf.push(character);
  295. }
  296. currentLabel = charBuf.join('');
  297. break;
  298. default:
  299. if (style) {
  300. throw new _util.FormatError('Invalid style "' + style + '" in PageLabel dictionary.');
  301. }
  302. }
  303. pageLabels[i] = prefix + currentLabel;
  304. currentLabel = '';
  305. currentIndex++;
  306. }
  307. return pageLabels;
  308. },
  309. get pageMode() {
  310. var obj = this.catDict.get('PageMode');
  311. var pageMode = 'UseNone';
  312. if ((0, _primitives.isName)(obj)) {
  313. switch (obj.name) {
  314. case 'UseNone':
  315. case 'UseOutlines':
  316. case 'UseThumbs':
  317. case 'FullScreen':
  318. case 'UseOC':
  319. case 'UseAttachments':
  320. pageMode = obj.name;
  321. }
  322. }
  323. return (0, _util.shadow)(this, 'pageMode', pageMode);
  324. },
  325. get attachments() {
  326. var xref = this.xref;
  327. var attachments = null,
  328. nameTreeRef;
  329. var obj = this.catDict.get('Names');
  330. if (obj) {
  331. nameTreeRef = obj.getRaw('EmbeddedFiles');
  332. }
  333. if (nameTreeRef) {
  334. var nameTree = new NameTree(nameTreeRef, xref);
  335. var names = nameTree.getAll();
  336. for (var name in names) {
  337. var fs = new FileSpec(names[name], xref);
  338. if (!attachments) {
  339. attachments = Object.create(null);
  340. }
  341. attachments[(0, _util.stringToPDFString)(name)] = fs.serializable;
  342. }
  343. }
  344. return (0, _util.shadow)(this, 'attachments', attachments);
  345. },
  346. get javaScript() {
  347. var xref = this.xref;
  348. var obj = this.catDict.get('Names');
  349. var javaScript = null;
  350. function appendIfJavaScriptDict(jsDict) {
  351. var type = jsDict.get('S');
  352. if (!(0, _primitives.isName)(type, 'JavaScript')) {
  353. return;
  354. }
  355. var js = jsDict.get('JS');
  356. if ((0, _primitives.isStream)(js)) {
  357. js = (0, _util.bytesToString)(js.getBytes());
  358. } else if (!(0, _util.isString)(js)) {
  359. return;
  360. }
  361. if (!javaScript) {
  362. javaScript = [];
  363. }
  364. javaScript.push((0, _util.stringToPDFString)(js));
  365. }
  366. if (obj && obj.has('JavaScript')) {
  367. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  368. var names = nameTree.getAll();
  369. for (var name in names) {
  370. var jsDict = names[name];
  371. if ((0, _primitives.isDict)(jsDict)) {
  372. appendIfJavaScriptDict(jsDict);
  373. }
  374. }
  375. }
  376. var openactionDict = this.catDict.get('OpenAction');
  377. if ((0, _primitives.isDict)(openactionDict, 'Action')) {
  378. var actionType = openactionDict.get('S');
  379. if ((0, _primitives.isName)(actionType, 'Named')) {
  380. var action = openactionDict.get('N');
  381. if ((0, _primitives.isName)(action, 'Print')) {
  382. if (!javaScript) {
  383. javaScript = [];
  384. }
  385. javaScript.push('print({});');
  386. }
  387. } else {
  388. appendIfJavaScriptDict(openactionDict);
  389. }
  390. }
  391. return (0, _util.shadow)(this, 'javaScript', javaScript);
  392. },
  393. cleanup: function Catalog_cleanup() {
  394. var _this = this;
  395. this.pageKidsCountCache.clear();
  396. var promises = [];
  397. this.fontCache.forEach(function (promise) {
  398. promises.push(promise);
  399. });
  400. return Promise.all(promises).then(function (translatedFonts) {
  401. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  402. var font = translatedFonts[i].dict;
  403. delete font.translated;
  404. }
  405. _this.fontCache.clear();
  406. _this.builtInCMapCache = Object.create(null);
  407. });
  408. },
  409. getPage: function Catalog_getPage(pageIndex) {
  410. var _this2 = this;
  411. if (!(pageIndex in this.pagePromises)) {
  412. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(function (_ref) {
  413. var _ref2 = _slicedToArray(_ref, 2),
  414. dict = _ref2[0],
  415. ref = _ref2[1];
  416. return _this2.pageFactory.createPage(pageIndex, dict, ref, _this2.fontCache, _this2.builtInCMapCache);
  417. });
  418. }
  419. return this.pagePromises[pageIndex];
  420. },
  421. getPageDict: function Catalog_getPageDict(pageIndex) {
  422. var capability = (0, _util.createPromiseCapability)();
  423. var nodesToVisit = [this.catDict.getRaw('Pages')];
  424. var count,
  425. currentPageIndex = 0;
  426. var xref = this.xref,
  427. pageKidsCountCache = this.pageKidsCountCache;
  428. function next() {
  429. while (nodesToVisit.length) {
  430. var currentNode = nodesToVisit.pop();
  431. if ((0, _primitives.isRef)(currentNode)) {
  432. count = pageKidsCountCache.get(currentNode);
  433. if (count > 0 && currentPageIndex + count < pageIndex) {
  434. currentPageIndex += count;
  435. continue;
  436. }
  437. xref.fetchAsync(currentNode).then(function (obj) {
  438. if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Kids')) {
  439. if (pageIndex === currentPageIndex) {
  440. if (currentNode && !pageKidsCountCache.has(currentNode)) {
  441. pageKidsCountCache.put(currentNode, 1);
  442. }
  443. capability.resolve([obj, currentNode]);
  444. } else {
  445. currentPageIndex++;
  446. next();
  447. }
  448. return;
  449. }
  450. nodesToVisit.push(obj);
  451. next();
  452. }, capability.reject);
  453. return;
  454. }
  455. if (!(0, _primitives.isDict)(currentNode)) {
  456. capability.reject(new _util.FormatError('page dictionary kid reference points to wrong type of object'));
  457. return;
  458. }
  459. count = currentNode.get('Count');
  460. var objId = currentNode.objId;
  461. if (objId && !pageKidsCountCache.has(objId)) {
  462. pageKidsCountCache.put(objId, count);
  463. }
  464. if (currentPageIndex + count <= pageIndex) {
  465. currentPageIndex += count;
  466. continue;
  467. }
  468. var kids = currentNode.get('Kids');
  469. if (!Array.isArray(kids)) {
  470. capability.reject(new _util.FormatError('page dictionary kids object is not an array'));
  471. return;
  472. }
  473. for (var last = kids.length - 1; last >= 0; last--) {
  474. nodesToVisit.push(kids[last]);
  475. }
  476. }
  477. capability.reject(new Error('Page index ' + pageIndex + ' not found.'));
  478. }
  479. next();
  480. return capability.promise;
  481. },
  482. getPageIndex: function Catalog_getPageIndex(pageRef) {
  483. var xref = this.xref;
  484. function pagesBeforeRef(kidRef) {
  485. var total = 0;
  486. var parentRef;
  487. return xref.fetchAsync(kidRef).then(function (node) {
  488. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, 'Page') && !((0, _primitives.isDict)(node) && !node.has('Type') && node.has('Contents'))) {
  489. throw new _util.FormatError('The reference does not point to a /Page Dict.');
  490. }
  491. if (!node) {
  492. return null;
  493. }
  494. if (!(0, _primitives.isDict)(node)) {
  495. throw new _util.FormatError('node must be a Dict.');
  496. }
  497. parentRef = node.getRaw('Parent');
  498. return node.getAsync('Parent');
  499. }).then(function (parent) {
  500. if (!parent) {
  501. return null;
  502. }
  503. if (!(0, _primitives.isDict)(parent)) {
  504. throw new _util.FormatError('parent must be a Dict.');
  505. }
  506. return parent.getAsync('Kids');
  507. }).then(function (kids) {
  508. if (!kids) {
  509. return null;
  510. }
  511. var kidPromises = [];
  512. var found = false;
  513. for (var i = 0; i < kids.length; i++) {
  514. var kid = kids[i];
  515. if (!(0, _primitives.isRef)(kid)) {
  516. throw new _util.FormatError('kid must be a Ref.');
  517. }
  518. if (kid.num === kidRef.num) {
  519. found = true;
  520. break;
  521. }
  522. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  523. if (kid.has('Count')) {
  524. var count = kid.get('Count');
  525. total += count;
  526. } else {
  527. total++;
  528. }
  529. }));
  530. }
  531. if (!found) {
  532. throw new _util.FormatError('kid ref not found in parents kids');
  533. }
  534. return Promise.all(kidPromises).then(function () {
  535. return [total, parentRef];
  536. });
  537. });
  538. }
  539. var total = 0;
  540. function next(ref) {
  541. return pagesBeforeRef(ref).then(function (args) {
  542. if (!args) {
  543. return total;
  544. }
  545. var count = args[0];
  546. var parentRef = args[1];
  547. total += count;
  548. return next(parentRef);
  549. });
  550. }
  551. return next(pageRef);
  552. }
  553. };
  554. Catalog.parseDestDictionary = function Catalog_parseDestDictionary(params) {
  555. function addDefaultProtocolToUrl(url) {
  556. if (url.indexOf('www.') === 0) {
  557. return 'http://' + url;
  558. }
  559. return url;
  560. }
  561. function tryConvertUrlEncoding(url) {
  562. try {
  563. return (0, _util.stringToUTF8String)(url);
  564. } catch (e) {
  565. return url;
  566. }
  567. }
  568. var destDict = params.destDict;
  569. if (!(0, _primitives.isDict)(destDict)) {
  570. (0, _util.warn)('parseDestDictionary: "destDict" must be a dictionary.');
  571. return;
  572. }
  573. var resultObj = params.resultObj;
  574. if ((typeof resultObj === 'undefined' ? 'undefined' : _typeof(resultObj)) !== 'object') {
  575. (0, _util.warn)('parseDestDictionary: "resultObj" must be an object.');
  576. return;
  577. }
  578. var docBaseUrl = params.docBaseUrl || null;
  579. var action = destDict.get('A'),
  580. url,
  581. dest;
  582. if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
  583. action = destDict.get('Dest');
  584. }
  585. if ((0, _primitives.isDict)(action)) {
  586. var actionType = action.get('S');
  587. if (!(0, _primitives.isName)(actionType)) {
  588. (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
  589. return;
  590. }
  591. var actionName = actionType.name;
  592. switch (actionName) {
  593. case 'URI':
  594. url = action.get('URI');
  595. if ((0, _primitives.isName)(url)) {
  596. url = '/' + url.name;
  597. } else if ((0, _util.isString)(url)) {
  598. url = addDefaultProtocolToUrl(url);
  599. }
  600. break;
  601. case 'GoTo':
  602. dest = action.get('D');
  603. break;
  604. case 'Launch':
  605. case 'GoToR':
  606. var urlDict = action.get('F');
  607. if ((0, _primitives.isDict)(urlDict)) {
  608. url = urlDict.get('F') || null;
  609. } else if ((0, _util.isString)(urlDict)) {
  610. url = urlDict;
  611. }
  612. var remoteDest = action.get('D');
  613. if (remoteDest) {
  614. if ((0, _primitives.isName)(remoteDest)) {
  615. remoteDest = remoteDest.name;
  616. }
  617. if ((0, _util.isString)(url)) {
  618. var baseUrl = url.split('#')[0];
  619. if ((0, _util.isString)(remoteDest)) {
  620. url = baseUrl + '#' + remoteDest;
  621. } else if (Array.isArray(remoteDest)) {
  622. url = baseUrl + '#' + JSON.stringify(remoteDest);
  623. }
  624. }
  625. }
  626. var newWindow = action.get('NewWindow');
  627. if ((0, _util.isBool)(newWindow)) {
  628. resultObj.newWindow = newWindow;
  629. }
  630. break;
  631. case 'Named':
  632. var namedAction = action.get('N');
  633. if ((0, _primitives.isName)(namedAction)) {
  634. resultObj.action = namedAction.name;
  635. }
  636. break;
  637. case 'JavaScript':
  638. var jsAction = action.get('JS'),
  639. js;
  640. if ((0, _primitives.isStream)(jsAction)) {
  641. js = (0, _util.bytesToString)(jsAction.getBytes());
  642. } else if ((0, _util.isString)(jsAction)) {
  643. js = jsAction;
  644. }
  645. if (js) {
  646. var URL_OPEN_METHODS = ['app.launchURL', 'window.open'];
  647. var regex = new RegExp('^\\s*(' + URL_OPEN_METHODS.join('|').split('.').join('\\.') + ')\\((?:\'|\")([^\'\"]*)(?:\'|\")(?:,\\s*(\\w+)\\)|\\))', 'i');
  648. var jsUrl = regex.exec((0, _util.stringToPDFString)(js));
  649. if (jsUrl && jsUrl[2]) {
  650. url = jsUrl[2];
  651. if (jsUrl[3] === 'true' && jsUrl[1] === 'app.launchURL') {
  652. resultObj.newWindow = true;
  653. }
  654. break;
  655. }
  656. }
  657. default:
  658. (0, _util.warn)('parseDestDictionary: Unsupported Action type "' + actionName + '".');
  659. break;
  660. }
  661. } else if (destDict.has('Dest')) {
  662. dest = destDict.get('Dest');
  663. }
  664. if ((0, _util.isString)(url)) {
  665. url = tryConvertUrlEncoding(url);
  666. var absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
  667. if (absoluteUrl) {
  668. resultObj.url = absoluteUrl.href;
  669. }
  670. resultObj.unsafeUrl = url;
  671. }
  672. if (dest) {
  673. if ((0, _primitives.isName)(dest)) {
  674. dest = dest.name;
  675. }
  676. if ((0, _util.isString)(dest) || Array.isArray(dest)) {
  677. resultObj.dest = dest;
  678. }
  679. }
  680. };
  681. return Catalog;
  682. }();
  683. var XRef = function XRefClosure() {
  684. function XRef(stream, pdfManager) {
  685. this.stream = stream;
  686. this.pdfManager = pdfManager;
  687. this.entries = [];
  688. this.xrefstms = Object.create(null);
  689. this.cache = [];
  690. this.stats = {
  691. streamTypes: [],
  692. fontTypes: []
  693. };
  694. }
  695. XRef.prototype = {
  696. setStartXRef: function XRef_setStartXRef(startXRef) {
  697. this.startXRefQueue = [startXRef];
  698. },
  699. parse: function XRef_parse(recoveryMode) {
  700. var trailerDict;
  701. if (!recoveryMode) {
  702. trailerDict = this.readXRef();
  703. } else {
  704. (0, _util.warn)('Indexing all PDF objects');
  705. trailerDict = this.indexObjects();
  706. }
  707. trailerDict.assignXref(this);
  708. this.trailer = trailerDict;
  709. var encrypt = trailerDict.get('Encrypt');
  710. if ((0, _primitives.isDict)(encrypt)) {
  711. var ids = trailerDict.get('ID');
  712. var fileId = ids && ids.length ? ids[0] : '';
  713. encrypt.suppressEncryption = true;
  714. this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
  715. }
  716. if (!(this.root = trailerDict.get('Root'))) {
  717. throw new _util.FormatError('Invalid root reference');
  718. }
  719. },
  720. processXRefTable: function XRef_processXRefTable(parser) {
  721. if (!('tableState' in this)) {
  722. this.tableState = {
  723. entryNum: 0,
  724. streamPos: parser.lexer.stream.pos,
  725. parserBuf1: parser.buf1,
  726. parserBuf2: parser.buf2
  727. };
  728. }
  729. var obj = this.readXRefTable(parser);
  730. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  731. throw new _util.FormatError('Invalid XRef table: could not find trailer dictionary');
  732. }
  733. var dict = parser.getObj();
  734. if (!(0, _primitives.isDict)(dict) && dict.dict) {
  735. dict = dict.dict;
  736. }
  737. if (!(0, _primitives.isDict)(dict)) {
  738. throw new _util.FormatError('Invalid XRef table: could not parse trailer dictionary');
  739. }
  740. delete this.tableState;
  741. return dict;
  742. },
  743. readXRefTable: function XRef_readXRefTable(parser) {
  744. var stream = parser.lexer.stream;
  745. var tableState = this.tableState;
  746. stream.pos = tableState.streamPos;
  747. parser.buf1 = tableState.parserBuf1;
  748. parser.buf2 = tableState.parserBuf2;
  749. var obj;
  750. while (true) {
  751. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  752. if ((0, _primitives.isCmd)(obj = parser.getObj(), 'trailer')) {
  753. break;
  754. }
  755. tableState.firstEntryNum = obj;
  756. tableState.entryCount = parser.getObj();
  757. }
  758. var first = tableState.firstEntryNum;
  759. var count = tableState.entryCount;
  760. if (!Number.isInteger(first) || !Number.isInteger(count)) {
  761. throw new _util.FormatError('Invalid XRef table: wrong types in subsection header');
  762. }
  763. for (var i = tableState.entryNum; i < count; i++) {
  764. tableState.streamPos = stream.pos;
  765. tableState.entryNum = i;
  766. tableState.parserBuf1 = parser.buf1;
  767. tableState.parserBuf2 = parser.buf2;
  768. var entry = {};
  769. entry.offset = parser.getObj();
  770. entry.gen = parser.getObj();
  771. var type = parser.getObj();
  772. if ((0, _primitives.isCmd)(type, 'f')) {
  773. entry.free = true;
  774. } else if ((0, _primitives.isCmd)(type, 'n')) {
  775. entry.uncompressed = true;
  776. }
  777. if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
  778. throw new _util.FormatError('Invalid entry in XRef subsection: ' + first + ', ' + count);
  779. }
  780. if (i === 0 && entry.free && first === 1) {
  781. first = 0;
  782. }
  783. if (!this.entries[i + first]) {
  784. this.entries[i + first] = entry;
  785. }
  786. }
  787. tableState.entryNum = 0;
  788. tableState.streamPos = stream.pos;
  789. tableState.parserBuf1 = parser.buf1;
  790. tableState.parserBuf2 = parser.buf2;
  791. delete tableState.firstEntryNum;
  792. delete tableState.entryCount;
  793. }
  794. if (this.entries[0] && !this.entries[0].free) {
  795. throw new _util.FormatError('Invalid XRef table: unexpected first object');
  796. }
  797. return obj;
  798. },
  799. processXRefStream: function XRef_processXRefStream(stream) {
  800. if (!('streamState' in this)) {
  801. var streamParameters = stream.dict;
  802. var byteWidths = streamParameters.get('W');
  803. var range = streamParameters.get('Index');
  804. if (!range) {
  805. range = [0, streamParameters.get('Size')];
  806. }
  807. this.streamState = {
  808. entryRanges: range,
  809. byteWidths: byteWidths,
  810. entryNum: 0,
  811. streamPos: stream.pos
  812. };
  813. }
  814. this.readXRefStream(stream);
  815. delete this.streamState;
  816. return stream.dict;
  817. },
  818. readXRefStream: function XRef_readXRefStream(stream) {
  819. var i, j;
  820. var streamState = this.streamState;
  821. stream.pos = streamState.streamPos;
  822. var byteWidths = streamState.byteWidths;
  823. var typeFieldWidth = byteWidths[0];
  824. var offsetFieldWidth = byteWidths[1];
  825. var generationFieldWidth = byteWidths[2];
  826. var entryRanges = streamState.entryRanges;
  827. while (entryRanges.length > 0) {
  828. var first = entryRanges[0];
  829. var n = entryRanges[1];
  830. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  831. throw new _util.FormatError('Invalid XRef range fields: ' + first + ', ' + n);
  832. }
  833. if (!Number.isInteger(typeFieldWidth) || !Number.isInteger(offsetFieldWidth) || !Number.isInteger(generationFieldWidth)) {
  834. throw new _util.FormatError('Invalid XRef entry fields length: ' + first + ', ' + n);
  835. }
  836. for (i = streamState.entryNum; i < n; ++i) {
  837. streamState.entryNum = i;
  838. streamState.streamPos = stream.pos;
  839. var type = 0,
  840. offset = 0,
  841. generation = 0;
  842. for (j = 0; j < typeFieldWidth; ++j) {
  843. type = type << 8 | stream.getByte();
  844. }
  845. if (typeFieldWidth === 0) {
  846. type = 1;
  847. }
  848. for (j = 0; j < offsetFieldWidth; ++j) {
  849. offset = offset << 8 | stream.getByte();
  850. }
  851. for (j = 0; j < generationFieldWidth; ++j) {
  852. generation = generation << 8 | stream.getByte();
  853. }
  854. var entry = {};
  855. entry.offset = offset;
  856. entry.gen = generation;
  857. switch (type) {
  858. case 0:
  859. entry.free = true;
  860. break;
  861. case 1:
  862. entry.uncompressed = true;
  863. break;
  864. case 2:
  865. break;
  866. default:
  867. throw new _util.FormatError('Invalid XRef entry type: ' + type);
  868. }
  869. if (!this.entries[first + i]) {
  870. this.entries[first + i] = entry;
  871. }
  872. }
  873. streamState.entryNum = 0;
  874. streamState.streamPos = stream.pos;
  875. entryRanges.splice(0, 2);
  876. }
  877. },
  878. indexObjects: function XRef_indexObjects() {
  879. var TAB = 0x9,
  880. LF = 0xA,
  881. CR = 0xD,
  882. SPACE = 0x20;
  883. var PERCENT = 0x25,
  884. LT = 0x3C;
  885. function readToken(data, offset) {
  886. var token = '',
  887. ch = data[offset];
  888. while (ch !== LF && ch !== CR && ch !== LT) {
  889. if (++offset >= data.length) {
  890. break;
  891. }
  892. token += String.fromCharCode(ch);
  893. ch = data[offset];
  894. }
  895. return token;
  896. }
  897. function skipUntil(data, offset, what) {
  898. var length = what.length,
  899. dataLength = data.length;
  900. var skipped = 0;
  901. while (offset < dataLength) {
  902. var i = 0;
  903. while (i < length && data[offset + i] === what[i]) {
  904. ++i;
  905. }
  906. if (i >= length) {
  907. break;
  908. }
  909. offset++;
  910. skipped++;
  911. }
  912. return skipped;
  913. }
  914. var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
  915. var endobjRegExp = /\bendobj[\b\s]$/;
  916. var nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s])$/;
  917. var CHECK_CONTENT_LENGTH = 25;
  918. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  919. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
  920. var objBytes = new Uint8Array([111, 98, 106]);
  921. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  922. this.entries.length = 0;
  923. var stream = this.stream;
  924. stream.pos = 0;
  925. var buffer = stream.getBytes();
  926. var position = stream.start,
  927. length = buffer.length;
  928. var trailers = [],
  929. xrefStms = [];
  930. while (position < length) {
  931. var ch = buffer[position];
  932. if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
  933. ++position;
  934. continue;
  935. }
  936. if (ch === PERCENT) {
  937. do {
  938. ++position;
  939. if (position >= length) {
  940. break;
  941. }
  942. ch = buffer[position];
  943. } while (ch !== LF && ch !== CR);
  944. continue;
  945. }
  946. var token = readToken(buffer, position);
  947. var m;
  948. if (token.indexOf('xref') === 0 && (token.length === 4 || /\s/.test(token[4]))) {
  949. position += skipUntil(buffer, position, trailerBytes);
  950. trailers.push(position);
  951. position += skipUntil(buffer, position, startxrefBytes);
  952. } else if (m = objRegExp.exec(token)) {
  953. if (typeof this.entries[m[1]] === 'undefined') {
  954. this.entries[m[1]] = {
  955. offset: position - stream.start,
  956. gen: m[2] | 0,
  957. uncompressed: true
  958. };
  959. }
  960. var contentLength = void 0,
  961. startPos = position + token.length;
  962. while (startPos < buffer.length) {
  963. var endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
  964. contentLength = endPos - position;
  965. var checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
  966. var tokenStr = (0, _util.bytesToString)(buffer.subarray(checkPos, endPos));
  967. if (endobjRegExp.test(tokenStr)) {
  968. break;
  969. } else {
  970. var objToken = nestedObjRegExp.exec(tokenStr);
  971. if (objToken && objToken[1]) {
  972. (0, _util.warn)('indexObjects: Found new "obj" inside of another "obj", ' + 'caused by missing "endobj" -- trying to recover.');
  973. contentLength -= objToken[1].length;
  974. break;
  975. }
  976. }
  977. startPos += contentLength;
  978. }
  979. var content = buffer.subarray(position, position + contentLength);
  980. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  981. if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
  982. xrefStms.push(position - stream.start);
  983. this.xrefstms[position - stream.start] = 1;
  984. }
  985. position += contentLength;
  986. } else if (token.indexOf('trailer') === 0 && (token.length === 7 || /\s/.test(token[7]))) {
  987. trailers.push(position);
  988. position += skipUntil(buffer, position, startxrefBytes);
  989. } else {
  990. position += token.length + 1;
  991. }
  992. }
  993. var i, ii;
  994. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  995. this.startXRefQueue.push(xrefStms[i]);
  996. this.readXRef(true);
  997. }
  998. var dict;
  999. for (i = 0, ii = trailers.length; i < ii; ++i) {
  1000. stream.pos = trailers[i];
  1001. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this, true);
  1002. var obj = parser.getObj();
  1003. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  1004. continue;
  1005. }
  1006. dict = parser.getObj();
  1007. if (!(0, _primitives.isDict)(dict)) {
  1008. continue;
  1009. }
  1010. if (dict.has('ID')) {
  1011. return dict;
  1012. }
  1013. }
  1014. if (dict) {
  1015. return dict;
  1016. }
  1017. throw new _util.InvalidPDFException('Invalid PDF structure');
  1018. },
  1019. readXRef: function XRef_readXRef(recoveryMode) {
  1020. var stream = this.stream;
  1021. var startXRefParsedCache = Object.create(null);
  1022. try {
  1023. while (this.startXRefQueue.length) {
  1024. var startXRef = this.startXRefQueue[0];
  1025. if (startXRefParsedCache[startXRef]) {
  1026. (0, _util.warn)('readXRef - skipping XRef table since it was already parsed.');
  1027. this.startXRefQueue.shift();
  1028. continue;
  1029. }
  1030. startXRefParsedCache[startXRef] = true;
  1031. stream.pos = startXRef + stream.start;
  1032. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
  1033. var obj = parser.getObj();
  1034. var dict;
  1035. if ((0, _primitives.isCmd)(obj, 'xref')) {
  1036. dict = this.processXRefTable(parser);
  1037. if (!this.topDict) {
  1038. this.topDict = dict;
  1039. }
  1040. obj = dict.get('XRefStm');
  1041. if (Number.isInteger(obj)) {
  1042. var pos = obj;
  1043. if (!(pos in this.xrefstms)) {
  1044. this.xrefstms[pos] = 1;
  1045. this.startXRefQueue.push(pos);
  1046. }
  1047. }
  1048. } else if (Number.isInteger(obj)) {
  1049. if (!Number.isInteger(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), 'obj') || !(0, _primitives.isStream)(obj = parser.getObj())) {
  1050. throw new _util.FormatError('Invalid XRef stream');
  1051. }
  1052. dict = this.processXRefStream(obj);
  1053. if (!this.topDict) {
  1054. this.topDict = dict;
  1055. }
  1056. if (!dict) {
  1057. throw new _util.FormatError('Failed to read XRef stream');
  1058. }
  1059. } else {
  1060. throw new _util.FormatError('Invalid XRef stream header');
  1061. }
  1062. obj = dict.get('Prev');
  1063. if (Number.isInteger(obj)) {
  1064. this.startXRefQueue.push(obj);
  1065. } else if ((0, _primitives.isRef)(obj)) {
  1066. this.startXRefQueue.push(obj.num);
  1067. }
  1068. this.startXRefQueue.shift();
  1069. }
  1070. return this.topDict;
  1071. } catch (e) {
  1072. if (e instanceof _util.MissingDataException) {
  1073. throw e;
  1074. }
  1075. (0, _util.info)('(while reading XRef): ' + e);
  1076. }
  1077. if (recoveryMode) {
  1078. return;
  1079. }
  1080. throw new _util.XRefParseException();
  1081. },
  1082. getEntry: function XRef_getEntry(i) {
  1083. var xrefEntry = this.entries[i];
  1084. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  1085. return xrefEntry;
  1086. }
  1087. return null;
  1088. },
  1089. fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
  1090. if (!(0, _primitives.isRef)(obj)) {
  1091. return obj;
  1092. }
  1093. return this.fetch(obj, suppressEncryption);
  1094. },
  1095. fetch: function XRef_fetch(ref, suppressEncryption) {
  1096. if (!(0, _primitives.isRef)(ref)) {
  1097. throw new Error('ref object is not a reference');
  1098. }
  1099. var num = ref.num;
  1100. if (num in this.cache) {
  1101. var cacheEntry = this.cache[num];
  1102. if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
  1103. cacheEntry.objId = ref.toString();
  1104. }
  1105. return cacheEntry;
  1106. }
  1107. var xrefEntry = this.getEntry(num);
  1108. if (xrefEntry === null) {
  1109. return this.cache[num] = null;
  1110. }
  1111. if (xrefEntry.uncompressed) {
  1112. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  1113. } else {
  1114. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  1115. }
  1116. if ((0, _primitives.isDict)(xrefEntry)) {
  1117. xrefEntry.objId = ref.toString();
  1118. } else if ((0, _primitives.isStream)(xrefEntry)) {
  1119. xrefEntry.dict.objId = ref.toString();
  1120. }
  1121. return xrefEntry;
  1122. },
  1123. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry, suppressEncryption) {
  1124. var gen = ref.gen;
  1125. var num = ref.num;
  1126. if (xrefEntry.gen !== gen) {
  1127. throw new _util.FormatError('inconsistent generation in XRef');
  1128. }
  1129. var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
  1130. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
  1131. var obj1 = parser.getObj();
  1132. var obj2 = parser.getObj();
  1133. var obj3 = parser.getObj();
  1134. if (!Number.isInteger(obj1)) {
  1135. obj1 = parseInt(obj1, 10);
  1136. }
  1137. if (!Number.isInteger(obj2)) {
  1138. obj2 = parseInt(obj2, 10);
  1139. }
  1140. if (obj1 !== num || obj2 !== gen || !(0, _primitives.isCmd)(obj3)) {
  1141. throw new _util.FormatError('bad XRef entry');
  1142. }
  1143. if (obj3.cmd !== 'obj') {
  1144. if (obj3.cmd.indexOf('obj') === 0) {
  1145. num = parseInt(obj3.cmd.substring(3), 10);
  1146. if (!Number.isNaN(num)) {
  1147. return num;
  1148. }
  1149. }
  1150. throw new _util.FormatError('bad XRef entry');
  1151. }
  1152. if (this.encrypt && !suppressEncryption) {
  1153. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  1154. } else {
  1155. xrefEntry = parser.getObj();
  1156. }
  1157. if (!(0, _primitives.isStream)(xrefEntry)) {
  1158. this.cache[num] = xrefEntry;
  1159. }
  1160. return xrefEntry;
  1161. },
  1162. fetchCompressed: function XRef_fetchCompressed(xrefEntry, suppressEncryption) {
  1163. var tableOffset = xrefEntry.offset;
  1164. var stream = this.fetch(new _primitives.Ref(tableOffset, 0));
  1165. if (!(0, _primitives.isStream)(stream)) {
  1166. throw new _util.FormatError('bad ObjStm stream');
  1167. }
  1168. var first = stream.dict.get('First');
  1169. var n = stream.dict.get('N');
  1170. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1171. throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
  1172. }
  1173. var parser = new _parser.Parser(new _parser.Lexer(stream), false, this);
  1174. parser.allowStreams = true;
  1175. var i,
  1176. entries = [],
  1177. num,
  1178. nums = [];
  1179. for (i = 0; i < n; ++i) {
  1180. num = parser.getObj();
  1181. if (!Number.isInteger(num)) {
  1182. throw new _util.FormatError('invalid object number in the ObjStm stream: ' + num);
  1183. }
  1184. nums.push(num);
  1185. var offset = parser.getObj();
  1186. if (!Number.isInteger(offset)) {
  1187. throw new _util.FormatError('invalid object offset in the ObjStm stream: ' + offset);
  1188. }
  1189. }
  1190. for (i = 0; i < n; ++i) {
  1191. entries.push(parser.getObj());
  1192. if ((0, _primitives.isCmd)(parser.buf1, 'endobj')) {
  1193. parser.shift();
  1194. }
  1195. num = nums[i];
  1196. var entry = this.entries[num];
  1197. if (entry && entry.offset === tableOffset && entry.gen === i) {
  1198. this.cache[num] = entries[i];
  1199. }
  1200. }
  1201. xrefEntry = entries[xrefEntry.gen];
  1202. if (xrefEntry === undefined) {
  1203. throw new _util.FormatError('bad XRef entry for compressed object');
  1204. }
  1205. return xrefEntry;
  1206. },
  1207. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj, suppressEncryption) {
  1208. if (!(0, _primitives.isRef)(obj)) {
  1209. return Promise.resolve(obj);
  1210. }
  1211. return this.fetchAsync(obj, suppressEncryption);
  1212. },
  1213. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  1214. var streamManager = this.stream.manager;
  1215. var xref = this;
  1216. return new Promise(function tryFetch(resolve, reject) {
  1217. try {
  1218. resolve(xref.fetch(ref, suppressEncryption));
  1219. } catch (e) {
  1220. if (e instanceof _util.MissingDataException) {
  1221. streamManager.requestRange(e.begin, e.end).then(function () {
  1222. tryFetch(resolve, reject);
  1223. }, reject);
  1224. return;
  1225. }
  1226. reject(e);
  1227. }
  1228. });
  1229. },
  1230. getCatalogObj: function XRef_getCatalogObj() {
  1231. return this.root;
  1232. }
  1233. };
  1234. return XRef;
  1235. }();
  1236. var NameOrNumberTree = function NameOrNumberTreeClosure() {
  1237. function NameOrNumberTree(root, xref) {
  1238. (0, _util.unreachable)('Cannot initialize NameOrNumberTree.');
  1239. }
  1240. NameOrNumberTree.prototype = {
  1241. getAll: function NameOrNumberTree_getAll() {
  1242. var dict = Object.create(null);
  1243. if (!this.root) {
  1244. return dict;
  1245. }
  1246. var xref = this.xref;
  1247. var processed = new _primitives.RefSet();
  1248. processed.put(this.root);
  1249. var queue = [this.root];
  1250. while (queue.length > 0) {
  1251. var i, n;
  1252. var obj = xref.fetchIfRef(queue.shift());
  1253. if (!(0, _primitives.isDict)(obj)) {
  1254. continue;
  1255. }
  1256. if (obj.has('Kids')) {
  1257. var kids = obj.get('Kids');
  1258. for (i = 0, n = kids.length; i < n; i++) {
  1259. var kid = kids[i];
  1260. if (processed.has(kid)) {
  1261. throw new _util.FormatError('Duplicate entry in "' + this._type + '" tree.');
  1262. }
  1263. queue.push(kid);
  1264. processed.put(kid);
  1265. }
  1266. continue;
  1267. }
  1268. var entries = obj.get(this._type);
  1269. if (Array.isArray(entries)) {
  1270. for (i = 0, n = entries.length; i < n; i += 2) {
  1271. dict[xref.fetchIfRef(entries[i])] = xref.fetchIfRef(entries[i + 1]);
  1272. }
  1273. }
  1274. }
  1275. return dict;
  1276. },
  1277. get: function NameOrNumberTree_get(key) {
  1278. if (!this.root) {
  1279. return null;
  1280. }
  1281. var xref = this.xref;
  1282. var kidsOrEntries = xref.fetchIfRef(this.root);
  1283. var loopCount = 0;
  1284. var MAX_LEVELS = 10;
  1285. var l, r, m;
  1286. while (kidsOrEntries.has('Kids')) {
  1287. if (++loopCount > MAX_LEVELS) {
  1288. (0, _util.warn)('Search depth limit reached for "' + this._type + '" tree.');
  1289. return null;
  1290. }
  1291. var kids = kidsOrEntries.get('Kids');
  1292. if (!Array.isArray(kids)) {
  1293. return null;
  1294. }
  1295. l = 0;
  1296. r = kids.length - 1;
  1297. while (l <= r) {
  1298. m = l + r >> 1;
  1299. var kid = xref.fetchIfRef(kids[m]);
  1300. var limits = kid.get('Limits');
  1301. if (key < xref.fetchIfRef(limits[0])) {
  1302. r = m - 1;
  1303. } else if (key > xref.fetchIfRef(limits[1])) {
  1304. l = m + 1;
  1305. } else {
  1306. kidsOrEntries = xref.fetchIfRef(kids[m]);
  1307. break;
  1308. }
  1309. }
  1310. if (l > r) {
  1311. return null;
  1312. }
  1313. }
  1314. var entries = kidsOrEntries.get(this._type);
  1315. if (Array.isArray(entries)) {
  1316. l = 0;
  1317. r = entries.length - 2;
  1318. while (l <= r) {
  1319. m = l + r & ~1;
  1320. var currentKey = xref.fetchIfRef(entries[m]);
  1321. if (key < currentKey) {
  1322. r = m - 2;
  1323. } else if (key > currentKey) {
  1324. l = m + 2;
  1325. } else {
  1326. return xref.fetchIfRef(entries[m + 1]);
  1327. }
  1328. }
  1329. }
  1330. return null;
  1331. }
  1332. };
  1333. return NameOrNumberTree;
  1334. }();
  1335. var NameTree = function NameTreeClosure() {
  1336. function NameTree(root, xref) {
  1337. this.root = root;
  1338. this.xref = xref;
  1339. this._type = 'Names';
  1340. }
  1341. _util.Util.inherit(NameTree, NameOrNumberTree, {});
  1342. return NameTree;
  1343. }();
  1344. var NumberTree = function NumberTreeClosure() {
  1345. function NumberTree(root, xref) {
  1346. this.root = root;
  1347. this.xref = xref;
  1348. this._type = 'Nums';
  1349. }
  1350. _util.Util.inherit(NumberTree, NameOrNumberTree, {});
  1351. return NumberTree;
  1352. }();
  1353. var FileSpec = function FileSpecClosure() {
  1354. function FileSpec(root, xref) {
  1355. if (!root || !(0, _primitives.isDict)(root)) {
  1356. return;
  1357. }
  1358. this.xref = xref;
  1359. this.root = root;
  1360. if (root.has('FS')) {
  1361. this.fs = root.get('FS');
  1362. }
  1363. this.description = root.has('Desc') ? (0, _util.stringToPDFString)(root.get('Desc')) : '';
  1364. if (root.has('RF')) {
  1365. (0, _util.warn)('Related file specifications are not supported');
  1366. }
  1367. this.contentAvailable = true;
  1368. if (!root.has('EF')) {
  1369. this.contentAvailable = false;
  1370. (0, _util.warn)('Non-embedded file specifications are not supported');
  1371. }
  1372. }
  1373. function pickPlatformItem(dict) {
  1374. if (dict.has('UF')) {
  1375. return dict.get('UF');
  1376. } else if (dict.has('F')) {
  1377. return dict.get('F');
  1378. } else if (dict.has('Unix')) {
  1379. return dict.get('Unix');
  1380. } else if (dict.has('Mac')) {
  1381. return dict.get('Mac');
  1382. } else if (dict.has('DOS')) {
  1383. return dict.get('DOS');
  1384. }
  1385. return null;
  1386. }
  1387. FileSpec.prototype = {
  1388. get filename() {
  1389. if (!this._filename && this.root) {
  1390. var filename = pickPlatformItem(this.root) || 'unnamed';
  1391. this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
  1392. }
  1393. return this._filename;
  1394. },
  1395. get content() {
  1396. if (!this.contentAvailable) {
  1397. return null;
  1398. }
  1399. if (!this.contentRef && this.root) {
  1400. this.contentRef = pickPlatformItem(this.root.get('EF'));
  1401. }
  1402. var content = null;
  1403. if (this.contentRef) {
  1404. var xref = this.xref;
  1405. var fileObj = xref.fetchIfRef(this.contentRef);
  1406. if (fileObj && (0, _primitives.isStream)(fileObj)) {
  1407. content = fileObj.getBytes();
  1408. } else {
  1409. (0, _util.warn)('Embedded file specification points to non-existing/invalid ' + 'content');
  1410. }
  1411. } else {
  1412. (0, _util.warn)('Embedded file specification does not have a content');
  1413. }
  1414. return content;
  1415. },
  1416. get serializable() {
  1417. return {
  1418. filename: this.filename,
  1419. content: this.content
  1420. };
  1421. }
  1422. };
  1423. return FileSpec;
  1424. }();
  1425. var ObjectLoader = function () {
  1426. function mayHaveChildren(value) {
  1427. return (0, _primitives.isRef)(value) || (0, _primitives.isDict)(value) || Array.isArray(value) || (0, _primitives.isStream)(value);
  1428. }
  1429. function addChildren(node, nodesToVisit) {
  1430. if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
  1431. var dict = (0, _primitives.isDict)(node) ? node : node.dict;
  1432. var dictKeys = dict.getKeys();
  1433. for (var i = 0, ii = dictKeys.length; i < ii; i++) {
  1434. var rawValue = dict.getRaw(dictKeys[i]);
  1435. if (mayHaveChildren(rawValue)) {
  1436. nodesToVisit.push(rawValue);
  1437. }
  1438. }
  1439. } else if (Array.isArray(node)) {
  1440. for (var _i = 0, _ii = node.length; _i < _ii; _i++) {
  1441. var value = node[_i];
  1442. if (mayHaveChildren(value)) {
  1443. nodesToVisit.push(value);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. function ObjectLoader(dict, keys, xref) {
  1449. this.dict = dict;
  1450. this.keys = keys;
  1451. this.xref = xref;
  1452. this.refSet = null;
  1453. this.capability = null;
  1454. }
  1455. ObjectLoader.prototype = {
  1456. load: function load() {
  1457. this.capability = (0, _util.createPromiseCapability)();
  1458. if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
  1459. this.capability.resolve();
  1460. return this.capability.promise;
  1461. }
  1462. var keys = this.keys,
  1463. dict = this.dict;
  1464. this.refSet = new _primitives.RefSet();
  1465. var nodesToVisit = [];
  1466. for (var i = 0, ii = keys.length; i < ii; i++) {
  1467. var rawValue = dict.getRaw(keys[i]);
  1468. if (rawValue !== undefined) {
  1469. nodesToVisit.push(rawValue);
  1470. }
  1471. }
  1472. this._walk(nodesToVisit);
  1473. return this.capability.promise;
  1474. },
  1475. _walk: function _walk(nodesToVisit) {
  1476. var _this3 = this;
  1477. var nodesToRevisit = [];
  1478. var pendingRequests = [];
  1479. while (nodesToVisit.length) {
  1480. var currentNode = nodesToVisit.pop();
  1481. if ((0, _primitives.isRef)(currentNode)) {
  1482. if (this.refSet.has(currentNode)) {
  1483. continue;
  1484. }
  1485. try {
  1486. this.refSet.put(currentNode);
  1487. currentNode = this.xref.fetch(currentNode);
  1488. } catch (ex) {
  1489. if (!(ex instanceof _util.MissingDataException)) {
  1490. throw ex;
  1491. }
  1492. nodesToRevisit.push(currentNode);
  1493. pendingRequests.push({
  1494. begin: ex.begin,
  1495. end: ex.end
  1496. });
  1497. }
  1498. }
  1499. if (currentNode && currentNode.getBaseStreams) {
  1500. var baseStreams = currentNode.getBaseStreams();
  1501. var foundMissingData = false;
  1502. for (var i = 0, ii = baseStreams.length; i < ii; i++) {
  1503. var stream = baseStreams[i];
  1504. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  1505. foundMissingData = true;
  1506. pendingRequests.push({
  1507. begin: stream.start,
  1508. end: stream.end
  1509. });
  1510. }
  1511. }
  1512. if (foundMissingData) {
  1513. nodesToRevisit.push(currentNode);
  1514. }
  1515. }
  1516. addChildren(currentNode, nodesToVisit);
  1517. }
  1518. if (pendingRequests.length) {
  1519. this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
  1520. for (var _i2 = 0, _ii2 = nodesToRevisit.length; _i2 < _ii2; _i2++) {
  1521. var node = nodesToRevisit[_i2];
  1522. if ((0, _primitives.isRef)(node)) {
  1523. _this3.refSet.remove(node);
  1524. }
  1525. }
  1526. _this3._walk(nodesToRevisit);
  1527. }, this.capability.reject);
  1528. return;
  1529. }
  1530. this.refSet = null;
  1531. this.capability.resolve();
  1532. }
  1533. };
  1534. return ObjectLoader;
  1535. }();
  1536. exports.Catalog = Catalog;
  1537. exports.ObjectLoader = ObjectLoader;
  1538. exports.XRef = XRef;
  1539. exports.FileSpec = FileSpec;