obj.js 54 KB

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