2
0

obj.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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. if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
  1331. var dict = (0, _primitives.isDict)(node) ? node : node.dict;
  1332. var dictKeys = dict.getKeys();
  1333. for (var i = 0, ii = dictKeys.length; i < ii; i++) {
  1334. var rawValue = dict.getRaw(dictKeys[i]);
  1335. if (mayHaveChildren(rawValue)) {
  1336. nodesToVisit.push(rawValue);
  1337. }
  1338. }
  1339. } else if ((0, _util.isArray)(node)) {
  1340. for (var _i = 0, _ii = node.length; _i < _ii; _i++) {
  1341. var value = node[_i];
  1342. if (mayHaveChildren(value)) {
  1343. nodesToVisit.push(value);
  1344. }
  1345. }
  1346. }
  1347. }
  1348. function ObjectLoader(dict, keys, xref) {
  1349. this.dict = dict;
  1350. this.keys = keys;
  1351. this.xref = xref;
  1352. this.refSet = null;
  1353. this.capability = null;
  1354. }
  1355. ObjectLoader.prototype = {
  1356. load: function load() {
  1357. this.capability = (0, _util.createPromiseCapability)();
  1358. if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
  1359. this.capability.resolve();
  1360. return this.capability.promise;
  1361. }
  1362. var keys = this.keys,
  1363. dict = this.dict;
  1364. this.refSet = new _primitives.RefSet();
  1365. var nodesToVisit = [];
  1366. for (var i = 0, ii = keys.length; i < ii; i++) {
  1367. var rawValue = dict.getRaw(keys[i]);
  1368. if (rawValue !== undefined) {
  1369. nodesToVisit.push(rawValue);
  1370. }
  1371. }
  1372. this._walk(nodesToVisit);
  1373. return this.capability.promise;
  1374. },
  1375. _walk: function _walk(nodesToVisit) {
  1376. var _this3 = this;
  1377. var nodesToRevisit = [];
  1378. var pendingRequests = [];
  1379. while (nodesToVisit.length) {
  1380. var currentNode = nodesToVisit.pop();
  1381. if ((0, _primitives.isRef)(currentNode)) {
  1382. if (this.refSet.has(currentNode)) {
  1383. continue;
  1384. }
  1385. try {
  1386. this.refSet.put(currentNode);
  1387. currentNode = this.xref.fetch(currentNode);
  1388. } catch (ex) {
  1389. if (!(ex instanceof _util.MissingDataException)) {
  1390. throw ex;
  1391. }
  1392. nodesToRevisit.push(currentNode);
  1393. pendingRequests.push({
  1394. begin: ex.begin,
  1395. end: ex.end
  1396. });
  1397. }
  1398. }
  1399. if (currentNode && currentNode.getBaseStreams) {
  1400. var baseStreams = currentNode.getBaseStreams();
  1401. var foundMissingData = false;
  1402. for (var i = 0, ii = baseStreams.length; i < ii; i++) {
  1403. var stream = baseStreams[i];
  1404. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  1405. foundMissingData = true;
  1406. pendingRequests.push({
  1407. begin: stream.start,
  1408. end: stream.end
  1409. });
  1410. }
  1411. }
  1412. if (foundMissingData) {
  1413. nodesToRevisit.push(currentNode);
  1414. }
  1415. }
  1416. addChildren(currentNode, nodesToVisit);
  1417. }
  1418. if (pendingRequests.length) {
  1419. this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
  1420. for (var _i2 = 0, _ii2 = nodesToRevisit.length; _i2 < _ii2; _i2++) {
  1421. var node = nodesToRevisit[_i2];
  1422. if ((0, _primitives.isRef)(node)) {
  1423. _this3.refSet.remove(node);
  1424. }
  1425. }
  1426. _this3._walk(nodesToRevisit);
  1427. }, this.capability.reject);
  1428. return;
  1429. }
  1430. this.refSet = null;
  1431. this.capability.resolve();
  1432. }
  1433. };
  1434. return ObjectLoader;
  1435. }();
  1436. exports.Catalog = Catalog;
  1437. exports.ObjectLoader = ObjectLoader;
  1438. exports.XRef = XRef;
  1439. exports.FileSpec = FileSpec;