obj.js 51 KB

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