obj.js 52 KB

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