obj.js 51 KB

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