obj.js 50 KB

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