obj.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  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 ((0, _util.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 (!(0, _util.isInt)(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 && !((0, _util.isInt)(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 = [];
  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. javaScript.push((0, _util.stringToPDFString)(js));
  362. }
  363. if (obj && obj.has('JavaScript')) {
  364. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  365. var names = nameTree.getAll();
  366. for (var name in names) {
  367. var jsDict = names[name];
  368. if ((0, _primitives.isDict)(jsDict)) {
  369. appendIfJavaScriptDict(jsDict);
  370. }
  371. }
  372. }
  373. var openactionDict = this.catDict.get('OpenAction');
  374. if ((0, _primitives.isDict)(openactionDict, 'Action')) {
  375. var actionType = openactionDict.get('S');
  376. if ((0, _primitives.isName)(actionType, 'Named')) {
  377. var action = openactionDict.get('N');
  378. if ((0, _primitives.isName)(action, 'Print')) {
  379. javaScript.push('print({});');
  380. }
  381. } else {
  382. appendIfJavaScriptDict(openactionDict);
  383. }
  384. }
  385. return (0, _util.shadow)(this, 'javaScript', javaScript);
  386. },
  387. cleanup: function Catalog_cleanup() {
  388. var _this = this;
  389. this.pageKidsCountCache.clear();
  390. var promises = [];
  391. this.fontCache.forEach(function (promise) {
  392. promises.push(promise);
  393. });
  394. return Promise.all(promises).then(function (translatedFonts) {
  395. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  396. var font = translatedFonts[i].dict;
  397. delete font.translated;
  398. }
  399. _this.fontCache.clear();
  400. _this.builtInCMapCache = Object.create(null);
  401. });
  402. },
  403. getPage: function Catalog_getPage(pageIndex) {
  404. var _this2 = this;
  405. if (!(pageIndex in this.pagePromises)) {
  406. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(function (_ref) {
  407. var _ref2 = _slicedToArray(_ref, 2),
  408. dict = _ref2[0],
  409. ref = _ref2[1];
  410. return _this2.pageFactory.createPage(pageIndex, dict, ref, _this2.fontCache, _this2.builtInCMapCache);
  411. });
  412. }
  413. return this.pagePromises[pageIndex];
  414. },
  415. getPageDict: function Catalog_getPageDict(pageIndex) {
  416. var capability = (0, _util.createPromiseCapability)();
  417. var nodesToVisit = [this.catDict.getRaw('Pages')];
  418. var count,
  419. currentPageIndex = 0;
  420. var xref = this.xref,
  421. pageKidsCountCache = this.pageKidsCountCache;
  422. function next() {
  423. while (nodesToVisit.length) {
  424. var currentNode = nodesToVisit.pop();
  425. if ((0, _primitives.isRef)(currentNode)) {
  426. count = pageKidsCountCache.get(currentNode);
  427. if (count > 0 && currentPageIndex + count < pageIndex) {
  428. currentPageIndex += count;
  429. continue;
  430. }
  431. xref.fetchAsync(currentNode).then(function (obj) {
  432. if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Kids')) {
  433. if (pageIndex === currentPageIndex) {
  434. if (currentNode && !pageKidsCountCache.has(currentNode)) {
  435. pageKidsCountCache.put(currentNode, 1);
  436. }
  437. capability.resolve([obj, currentNode]);
  438. } else {
  439. currentPageIndex++;
  440. next();
  441. }
  442. return;
  443. }
  444. nodesToVisit.push(obj);
  445. next();
  446. }, capability.reject);
  447. return;
  448. }
  449. if (!(0, _primitives.isDict)(currentNode)) {
  450. capability.reject(new _util.FormatError('page dictionary kid reference points to wrong type of object'));
  451. return;
  452. }
  453. count = currentNode.get('Count');
  454. var objId = currentNode.objId;
  455. if (objId && !pageKidsCountCache.has(objId)) {
  456. pageKidsCountCache.put(objId, count);
  457. }
  458. if (currentPageIndex + count <= pageIndex) {
  459. currentPageIndex += count;
  460. continue;
  461. }
  462. var kids = currentNode.get('Kids');
  463. if (!(0, _util.isArray)(kids)) {
  464. capability.reject(new _util.FormatError('page dictionary kids object is not an array'));
  465. return;
  466. }
  467. for (var last = kids.length - 1; last >= 0; last--) {
  468. nodesToVisit.push(kids[last]);
  469. }
  470. }
  471. capability.reject(new Error('Page index ' + pageIndex + ' not found.'));
  472. }
  473. next();
  474. return capability.promise;
  475. },
  476. getPageIndex: function Catalog_getPageIndex(pageRef) {
  477. var xref = this.xref;
  478. function pagesBeforeRef(kidRef) {
  479. var total = 0;
  480. var parentRef;
  481. return xref.fetchAsync(kidRef).then(function (node) {
  482. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, 'Page') && !((0, _primitives.isDict)(node) && !node.has('Type') && node.has('Contents'))) {
  483. throw new _util.FormatError('The reference does not point to a /Page Dict.');
  484. }
  485. if (!node) {
  486. return null;
  487. }
  488. if (!(0, _primitives.isDict)(node)) {
  489. throw new _util.FormatError('node must be a Dict.');
  490. }
  491. parentRef = node.getRaw('Parent');
  492. return node.getAsync('Parent');
  493. }).then(function (parent) {
  494. if (!parent) {
  495. return null;
  496. }
  497. if (!(0, _primitives.isDict)(parent)) {
  498. throw new _util.FormatError('parent must be a Dict.');
  499. }
  500. return parent.getAsync('Kids');
  501. }).then(function (kids) {
  502. if (!kids) {
  503. return null;
  504. }
  505. var kidPromises = [];
  506. var found = false;
  507. for (var i = 0; i < kids.length; i++) {
  508. var kid = kids[i];
  509. if (!(0, _primitives.isRef)(kid)) {
  510. throw new _util.FormatError('kid must be a Ref.');
  511. }
  512. if (kid.num === kidRef.num) {
  513. found = true;
  514. break;
  515. }
  516. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  517. if (kid.has('Count')) {
  518. var count = kid.get('Count');
  519. total += count;
  520. } else {
  521. total++;
  522. }
  523. }));
  524. }
  525. if (!found) {
  526. throw new _util.FormatError('kid ref not found in parents kids');
  527. }
  528. return Promise.all(kidPromises).then(function () {
  529. return [total, parentRef];
  530. });
  531. });
  532. }
  533. var total = 0;
  534. function next(ref) {
  535. return pagesBeforeRef(ref).then(function (args) {
  536. if (!args) {
  537. return total;
  538. }
  539. var count = args[0];
  540. var parentRef = args[1];
  541. total += count;
  542. return next(parentRef);
  543. });
  544. }
  545. return next(pageRef);
  546. }
  547. };
  548. Catalog.parseDestDictionary = function Catalog_parseDestDictionary(params) {
  549. function addDefaultProtocolToUrl(url) {
  550. if (url.indexOf('www.') === 0) {
  551. return 'http://' + url;
  552. }
  553. return url;
  554. }
  555. function tryConvertUrlEncoding(url) {
  556. try {
  557. return (0, _util.stringToUTF8String)(url);
  558. } catch (e) {
  559. return url;
  560. }
  561. }
  562. var destDict = params.destDict;
  563. if (!(0, _primitives.isDict)(destDict)) {
  564. (0, _util.warn)('parseDestDictionary: "destDict" must be a dictionary.');
  565. return;
  566. }
  567. var resultObj = params.resultObj;
  568. if ((typeof resultObj === 'undefined' ? 'undefined' : _typeof(resultObj)) !== 'object') {
  569. (0, _util.warn)('parseDestDictionary: "resultObj" must be an object.');
  570. return;
  571. }
  572. var docBaseUrl = params.docBaseUrl || null;
  573. var action = destDict.get('A'),
  574. url,
  575. dest;
  576. if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
  577. action = destDict.get('Dest');
  578. }
  579. if ((0, _primitives.isDict)(action)) {
  580. var actionType = action.get('S');
  581. if (!(0, _primitives.isName)(actionType)) {
  582. (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
  583. return;
  584. }
  585. var actionName = actionType.name;
  586. switch (actionName) {
  587. case 'URI':
  588. url = action.get('URI');
  589. if ((0, _primitives.isName)(url)) {
  590. url = '/' + url.name;
  591. } else if ((0, _util.isString)(url)) {
  592. url = addDefaultProtocolToUrl(url);
  593. }
  594. break;
  595. case 'GoTo':
  596. dest = action.get('D');
  597. break;
  598. case 'Launch':
  599. case 'GoToR':
  600. var urlDict = action.get('F');
  601. if ((0, _primitives.isDict)(urlDict)) {
  602. url = urlDict.get('F') || null;
  603. } else if ((0, _util.isString)(urlDict)) {
  604. url = urlDict;
  605. }
  606. var remoteDest = action.get('D');
  607. if (remoteDest) {
  608. if ((0, _primitives.isName)(remoteDest)) {
  609. remoteDest = remoteDest.name;
  610. }
  611. if ((0, _util.isString)(url)) {
  612. var baseUrl = url.split('#')[0];
  613. if ((0, _util.isString)(remoteDest)) {
  614. url = baseUrl + '#' + remoteDest;
  615. } else if ((0, _util.isArray)(remoteDest)) {
  616. url = baseUrl + '#' + JSON.stringify(remoteDest);
  617. }
  618. }
  619. }
  620. var newWindow = action.get('NewWindow');
  621. if ((0, _util.isBool)(newWindow)) {
  622. resultObj.newWindow = newWindow;
  623. }
  624. break;
  625. case 'Named':
  626. var namedAction = action.get('N');
  627. if ((0, _primitives.isName)(namedAction)) {
  628. resultObj.action = namedAction.name;
  629. }
  630. break;
  631. case 'JavaScript':
  632. var jsAction = action.get('JS'),
  633. js;
  634. if ((0, _primitives.isStream)(jsAction)) {
  635. js = (0, _util.bytesToString)(jsAction.getBytes());
  636. } else if ((0, _util.isString)(jsAction)) {
  637. js = jsAction;
  638. }
  639. if (js) {
  640. var URL_OPEN_METHODS = ['app.launchURL', 'window.open'];
  641. var regex = new RegExp('^\\s*(' + URL_OPEN_METHODS.join('|').split('.').join('\\.') + ')\\((?:\'|\")([^\'\"]*)(?:\'|\")(?:,\\s*(\\w+)\\)|\\))', 'i');
  642. var jsUrl = regex.exec((0, _util.stringToPDFString)(js));
  643. if (jsUrl && jsUrl[2]) {
  644. url = jsUrl[2];
  645. if (jsUrl[3] === 'true' && jsUrl[1] === 'app.launchURL') {
  646. resultObj.newWindow = true;
  647. }
  648. break;
  649. }
  650. }
  651. default:
  652. (0, _util.warn)('parseDestDictionary: Unsupported Action type "' + actionName + '".');
  653. break;
  654. }
  655. } else if (destDict.has('Dest')) {
  656. dest = destDict.get('Dest');
  657. }
  658. if ((0, _util.isString)(url)) {
  659. url = tryConvertUrlEncoding(url);
  660. var absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
  661. if (absoluteUrl) {
  662. resultObj.url = absoluteUrl.href;
  663. }
  664. resultObj.unsafeUrl = url;
  665. }
  666. if (dest) {
  667. if ((0, _primitives.isName)(dest)) {
  668. dest = dest.name;
  669. }
  670. if ((0, _util.isString)(dest) || (0, _util.isArray)(dest)) {
  671. resultObj.dest = dest;
  672. }
  673. }
  674. };
  675. return Catalog;
  676. }();
  677. var XRef = function XRefClosure() {
  678. function XRef(stream, pdfManager) {
  679. this.stream = stream;
  680. this.pdfManager = pdfManager;
  681. this.entries = [];
  682. this.xrefstms = Object.create(null);
  683. this.cache = [];
  684. this.stats = {
  685. streamTypes: [],
  686. fontTypes: []
  687. };
  688. }
  689. XRef.prototype = {
  690. setStartXRef: function XRef_setStartXRef(startXRef) {
  691. this.startXRefQueue = [startXRef];
  692. },
  693. parse: function XRef_parse(recoveryMode) {
  694. var trailerDict;
  695. if (!recoveryMode) {
  696. trailerDict = this.readXRef();
  697. } else {
  698. (0, _util.warn)('Indexing all PDF objects');
  699. trailerDict = this.indexObjects();
  700. }
  701. trailerDict.assignXref(this);
  702. this.trailer = trailerDict;
  703. var encrypt = trailerDict.get('Encrypt');
  704. if ((0, _primitives.isDict)(encrypt)) {
  705. var ids = trailerDict.get('ID');
  706. var fileId = ids && ids.length ? ids[0] : '';
  707. encrypt.suppressEncryption = true;
  708. this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
  709. }
  710. if (!(this.root = trailerDict.get('Root'))) {
  711. throw new _util.FormatError('Invalid root reference');
  712. }
  713. },
  714. processXRefTable: function XRef_processXRefTable(parser) {
  715. if (!('tableState' in this)) {
  716. this.tableState = {
  717. entryNum: 0,
  718. streamPos: parser.lexer.stream.pos,
  719. parserBuf1: parser.buf1,
  720. parserBuf2: parser.buf2
  721. };
  722. }
  723. var obj = this.readXRefTable(parser);
  724. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  725. throw new _util.FormatError('Invalid XRef table: could not find trailer dictionary');
  726. }
  727. var dict = parser.getObj();
  728. if (!(0, _primitives.isDict)(dict) && dict.dict) {
  729. dict = dict.dict;
  730. }
  731. if (!(0, _primitives.isDict)(dict)) {
  732. throw new _util.FormatError('Invalid XRef table: could not parse trailer dictionary');
  733. }
  734. delete this.tableState;
  735. return dict;
  736. },
  737. readXRefTable: function XRef_readXRefTable(parser) {
  738. var stream = parser.lexer.stream;
  739. var tableState = this.tableState;
  740. stream.pos = tableState.streamPos;
  741. parser.buf1 = tableState.parserBuf1;
  742. parser.buf2 = tableState.parserBuf2;
  743. var obj;
  744. while (true) {
  745. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  746. if ((0, _primitives.isCmd)(obj = parser.getObj(), 'trailer')) {
  747. break;
  748. }
  749. tableState.firstEntryNum = obj;
  750. tableState.entryCount = parser.getObj();
  751. }
  752. var first = tableState.firstEntryNum;
  753. var count = tableState.entryCount;
  754. if (!(0, _util.isInt)(first) || !(0, _util.isInt)(count)) {
  755. throw new _util.FormatError('Invalid XRef table: wrong types in subsection header');
  756. }
  757. for (var i = tableState.entryNum; i < count; i++) {
  758. tableState.streamPos = stream.pos;
  759. tableState.entryNum = i;
  760. tableState.parserBuf1 = parser.buf1;
  761. tableState.parserBuf2 = parser.buf2;
  762. var entry = {};
  763. entry.offset = parser.getObj();
  764. entry.gen = parser.getObj();
  765. var type = parser.getObj();
  766. if ((0, _primitives.isCmd)(type, 'f')) {
  767. entry.free = true;
  768. } else if ((0, _primitives.isCmd)(type, 'n')) {
  769. entry.uncompressed = true;
  770. }
  771. if (!(0, _util.isInt)(entry.offset) || !(0, _util.isInt)(entry.gen) || !(entry.free || entry.uncompressed)) {
  772. throw new _util.FormatError('Invalid entry in XRef subsection: ' + first + ', ' + count);
  773. }
  774. if (i === 0 && entry.free && first === 1) {
  775. first = 0;
  776. }
  777. if (!this.entries[i + first]) {
  778. this.entries[i + first] = entry;
  779. }
  780. }
  781. tableState.entryNum = 0;
  782. tableState.streamPos = stream.pos;
  783. tableState.parserBuf1 = parser.buf1;
  784. tableState.parserBuf2 = parser.buf2;
  785. delete tableState.firstEntryNum;
  786. delete tableState.entryCount;
  787. }
  788. if (this.entries[0] && !this.entries[0].free) {
  789. throw new _util.FormatError('Invalid XRef table: unexpected first object');
  790. }
  791. return obj;
  792. },
  793. processXRefStream: function XRef_processXRefStream(stream) {
  794. if (!('streamState' in this)) {
  795. var streamParameters = stream.dict;
  796. var byteWidths = streamParameters.get('W');
  797. var range = streamParameters.get('Index');
  798. if (!range) {
  799. range = [0, streamParameters.get('Size')];
  800. }
  801. this.streamState = {
  802. entryRanges: range,
  803. byteWidths: byteWidths,
  804. entryNum: 0,
  805. streamPos: stream.pos
  806. };
  807. }
  808. this.readXRefStream(stream);
  809. delete this.streamState;
  810. return stream.dict;
  811. },
  812. readXRefStream: function XRef_readXRefStream(stream) {
  813. var i, j;
  814. var streamState = this.streamState;
  815. stream.pos = streamState.streamPos;
  816. var byteWidths = streamState.byteWidths;
  817. var typeFieldWidth = byteWidths[0];
  818. var offsetFieldWidth = byteWidths[1];
  819. var generationFieldWidth = byteWidths[2];
  820. var entryRanges = streamState.entryRanges;
  821. while (entryRanges.length > 0) {
  822. var first = entryRanges[0];
  823. var n = entryRanges[1];
  824. if (!(0, _util.isInt)(first) || !(0, _util.isInt)(n)) {
  825. throw new _util.FormatError('Invalid XRef range fields: ' + first + ', ' + n);
  826. }
  827. if (!(0, _util.isInt)(typeFieldWidth) || !(0, _util.isInt)(offsetFieldWidth) || !(0, _util.isInt)(generationFieldWidth)) {
  828. throw new _util.FormatError('Invalid XRef entry fields length: ' + first + ', ' + n);
  829. }
  830. for (i = streamState.entryNum; i < n; ++i) {
  831. streamState.entryNum = i;
  832. streamState.streamPos = stream.pos;
  833. var type = 0,
  834. offset = 0,
  835. generation = 0;
  836. for (j = 0; j < typeFieldWidth; ++j) {
  837. type = type << 8 | stream.getByte();
  838. }
  839. if (typeFieldWidth === 0) {
  840. type = 1;
  841. }
  842. for (j = 0; j < offsetFieldWidth; ++j) {
  843. offset = offset << 8 | stream.getByte();
  844. }
  845. for (j = 0; j < generationFieldWidth; ++j) {
  846. generation = generation << 8 | stream.getByte();
  847. }
  848. var entry = {};
  849. entry.offset = offset;
  850. entry.gen = generation;
  851. switch (type) {
  852. case 0:
  853. entry.free = true;
  854. break;
  855. case 1:
  856. entry.uncompressed = true;
  857. break;
  858. case 2:
  859. break;
  860. default:
  861. throw new _util.FormatError('Invalid XRef entry type: ' + type);
  862. }
  863. if (!this.entries[first + i]) {
  864. this.entries[first + i] = entry;
  865. }
  866. }
  867. streamState.entryNum = 0;
  868. streamState.streamPos = stream.pos;
  869. entryRanges.splice(0, 2);
  870. }
  871. },
  872. indexObjects: function XRef_indexObjects() {
  873. var TAB = 0x9,
  874. LF = 0xA,
  875. CR = 0xD,
  876. SPACE = 0x20;
  877. var PERCENT = 0x25,
  878. LT = 0x3C;
  879. function readToken(data, offset) {
  880. var token = '',
  881. ch = data[offset];
  882. while (ch !== LF && ch !== CR && ch !== LT) {
  883. if (++offset >= data.length) {
  884. break;
  885. }
  886. token += String.fromCharCode(ch);
  887. ch = data[offset];
  888. }
  889. return token;
  890. }
  891. function skipUntil(data, offset, what) {
  892. var length = what.length,
  893. dataLength = data.length;
  894. var skipped = 0;
  895. while (offset < dataLength) {
  896. var i = 0;
  897. while (i < length && data[offset + i] === what[i]) {
  898. ++i;
  899. }
  900. if (i >= length) {
  901. break;
  902. }
  903. offset++;
  904. skipped++;
  905. }
  906. return skipped;
  907. }
  908. var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
  909. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  910. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
  911. var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);
  912. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  913. this.entries.length = 0;
  914. var stream = this.stream;
  915. stream.pos = 0;
  916. var buffer = stream.getBytes();
  917. var position = stream.start,
  918. length = buffer.length;
  919. var trailers = [],
  920. xrefStms = [];
  921. while (position < length) {
  922. var ch = buffer[position];
  923. if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
  924. ++position;
  925. continue;
  926. }
  927. if (ch === PERCENT) {
  928. do {
  929. ++position;
  930. if (position >= length) {
  931. break;
  932. }
  933. ch = buffer[position];
  934. } while (ch !== LF && ch !== CR);
  935. continue;
  936. }
  937. var token = readToken(buffer, position);
  938. var m;
  939. if (token.indexOf('xref') === 0 && (token.length === 4 || /\s/.test(token[4]))) {
  940. position += skipUntil(buffer, position, trailerBytes);
  941. trailers.push(position);
  942. position += skipUntil(buffer, position, startxrefBytes);
  943. } else if (m = objRegExp.exec(token)) {
  944. if (typeof this.entries[m[1]] === 'undefined') {
  945. this.entries[m[1]] = {
  946. offset: position - stream.start,
  947. gen: m[2] | 0,
  948. uncompressed: true
  949. };
  950. }
  951. var contentLength = skipUntil(buffer, position, endobjBytes) + 7;
  952. var content = buffer.subarray(position, position + contentLength);
  953. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  954. if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
  955. xrefStms.push(position - stream.start);
  956. this.xrefstms[position - stream.start] = 1;
  957. }
  958. position += contentLength;
  959. } else if (token.indexOf('trailer') === 0 && (token.length === 7 || /\s/.test(token[7]))) {
  960. trailers.push(position);
  961. position += skipUntil(buffer, position, startxrefBytes);
  962. } else {
  963. position += token.length + 1;
  964. }
  965. }
  966. var i, ii;
  967. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  968. this.startXRefQueue.push(xrefStms[i]);
  969. this.readXRef(true);
  970. }
  971. var dict;
  972. for (i = 0, ii = trailers.length; i < ii; ++i) {
  973. stream.pos = trailers[i];
  974. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this, true);
  975. var obj = parser.getObj();
  976. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  977. continue;
  978. }
  979. dict = parser.getObj();
  980. if (!(0, _primitives.isDict)(dict)) {
  981. continue;
  982. }
  983. if (dict.has('ID')) {
  984. return dict;
  985. }
  986. }
  987. if (dict) {
  988. return dict;
  989. }
  990. throw new _util.InvalidPDFException('Invalid PDF structure');
  991. },
  992. readXRef: function XRef_readXRef(recoveryMode) {
  993. var stream = this.stream;
  994. var startXRefParsedCache = Object.create(null);
  995. try {
  996. while (this.startXRefQueue.length) {
  997. var startXRef = this.startXRefQueue[0];
  998. if (startXRefParsedCache[startXRef]) {
  999. (0, _util.warn)('readXRef - skipping XRef table since it was already parsed.');
  1000. this.startXRefQueue.shift();
  1001. continue;
  1002. }
  1003. startXRefParsedCache[startXRef] = true;
  1004. stream.pos = startXRef + stream.start;
  1005. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
  1006. var obj = parser.getObj();
  1007. var dict;
  1008. if ((0, _primitives.isCmd)(obj, 'xref')) {
  1009. dict = this.processXRefTable(parser);
  1010. if (!this.topDict) {
  1011. this.topDict = dict;
  1012. }
  1013. obj = dict.get('XRefStm');
  1014. if ((0, _util.isInt)(obj)) {
  1015. var pos = obj;
  1016. if (!(pos in this.xrefstms)) {
  1017. this.xrefstms[pos] = 1;
  1018. this.startXRefQueue.push(pos);
  1019. }
  1020. }
  1021. } else if ((0, _util.isInt)(obj)) {
  1022. if (!(0, _util.isInt)(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), 'obj') || !(0, _primitives.isStream)(obj = parser.getObj())) {
  1023. throw new _util.FormatError('Invalid XRef stream');
  1024. }
  1025. dict = this.processXRefStream(obj);
  1026. if (!this.topDict) {
  1027. this.topDict = dict;
  1028. }
  1029. if (!dict) {
  1030. throw new _util.FormatError('Failed to read XRef stream');
  1031. }
  1032. } else {
  1033. throw new _util.FormatError('Invalid XRef stream header');
  1034. }
  1035. obj = dict.get('Prev');
  1036. if ((0, _util.isInt)(obj)) {
  1037. this.startXRefQueue.push(obj);
  1038. } else if ((0, _primitives.isRef)(obj)) {
  1039. this.startXRefQueue.push(obj.num);
  1040. }
  1041. this.startXRefQueue.shift();
  1042. }
  1043. return this.topDict;
  1044. } catch (e) {
  1045. if (e instanceof _util.MissingDataException) {
  1046. throw e;
  1047. }
  1048. (0, _util.info)('(while reading XRef): ' + e);
  1049. }
  1050. if (recoveryMode) {
  1051. return;
  1052. }
  1053. throw new _util.XRefParseException();
  1054. },
  1055. getEntry: function XRef_getEntry(i) {
  1056. var xrefEntry = this.entries[i];
  1057. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  1058. return xrefEntry;
  1059. }
  1060. return null;
  1061. },
  1062. fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
  1063. if (!(0, _primitives.isRef)(obj)) {
  1064. return obj;
  1065. }
  1066. return this.fetch(obj, suppressEncryption);
  1067. },
  1068. fetch: function XRef_fetch(ref, suppressEncryption) {
  1069. if (!(0, _primitives.isRef)(ref)) {
  1070. throw new Error('ref object is not a reference');
  1071. }
  1072. var num = ref.num;
  1073. if (num in this.cache) {
  1074. var cacheEntry = this.cache[num];
  1075. if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
  1076. cacheEntry.objId = ref.toString();
  1077. }
  1078. return cacheEntry;
  1079. }
  1080. var xrefEntry = this.getEntry(num);
  1081. if (xrefEntry === null) {
  1082. return this.cache[num] = null;
  1083. }
  1084. if (xrefEntry.uncompressed) {
  1085. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  1086. } else {
  1087. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  1088. }
  1089. if ((0, _primitives.isDict)(xrefEntry)) {
  1090. xrefEntry.objId = ref.toString();
  1091. } else if ((0, _primitives.isStream)(xrefEntry)) {
  1092. xrefEntry.dict.objId = ref.toString();
  1093. }
  1094. return xrefEntry;
  1095. },
  1096. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry, suppressEncryption) {
  1097. var gen = ref.gen;
  1098. var num = ref.num;
  1099. if (xrefEntry.gen !== gen) {
  1100. throw new _util.FormatError('inconsistent generation in XRef');
  1101. }
  1102. var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
  1103. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
  1104. var obj1 = parser.getObj();
  1105. var obj2 = parser.getObj();
  1106. var obj3 = parser.getObj();
  1107. if (!(0, _util.isInt)(obj1) || parseInt(obj1, 10) !== num || !(0, _util.isInt)(obj2) || parseInt(obj2, 10) !== gen || !(0, _primitives.isCmd)(obj3)) {
  1108. throw new _util.FormatError('bad XRef entry');
  1109. }
  1110. if (!(0, _primitives.isCmd)(obj3, 'obj')) {
  1111. if (obj3.cmd.indexOf('obj') === 0) {
  1112. num = parseInt(obj3.cmd.substring(3), 10);
  1113. if (!isNaN(num)) {
  1114. return num;
  1115. }
  1116. }
  1117. throw new _util.FormatError('bad XRef entry');
  1118. }
  1119. if (this.encrypt && !suppressEncryption) {
  1120. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  1121. } else {
  1122. xrefEntry = parser.getObj();
  1123. }
  1124. if (!(0, _primitives.isStream)(xrefEntry)) {
  1125. this.cache[num] = xrefEntry;
  1126. }
  1127. return xrefEntry;
  1128. },
  1129. fetchCompressed: function XRef_fetchCompressed(xrefEntry, suppressEncryption) {
  1130. var tableOffset = xrefEntry.offset;
  1131. var stream = this.fetch(new _primitives.Ref(tableOffset, 0));
  1132. if (!(0, _primitives.isStream)(stream)) {
  1133. throw new _util.FormatError('bad ObjStm stream');
  1134. }
  1135. var first = stream.dict.get('First');
  1136. var n = stream.dict.get('N');
  1137. if (!(0, _util.isInt)(first) || !(0, _util.isInt)(n)) {
  1138. throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
  1139. }
  1140. var parser = new _parser.Parser(new _parser.Lexer(stream), false, this);
  1141. parser.allowStreams = true;
  1142. var i,
  1143. entries = [],
  1144. num,
  1145. nums = [];
  1146. for (i = 0; i < n; ++i) {
  1147. num = parser.getObj();
  1148. if (!(0, _util.isInt)(num)) {
  1149. throw new _util.FormatError('invalid object number in the ObjStm stream: ' + num);
  1150. }
  1151. nums.push(num);
  1152. var offset = parser.getObj();
  1153. if (!(0, _util.isInt)(offset)) {
  1154. throw new _util.FormatError('invalid object offset in the ObjStm stream: ' + offset);
  1155. }
  1156. }
  1157. for (i = 0; i < n; ++i) {
  1158. entries.push(parser.getObj());
  1159. if ((0, _primitives.isCmd)(parser.buf1, 'endobj')) {
  1160. parser.shift();
  1161. }
  1162. num = nums[i];
  1163. var entry = this.entries[num];
  1164. if (entry && entry.offset === tableOffset && entry.gen === i) {
  1165. this.cache[num] = entries[i];
  1166. }
  1167. }
  1168. xrefEntry = entries[xrefEntry.gen];
  1169. if (xrefEntry === undefined) {
  1170. throw new _util.FormatError('bad XRef entry for compressed object');
  1171. }
  1172. return xrefEntry;
  1173. },
  1174. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj, suppressEncryption) {
  1175. if (!(0, _primitives.isRef)(obj)) {
  1176. return Promise.resolve(obj);
  1177. }
  1178. return this.fetchAsync(obj, suppressEncryption);
  1179. },
  1180. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  1181. var streamManager = this.stream.manager;
  1182. var xref = this;
  1183. return new Promise(function tryFetch(resolve, reject) {
  1184. try {
  1185. resolve(xref.fetch(ref, suppressEncryption));
  1186. } catch (e) {
  1187. if (e instanceof _util.MissingDataException) {
  1188. streamManager.requestRange(e.begin, e.end).then(function () {
  1189. tryFetch(resolve, reject);
  1190. }, reject);
  1191. return;
  1192. }
  1193. reject(e);
  1194. }
  1195. });
  1196. },
  1197. getCatalogObj: function XRef_getCatalogObj() {
  1198. return this.root;
  1199. }
  1200. };
  1201. return XRef;
  1202. }();
  1203. var NameOrNumberTree = function NameOrNumberTreeClosure() {
  1204. function NameOrNumberTree(root, xref) {
  1205. throw new Error('Cannot initialize NameOrNumberTree.');
  1206. }
  1207. NameOrNumberTree.prototype = {
  1208. getAll: function NameOrNumberTree_getAll() {
  1209. var dict = Object.create(null);
  1210. if (!this.root) {
  1211. return dict;
  1212. }
  1213. var xref = this.xref;
  1214. var processed = new _primitives.RefSet();
  1215. processed.put(this.root);
  1216. var queue = [this.root];
  1217. while (queue.length > 0) {
  1218. var i, n;
  1219. var obj = xref.fetchIfRef(queue.shift());
  1220. if (!(0, _primitives.isDict)(obj)) {
  1221. continue;
  1222. }
  1223. if (obj.has('Kids')) {
  1224. var kids = obj.get('Kids');
  1225. for (i = 0, n = kids.length; i < n; i++) {
  1226. var kid = kids[i];
  1227. if (processed.has(kid)) {
  1228. throw new _util.FormatError('Duplicate entry in "' + this._type + '" tree.');
  1229. }
  1230. queue.push(kid);
  1231. processed.put(kid);
  1232. }
  1233. continue;
  1234. }
  1235. var entries = obj.get(this._type);
  1236. if ((0, _util.isArray)(entries)) {
  1237. for (i = 0, n = entries.length; i < n; i += 2) {
  1238. dict[xref.fetchIfRef(entries[i])] = xref.fetchIfRef(entries[i + 1]);
  1239. }
  1240. }
  1241. }
  1242. return dict;
  1243. },
  1244. get: function NameOrNumberTree_get(key) {
  1245. if (!this.root) {
  1246. return null;
  1247. }
  1248. var xref = this.xref;
  1249. var kidsOrEntries = xref.fetchIfRef(this.root);
  1250. var loopCount = 0;
  1251. var MAX_LEVELS = 10;
  1252. var l, r, m;
  1253. while (kidsOrEntries.has('Kids')) {
  1254. if (++loopCount > MAX_LEVELS) {
  1255. (0, _util.warn)('Search depth limit reached for "' + this._type + '" tree.');
  1256. return null;
  1257. }
  1258. var kids = kidsOrEntries.get('Kids');
  1259. if (!(0, _util.isArray)(kids)) {
  1260. return null;
  1261. }
  1262. l = 0;
  1263. r = kids.length - 1;
  1264. while (l <= r) {
  1265. m = l + r >> 1;
  1266. var kid = xref.fetchIfRef(kids[m]);
  1267. var limits = kid.get('Limits');
  1268. if (key < xref.fetchIfRef(limits[0])) {
  1269. r = m - 1;
  1270. } else if (key > xref.fetchIfRef(limits[1])) {
  1271. l = m + 1;
  1272. } else {
  1273. kidsOrEntries = xref.fetchIfRef(kids[m]);
  1274. break;
  1275. }
  1276. }
  1277. if (l > r) {
  1278. return null;
  1279. }
  1280. }
  1281. var entries = kidsOrEntries.get(this._type);
  1282. if ((0, _util.isArray)(entries)) {
  1283. l = 0;
  1284. r = entries.length - 2;
  1285. while (l <= r) {
  1286. m = l + r & ~1;
  1287. var currentKey = xref.fetchIfRef(entries[m]);
  1288. if (key < currentKey) {
  1289. r = m - 2;
  1290. } else if (key > currentKey) {
  1291. l = m + 2;
  1292. } else {
  1293. return xref.fetchIfRef(entries[m + 1]);
  1294. }
  1295. }
  1296. }
  1297. return null;
  1298. }
  1299. };
  1300. return NameOrNumberTree;
  1301. }();
  1302. var NameTree = function NameTreeClosure() {
  1303. function NameTree(root, xref) {
  1304. this.root = root;
  1305. this.xref = xref;
  1306. this._type = 'Names';
  1307. }
  1308. _util.Util.inherit(NameTree, NameOrNumberTree, {});
  1309. return NameTree;
  1310. }();
  1311. var NumberTree = function NumberTreeClosure() {
  1312. function NumberTree(root, xref) {
  1313. this.root = root;
  1314. this.xref = xref;
  1315. this._type = 'Nums';
  1316. }
  1317. _util.Util.inherit(NumberTree, NameOrNumberTree, {});
  1318. return NumberTree;
  1319. }();
  1320. var FileSpec = function FileSpecClosure() {
  1321. function FileSpec(root, xref) {
  1322. if (!root || !(0, _primitives.isDict)(root)) {
  1323. return;
  1324. }
  1325. this.xref = xref;
  1326. this.root = root;
  1327. if (root.has('FS')) {
  1328. this.fs = root.get('FS');
  1329. }
  1330. this.description = root.has('Desc') ? (0, _util.stringToPDFString)(root.get('Desc')) : '';
  1331. if (root.has('RF')) {
  1332. (0, _util.warn)('Related file specifications are not supported');
  1333. }
  1334. this.contentAvailable = true;
  1335. if (!root.has('EF')) {
  1336. this.contentAvailable = false;
  1337. (0, _util.warn)('Non-embedded file specifications are not supported');
  1338. }
  1339. }
  1340. function pickPlatformItem(dict) {
  1341. if (dict.has('UF')) {
  1342. return dict.get('UF');
  1343. } else if (dict.has('F')) {
  1344. return dict.get('F');
  1345. } else if (dict.has('Unix')) {
  1346. return dict.get('Unix');
  1347. } else if (dict.has('Mac')) {
  1348. return dict.get('Mac');
  1349. } else if (dict.has('DOS')) {
  1350. return dict.get('DOS');
  1351. }
  1352. return null;
  1353. }
  1354. FileSpec.prototype = {
  1355. get filename() {
  1356. if (!this._filename && this.root) {
  1357. var filename = pickPlatformItem(this.root) || 'unnamed';
  1358. this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
  1359. }
  1360. return this._filename;
  1361. },
  1362. get content() {
  1363. if (!this.contentAvailable) {
  1364. return null;
  1365. }
  1366. if (!this.contentRef && this.root) {
  1367. this.contentRef = pickPlatformItem(this.root.get('EF'));
  1368. }
  1369. var content = null;
  1370. if (this.contentRef) {
  1371. var xref = this.xref;
  1372. var fileObj = xref.fetchIfRef(this.contentRef);
  1373. if (fileObj && (0, _primitives.isStream)(fileObj)) {
  1374. content = fileObj.getBytes();
  1375. } else {
  1376. (0, _util.warn)('Embedded file specification points to non-existing/invalid ' + 'content');
  1377. }
  1378. } else {
  1379. (0, _util.warn)('Embedded file specification does not have a content');
  1380. }
  1381. return content;
  1382. },
  1383. get serializable() {
  1384. return {
  1385. filename: this.filename,
  1386. content: this.content
  1387. };
  1388. }
  1389. };
  1390. return FileSpec;
  1391. }();
  1392. var ObjectLoader = function () {
  1393. function mayHaveChildren(value) {
  1394. return (0, _primitives.isRef)(value) || (0, _primitives.isDict)(value) || (0, _util.isArray)(value) || (0, _primitives.isStream)(value);
  1395. }
  1396. function addChildren(node, nodesToVisit) {
  1397. if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
  1398. var dict = (0, _primitives.isDict)(node) ? node : node.dict;
  1399. var dictKeys = dict.getKeys();
  1400. for (var i = 0, ii = dictKeys.length; i < ii; i++) {
  1401. var rawValue = dict.getRaw(dictKeys[i]);
  1402. if (mayHaveChildren(rawValue)) {
  1403. nodesToVisit.push(rawValue);
  1404. }
  1405. }
  1406. } else if ((0, _util.isArray)(node)) {
  1407. for (var _i = 0, _ii = node.length; _i < _ii; _i++) {
  1408. var value = node[_i];
  1409. if (mayHaveChildren(value)) {
  1410. nodesToVisit.push(value);
  1411. }
  1412. }
  1413. }
  1414. }
  1415. function ObjectLoader(dict, keys, xref) {
  1416. this.dict = dict;
  1417. this.keys = keys;
  1418. this.xref = xref;
  1419. this.refSet = null;
  1420. this.capability = null;
  1421. }
  1422. ObjectLoader.prototype = {
  1423. load: function load() {
  1424. this.capability = (0, _util.createPromiseCapability)();
  1425. if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
  1426. this.capability.resolve();
  1427. return this.capability.promise;
  1428. }
  1429. var keys = this.keys,
  1430. dict = this.dict;
  1431. this.refSet = new _primitives.RefSet();
  1432. var nodesToVisit = [];
  1433. for (var i = 0, ii = keys.length; i < ii; i++) {
  1434. var rawValue = dict.getRaw(keys[i]);
  1435. if (rawValue !== undefined) {
  1436. nodesToVisit.push(rawValue);
  1437. }
  1438. }
  1439. this._walk(nodesToVisit);
  1440. return this.capability.promise;
  1441. },
  1442. _walk: function _walk(nodesToVisit) {
  1443. var _this3 = this;
  1444. var nodesToRevisit = [];
  1445. var pendingRequests = [];
  1446. while (nodesToVisit.length) {
  1447. var currentNode = nodesToVisit.pop();
  1448. if ((0, _primitives.isRef)(currentNode)) {
  1449. if (this.refSet.has(currentNode)) {
  1450. continue;
  1451. }
  1452. try {
  1453. this.refSet.put(currentNode);
  1454. currentNode = this.xref.fetch(currentNode);
  1455. } catch (ex) {
  1456. if (!(ex instanceof _util.MissingDataException)) {
  1457. throw ex;
  1458. }
  1459. nodesToRevisit.push(currentNode);
  1460. pendingRequests.push({
  1461. begin: ex.begin,
  1462. end: ex.end
  1463. });
  1464. }
  1465. }
  1466. if (currentNode && currentNode.getBaseStreams) {
  1467. var baseStreams = currentNode.getBaseStreams();
  1468. var foundMissingData = false;
  1469. for (var i = 0, ii = baseStreams.length; i < ii; i++) {
  1470. var stream = baseStreams[i];
  1471. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  1472. foundMissingData = true;
  1473. pendingRequests.push({
  1474. begin: stream.start,
  1475. end: stream.end
  1476. });
  1477. }
  1478. }
  1479. if (foundMissingData) {
  1480. nodesToRevisit.push(currentNode);
  1481. }
  1482. }
  1483. addChildren(currentNode, nodesToVisit);
  1484. }
  1485. if (pendingRequests.length) {
  1486. this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
  1487. for (var _i2 = 0, _ii2 = nodesToRevisit.length; _i2 < _ii2; _i2++) {
  1488. var node = nodesToRevisit[_i2];
  1489. if ((0, _primitives.isRef)(node)) {
  1490. _this3.refSet.remove(node);
  1491. }
  1492. }
  1493. _this3._walk(nodesToRevisit);
  1494. }, this.capability.reject);
  1495. return;
  1496. }
  1497. this.refSet = null;
  1498. this.capability.resolve();
  1499. }
  1500. };
  1501. return ObjectLoader;
  1502. }();
  1503. exports.Catalog = Catalog;
  1504. exports.ObjectLoader = ObjectLoader;
  1505. exports.XRef = XRef;
  1506. exports.FileSpec = FileSpec;