obj.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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. var objId = currentNode.objId;
  468. if (objId && !pageKidsCountCache.has(objId)) {
  469. pageKidsCountCache.put(objId, count);
  470. }
  471. if (currentPageIndex + count <= pageIndex) {
  472. currentPageIndex += count;
  473. continue;
  474. }
  475. var kids = currentNode.get('Kids');
  476. if (!Array.isArray(kids)) {
  477. capability.reject(new _util.FormatError('page dictionary kids object is not an array'));
  478. return;
  479. }
  480. for (var last = kids.length - 1; last >= 0; last--) {
  481. nodesToVisit.push(kids[last]);
  482. }
  483. }
  484. capability.reject(new Error('Page index ' + pageIndex + ' not found.'));
  485. }
  486. next();
  487. return capability.promise;
  488. },
  489. getPageIndex: function Catalog_getPageIndex(pageRef) {
  490. var xref = this.xref;
  491. function pagesBeforeRef(kidRef) {
  492. var total = 0;
  493. var parentRef;
  494. return xref.fetchAsync(kidRef).then(function (node) {
  495. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, 'Page') && !((0, _primitives.isDict)(node) && !node.has('Type') && node.has('Contents'))) {
  496. throw new _util.FormatError('The reference does not point to a /Page Dict.');
  497. }
  498. if (!node) {
  499. return null;
  500. }
  501. if (!(0, _primitives.isDict)(node)) {
  502. throw new _util.FormatError('node must be a Dict.');
  503. }
  504. parentRef = node.getRaw('Parent');
  505. return node.getAsync('Parent');
  506. }).then(function (parent) {
  507. if (!parent) {
  508. return null;
  509. }
  510. if (!(0, _primitives.isDict)(parent)) {
  511. throw new _util.FormatError('parent must be a Dict.');
  512. }
  513. return parent.getAsync('Kids');
  514. }).then(function (kids) {
  515. if (!kids) {
  516. return null;
  517. }
  518. var kidPromises = [];
  519. var found = false;
  520. for (var i = 0; i < kids.length; i++) {
  521. var kid = kids[i];
  522. if (!(0, _primitives.isRef)(kid)) {
  523. throw new _util.FormatError('kid must be a Ref.');
  524. }
  525. if (kid.num === kidRef.num) {
  526. found = true;
  527. break;
  528. }
  529. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  530. if (kid.has('Count')) {
  531. var count = kid.get('Count');
  532. total += count;
  533. } else {
  534. total++;
  535. }
  536. }));
  537. }
  538. if (!found) {
  539. throw new _util.FormatError('kid ref not found in parents kids');
  540. }
  541. return Promise.all(kidPromises).then(function () {
  542. return [total, parentRef];
  543. });
  544. });
  545. }
  546. var total = 0;
  547. function next(ref) {
  548. return pagesBeforeRef(ref).then(function (args) {
  549. if (!args) {
  550. return total;
  551. }
  552. var count = args[0];
  553. var parentRef = args[1];
  554. total += count;
  555. return next(parentRef);
  556. });
  557. }
  558. return next(pageRef);
  559. }
  560. };
  561. Catalog.parseDestDictionary = function Catalog_parseDestDictionary(params) {
  562. function addDefaultProtocolToUrl(url) {
  563. if (url.indexOf('www.') === 0) {
  564. return 'http://' + url;
  565. }
  566. return url;
  567. }
  568. function tryConvertUrlEncoding(url) {
  569. try {
  570. return (0, _util.stringToUTF8String)(url);
  571. } catch (e) {
  572. return url;
  573. }
  574. }
  575. var destDict = params.destDict;
  576. if (!(0, _primitives.isDict)(destDict)) {
  577. (0, _util.warn)('parseDestDictionary: "destDict" must be a dictionary.');
  578. return;
  579. }
  580. var resultObj = params.resultObj;
  581. if ((typeof resultObj === 'undefined' ? 'undefined' : _typeof(resultObj)) !== 'object') {
  582. (0, _util.warn)('parseDestDictionary: "resultObj" must be an object.');
  583. return;
  584. }
  585. var docBaseUrl = params.docBaseUrl || null;
  586. var action = destDict.get('A'),
  587. url,
  588. dest;
  589. if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
  590. action = destDict.get('Dest');
  591. }
  592. if ((0, _primitives.isDict)(action)) {
  593. var actionType = action.get('S');
  594. if (!(0, _primitives.isName)(actionType)) {
  595. (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
  596. return;
  597. }
  598. var actionName = actionType.name;
  599. switch (actionName) {
  600. case 'URI':
  601. url = action.get('URI');
  602. if ((0, _primitives.isName)(url)) {
  603. url = '/' + url.name;
  604. } else if ((0, _util.isString)(url)) {
  605. url = addDefaultProtocolToUrl(url);
  606. }
  607. break;
  608. case 'GoTo':
  609. dest = action.get('D');
  610. break;
  611. case 'Launch':
  612. case 'GoToR':
  613. var urlDict = action.get('F');
  614. if ((0, _primitives.isDict)(urlDict)) {
  615. url = urlDict.get('F') || null;
  616. } else if ((0, _util.isString)(urlDict)) {
  617. url = urlDict;
  618. }
  619. var remoteDest = action.get('D');
  620. if (remoteDest) {
  621. if ((0, _primitives.isName)(remoteDest)) {
  622. remoteDest = remoteDest.name;
  623. }
  624. if ((0, _util.isString)(url)) {
  625. var baseUrl = url.split('#')[0];
  626. if ((0, _util.isString)(remoteDest)) {
  627. url = baseUrl + '#' + remoteDest;
  628. } else if (Array.isArray(remoteDest)) {
  629. url = baseUrl + '#' + JSON.stringify(remoteDest);
  630. }
  631. }
  632. }
  633. var newWindow = action.get('NewWindow');
  634. if ((0, _util.isBool)(newWindow)) {
  635. resultObj.newWindow = newWindow;
  636. }
  637. break;
  638. case 'Named':
  639. var namedAction = action.get('N');
  640. if ((0, _primitives.isName)(namedAction)) {
  641. resultObj.action = namedAction.name;
  642. }
  643. break;
  644. case 'JavaScript':
  645. var jsAction = action.get('JS'),
  646. js;
  647. if ((0, _primitives.isStream)(jsAction)) {
  648. js = (0, _util.bytesToString)(jsAction.getBytes());
  649. } else if ((0, _util.isString)(jsAction)) {
  650. js = jsAction;
  651. }
  652. if (js) {
  653. var URL_OPEN_METHODS = ['app.launchURL', 'window.open'];
  654. var regex = new RegExp('^\\s*(' + URL_OPEN_METHODS.join('|').split('.').join('\\.') + ')\\((?:\'|\")([^\'\"]*)(?:\'|\")(?:,\\s*(\\w+)\\)|\\))', 'i');
  655. var jsUrl = regex.exec((0, _util.stringToPDFString)(js));
  656. if (jsUrl && jsUrl[2]) {
  657. url = jsUrl[2];
  658. if (jsUrl[3] === 'true' && jsUrl[1] === 'app.launchURL') {
  659. resultObj.newWindow = true;
  660. }
  661. break;
  662. }
  663. }
  664. default:
  665. (0, _util.warn)('parseDestDictionary: Unsupported Action type "' + actionName + '".');
  666. break;
  667. }
  668. } else if (destDict.has('Dest')) {
  669. dest = destDict.get('Dest');
  670. }
  671. if ((0, _util.isString)(url)) {
  672. url = tryConvertUrlEncoding(url);
  673. var absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
  674. if (absoluteUrl) {
  675. resultObj.url = absoluteUrl.href;
  676. }
  677. resultObj.unsafeUrl = url;
  678. }
  679. if (dest) {
  680. if ((0, _primitives.isName)(dest)) {
  681. dest = dest.name;
  682. }
  683. if ((0, _util.isString)(dest) || Array.isArray(dest)) {
  684. resultObj.dest = dest;
  685. }
  686. }
  687. };
  688. return Catalog;
  689. }();
  690. var XRef = function XRefClosure() {
  691. function XRef(stream, pdfManager) {
  692. this.stream = stream;
  693. this.pdfManager = pdfManager;
  694. this.entries = [];
  695. this.xrefstms = Object.create(null);
  696. this.cache = [];
  697. this.stats = {
  698. streamTypes: [],
  699. fontTypes: []
  700. };
  701. }
  702. XRef.prototype = {
  703. setStartXRef: function XRef_setStartXRef(startXRef) {
  704. this.startXRefQueue = [startXRef];
  705. },
  706. parse: function XRef_parse(recoveryMode) {
  707. var trailerDict;
  708. if (!recoveryMode) {
  709. trailerDict = this.readXRef();
  710. } else {
  711. (0, _util.warn)('Indexing all PDF objects');
  712. trailerDict = this.indexObjects();
  713. }
  714. trailerDict.assignXref(this);
  715. this.trailer = trailerDict;
  716. var encrypt = trailerDict.get('Encrypt');
  717. if ((0, _primitives.isDict)(encrypt)) {
  718. var ids = trailerDict.get('ID');
  719. var fileId = ids && ids.length ? ids[0] : '';
  720. encrypt.suppressEncryption = true;
  721. this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
  722. }
  723. if (!(this.root = trailerDict.get('Root'))) {
  724. throw new _util.FormatError('Invalid root reference');
  725. }
  726. },
  727. processXRefTable: function XRef_processXRefTable(parser) {
  728. if (!('tableState' in this)) {
  729. this.tableState = {
  730. entryNum: 0,
  731. streamPos: parser.lexer.stream.pos,
  732. parserBuf1: parser.buf1,
  733. parserBuf2: parser.buf2
  734. };
  735. }
  736. var obj = this.readXRefTable(parser);
  737. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  738. throw new _util.FormatError('Invalid XRef table: could not find trailer dictionary');
  739. }
  740. var dict = parser.getObj();
  741. if (!(0, _primitives.isDict)(dict) && dict.dict) {
  742. dict = dict.dict;
  743. }
  744. if (!(0, _primitives.isDict)(dict)) {
  745. throw new _util.FormatError('Invalid XRef table: could not parse trailer dictionary');
  746. }
  747. delete this.tableState;
  748. return dict;
  749. },
  750. readXRefTable: function XRef_readXRefTable(parser) {
  751. var stream = parser.lexer.stream;
  752. var tableState = this.tableState;
  753. stream.pos = tableState.streamPos;
  754. parser.buf1 = tableState.parserBuf1;
  755. parser.buf2 = tableState.parserBuf2;
  756. var obj;
  757. while (true) {
  758. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  759. if ((0, _primitives.isCmd)(obj = parser.getObj(), 'trailer')) {
  760. break;
  761. }
  762. tableState.firstEntryNum = obj;
  763. tableState.entryCount = parser.getObj();
  764. }
  765. var first = tableState.firstEntryNum;
  766. var count = tableState.entryCount;
  767. if (!Number.isInteger(first) || !Number.isInteger(count)) {
  768. throw new _util.FormatError('Invalid XRef table: wrong types in subsection header');
  769. }
  770. for (var i = tableState.entryNum; i < count; i++) {
  771. tableState.streamPos = stream.pos;
  772. tableState.entryNum = i;
  773. tableState.parserBuf1 = parser.buf1;
  774. tableState.parserBuf2 = parser.buf2;
  775. var entry = {};
  776. entry.offset = parser.getObj();
  777. entry.gen = parser.getObj();
  778. var type = parser.getObj();
  779. if ((0, _primitives.isCmd)(type, 'f')) {
  780. entry.free = true;
  781. } else if ((0, _primitives.isCmd)(type, 'n')) {
  782. entry.uncompressed = true;
  783. }
  784. if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
  785. throw new _util.FormatError('Invalid entry in XRef subsection: ' + first + ', ' + count);
  786. }
  787. if (i === 0 && entry.free && first === 1) {
  788. first = 0;
  789. }
  790. if (!this.entries[i + first]) {
  791. this.entries[i + first] = entry;
  792. }
  793. }
  794. tableState.entryNum = 0;
  795. tableState.streamPos = stream.pos;
  796. tableState.parserBuf1 = parser.buf1;
  797. tableState.parserBuf2 = parser.buf2;
  798. delete tableState.firstEntryNum;
  799. delete tableState.entryCount;
  800. }
  801. if (this.entries[0] && !this.entries[0].free) {
  802. throw new _util.FormatError('Invalid XRef table: unexpected first object');
  803. }
  804. return obj;
  805. },
  806. processXRefStream: function XRef_processXRefStream(stream) {
  807. if (!('streamState' in this)) {
  808. var streamParameters = stream.dict;
  809. var byteWidths = streamParameters.get('W');
  810. var range = streamParameters.get('Index');
  811. if (!range) {
  812. range = [0, streamParameters.get('Size')];
  813. }
  814. this.streamState = {
  815. entryRanges: range,
  816. byteWidths: byteWidths,
  817. entryNum: 0,
  818. streamPos: stream.pos
  819. };
  820. }
  821. this.readXRefStream(stream);
  822. delete this.streamState;
  823. return stream.dict;
  824. },
  825. readXRefStream: function XRef_readXRefStream(stream) {
  826. var i, j;
  827. var streamState = this.streamState;
  828. stream.pos = streamState.streamPos;
  829. var byteWidths = streamState.byteWidths;
  830. var typeFieldWidth = byteWidths[0];
  831. var offsetFieldWidth = byteWidths[1];
  832. var generationFieldWidth = byteWidths[2];
  833. var entryRanges = streamState.entryRanges;
  834. while (entryRanges.length > 0) {
  835. var first = entryRanges[0];
  836. var n = entryRanges[1];
  837. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  838. throw new _util.FormatError('Invalid XRef range fields: ' + first + ', ' + n);
  839. }
  840. if (!Number.isInteger(typeFieldWidth) || !Number.isInteger(offsetFieldWidth) || !Number.isInteger(generationFieldWidth)) {
  841. throw new _util.FormatError('Invalid XRef entry fields length: ' + first + ', ' + n);
  842. }
  843. for (i = streamState.entryNum; i < n; ++i) {
  844. streamState.entryNum = i;
  845. streamState.streamPos = stream.pos;
  846. var type = 0,
  847. offset = 0,
  848. generation = 0;
  849. for (j = 0; j < typeFieldWidth; ++j) {
  850. type = type << 8 | stream.getByte();
  851. }
  852. if (typeFieldWidth === 0) {
  853. type = 1;
  854. }
  855. for (j = 0; j < offsetFieldWidth; ++j) {
  856. offset = offset << 8 | stream.getByte();
  857. }
  858. for (j = 0; j < generationFieldWidth; ++j) {
  859. generation = generation << 8 | stream.getByte();
  860. }
  861. var entry = {};
  862. entry.offset = offset;
  863. entry.gen = generation;
  864. switch (type) {
  865. case 0:
  866. entry.free = true;
  867. break;
  868. case 1:
  869. entry.uncompressed = true;
  870. break;
  871. case 2:
  872. break;
  873. default:
  874. throw new _util.FormatError('Invalid XRef entry type: ' + type);
  875. }
  876. if (!this.entries[first + i]) {
  877. this.entries[first + i] = entry;
  878. }
  879. }
  880. streamState.entryNum = 0;
  881. streamState.streamPos = stream.pos;
  882. entryRanges.splice(0, 2);
  883. }
  884. },
  885. indexObjects: function XRef_indexObjects() {
  886. var TAB = 0x9,
  887. LF = 0xA,
  888. CR = 0xD,
  889. SPACE = 0x20;
  890. var PERCENT = 0x25,
  891. LT = 0x3C;
  892. function readToken(data, offset) {
  893. var token = '',
  894. ch = data[offset];
  895. while (ch !== LF && ch !== CR && ch !== LT) {
  896. if (++offset >= data.length) {
  897. break;
  898. }
  899. token += String.fromCharCode(ch);
  900. ch = data[offset];
  901. }
  902. return token;
  903. }
  904. function skipUntil(data, offset, what) {
  905. var length = what.length,
  906. dataLength = data.length;
  907. var skipped = 0;
  908. while (offset < dataLength) {
  909. var i = 0;
  910. while (i < length && data[offset + i] === what[i]) {
  911. ++i;
  912. }
  913. if (i >= length) {
  914. break;
  915. }
  916. offset++;
  917. skipped++;
  918. }
  919. return skipped;
  920. }
  921. var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
  922. var endobjRegExp = /\bendobj[\b\s]$/;
  923. var nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s])$/;
  924. var CHECK_CONTENT_LENGTH = 25;
  925. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  926. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
  927. var objBytes = new Uint8Array([111, 98, 106]);
  928. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  929. this.entries.length = 0;
  930. var stream = this.stream;
  931. stream.pos = 0;
  932. var buffer = stream.getBytes();
  933. var position = stream.start,
  934. length = buffer.length;
  935. var trailers = [],
  936. xrefStms = [];
  937. while (position < length) {
  938. var ch = buffer[position];
  939. if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
  940. ++position;
  941. continue;
  942. }
  943. if (ch === PERCENT) {
  944. do {
  945. ++position;
  946. if (position >= length) {
  947. break;
  948. }
  949. ch = buffer[position];
  950. } while (ch !== LF && ch !== CR);
  951. continue;
  952. }
  953. var token = readToken(buffer, position);
  954. var m;
  955. if (token.indexOf('xref') === 0 && (token.length === 4 || /\s/.test(token[4]))) {
  956. position += skipUntil(buffer, position, trailerBytes);
  957. trailers.push(position);
  958. position += skipUntil(buffer, position, startxrefBytes);
  959. } else if (m = objRegExp.exec(token)) {
  960. if (typeof this.entries[m[1]] === 'undefined') {
  961. this.entries[m[1]] = {
  962. offset: position - stream.start,
  963. gen: m[2] | 0,
  964. uncompressed: true
  965. };
  966. }
  967. var contentLength = void 0,
  968. startPos = position + token.length;
  969. while (startPos < buffer.length) {
  970. var endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
  971. contentLength = endPos - position;
  972. var checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
  973. var tokenStr = (0, _util.bytesToString)(buffer.subarray(checkPos, endPos));
  974. if (endobjRegExp.test(tokenStr)) {
  975. break;
  976. } else {
  977. var objToken = nestedObjRegExp.exec(tokenStr);
  978. if (objToken && objToken[1]) {
  979. (0, _util.warn)('indexObjects: Found new "obj" inside of another "obj", ' + 'caused by missing "endobj" -- trying to recover.');
  980. contentLength -= objToken[1].length;
  981. break;
  982. }
  983. }
  984. startPos += contentLength;
  985. }
  986. var content = buffer.subarray(position, position + contentLength);
  987. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  988. if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
  989. xrefStms.push(position - stream.start);
  990. this.xrefstms[position - stream.start] = 1;
  991. }
  992. position += contentLength;
  993. } else if (token.indexOf('trailer') === 0 && (token.length === 7 || /\s/.test(token[7]))) {
  994. trailers.push(position);
  995. position += skipUntil(buffer, position, startxrefBytes);
  996. } else {
  997. position += token.length + 1;
  998. }
  999. }
  1000. var i, ii;
  1001. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  1002. this.startXRefQueue.push(xrefStms[i]);
  1003. this.readXRef(true);
  1004. }
  1005. var dict;
  1006. for (i = 0, ii = trailers.length; i < ii; ++i) {
  1007. stream.pos = trailers[i];
  1008. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this, true);
  1009. var obj = parser.getObj();
  1010. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  1011. continue;
  1012. }
  1013. dict = parser.getObj();
  1014. if (!(0, _primitives.isDict)(dict)) {
  1015. continue;
  1016. }
  1017. if (dict.has('ID')) {
  1018. return dict;
  1019. }
  1020. }
  1021. if (dict) {
  1022. return dict;
  1023. }
  1024. throw new _util.InvalidPDFException('Invalid PDF structure');
  1025. },
  1026. readXRef: function XRef_readXRef(recoveryMode) {
  1027. var stream = this.stream;
  1028. var startXRefParsedCache = Object.create(null);
  1029. try {
  1030. while (this.startXRefQueue.length) {
  1031. var startXRef = this.startXRefQueue[0];
  1032. if (startXRefParsedCache[startXRef]) {
  1033. (0, _util.warn)('readXRef - skipping XRef table since it was already parsed.');
  1034. this.startXRefQueue.shift();
  1035. continue;
  1036. }
  1037. startXRefParsedCache[startXRef] = true;
  1038. stream.pos = startXRef + stream.start;
  1039. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
  1040. var obj = parser.getObj();
  1041. var dict;
  1042. if ((0, _primitives.isCmd)(obj, 'xref')) {
  1043. dict = this.processXRefTable(parser);
  1044. if (!this.topDict) {
  1045. this.topDict = dict;
  1046. }
  1047. obj = dict.get('XRefStm');
  1048. if (Number.isInteger(obj)) {
  1049. var pos = obj;
  1050. if (!(pos in this.xrefstms)) {
  1051. this.xrefstms[pos] = 1;
  1052. this.startXRefQueue.push(pos);
  1053. }
  1054. }
  1055. } else if (Number.isInteger(obj)) {
  1056. if (!Number.isInteger(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), 'obj') || !(0, _primitives.isStream)(obj = parser.getObj())) {
  1057. throw new _util.FormatError('Invalid XRef stream');
  1058. }
  1059. dict = this.processXRefStream(obj);
  1060. if (!this.topDict) {
  1061. this.topDict = dict;
  1062. }
  1063. if (!dict) {
  1064. throw new _util.FormatError('Failed to read XRef stream');
  1065. }
  1066. } else {
  1067. throw new _util.FormatError('Invalid XRef stream header');
  1068. }
  1069. obj = dict.get('Prev');
  1070. if (Number.isInteger(obj)) {
  1071. this.startXRefQueue.push(obj);
  1072. } else if ((0, _primitives.isRef)(obj)) {
  1073. this.startXRefQueue.push(obj.num);
  1074. }
  1075. this.startXRefQueue.shift();
  1076. }
  1077. return this.topDict;
  1078. } catch (e) {
  1079. if (e instanceof _util.MissingDataException) {
  1080. throw e;
  1081. }
  1082. (0, _util.info)('(while reading XRef): ' + e);
  1083. }
  1084. if (recoveryMode) {
  1085. return;
  1086. }
  1087. throw new _util.XRefParseException();
  1088. },
  1089. getEntry: function XRef_getEntry(i) {
  1090. var xrefEntry = this.entries[i];
  1091. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  1092. return xrefEntry;
  1093. }
  1094. return null;
  1095. },
  1096. fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
  1097. if (!(0, _primitives.isRef)(obj)) {
  1098. return obj;
  1099. }
  1100. return this.fetch(obj, suppressEncryption);
  1101. },
  1102. fetch: function XRef_fetch(ref, suppressEncryption) {
  1103. if (!(0, _primitives.isRef)(ref)) {
  1104. throw new Error('ref object is not a reference');
  1105. }
  1106. var num = ref.num;
  1107. if (num in this.cache) {
  1108. var cacheEntry = this.cache[num];
  1109. if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
  1110. cacheEntry.objId = ref.toString();
  1111. }
  1112. return cacheEntry;
  1113. }
  1114. var xrefEntry = this.getEntry(num);
  1115. if (xrefEntry === null) {
  1116. return this.cache[num] = null;
  1117. }
  1118. if (xrefEntry.uncompressed) {
  1119. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  1120. } else {
  1121. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  1122. }
  1123. if ((0, _primitives.isDict)(xrefEntry)) {
  1124. xrefEntry.objId = ref.toString();
  1125. } else if ((0, _primitives.isStream)(xrefEntry)) {
  1126. xrefEntry.dict.objId = ref.toString();
  1127. }
  1128. return xrefEntry;
  1129. },
  1130. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry, suppressEncryption) {
  1131. var gen = ref.gen;
  1132. var num = ref.num;
  1133. if (xrefEntry.gen !== gen) {
  1134. throw new _util.FormatError('inconsistent generation in XRef');
  1135. }
  1136. var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
  1137. var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
  1138. var obj1 = parser.getObj();
  1139. var obj2 = parser.getObj();
  1140. var obj3 = parser.getObj();
  1141. if (!Number.isInteger(obj1)) {
  1142. obj1 = parseInt(obj1, 10);
  1143. }
  1144. if (!Number.isInteger(obj2)) {
  1145. obj2 = parseInt(obj2, 10);
  1146. }
  1147. if (obj1 !== num || obj2 !== gen || !(0, _primitives.isCmd)(obj3)) {
  1148. throw new _util.FormatError('bad XRef entry');
  1149. }
  1150. if (obj3.cmd !== 'obj') {
  1151. if (obj3.cmd.indexOf('obj') === 0) {
  1152. num = parseInt(obj3.cmd.substring(3), 10);
  1153. if (!Number.isNaN(num)) {
  1154. return num;
  1155. }
  1156. }
  1157. throw new _util.FormatError('bad XRef entry');
  1158. }
  1159. if (this.encrypt && !suppressEncryption) {
  1160. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  1161. } else {
  1162. xrefEntry = parser.getObj();
  1163. }
  1164. if (!(0, _primitives.isStream)(xrefEntry)) {
  1165. this.cache[num] = xrefEntry;
  1166. }
  1167. return xrefEntry;
  1168. },
  1169. fetchCompressed: function XRef_fetchCompressed(xrefEntry, suppressEncryption) {
  1170. var tableOffset = xrefEntry.offset;
  1171. var stream = this.fetch(new _primitives.Ref(tableOffset, 0));
  1172. if (!(0, _primitives.isStream)(stream)) {
  1173. throw new _util.FormatError('bad ObjStm stream');
  1174. }
  1175. var first = stream.dict.get('First');
  1176. var n = stream.dict.get('N');
  1177. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1178. throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
  1179. }
  1180. var parser = new _parser.Parser(new _parser.Lexer(stream), false, this);
  1181. parser.allowStreams = true;
  1182. var i,
  1183. entries = [],
  1184. num,
  1185. nums = [];
  1186. for (i = 0; i < n; ++i) {
  1187. num = parser.getObj();
  1188. if (!Number.isInteger(num)) {
  1189. throw new _util.FormatError('invalid object number in the ObjStm stream: ' + num);
  1190. }
  1191. nums.push(num);
  1192. var offset = parser.getObj();
  1193. if (!Number.isInteger(offset)) {
  1194. throw new _util.FormatError('invalid object offset in the ObjStm stream: ' + offset);
  1195. }
  1196. }
  1197. for (i = 0; i < n; ++i) {
  1198. entries.push(parser.getObj());
  1199. if ((0, _primitives.isCmd)(parser.buf1, 'endobj')) {
  1200. parser.shift();
  1201. }
  1202. num = nums[i];
  1203. var entry = this.entries[num];
  1204. if (entry && entry.offset === tableOffset && entry.gen === i) {
  1205. this.cache[num] = entries[i];
  1206. }
  1207. }
  1208. xrefEntry = entries[xrefEntry.gen];
  1209. if (xrefEntry === undefined) {
  1210. throw new _util.FormatError('bad XRef entry for compressed object');
  1211. }
  1212. return xrefEntry;
  1213. },
  1214. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj, suppressEncryption) {
  1215. if (!(0, _primitives.isRef)(obj)) {
  1216. return Promise.resolve(obj);
  1217. }
  1218. return this.fetchAsync(obj, suppressEncryption);
  1219. },
  1220. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  1221. var streamManager = this.stream.manager;
  1222. var xref = this;
  1223. return new Promise(function tryFetch(resolve, reject) {
  1224. try {
  1225. resolve(xref.fetch(ref, suppressEncryption));
  1226. } catch (e) {
  1227. if (e instanceof _util.MissingDataException) {
  1228. streamManager.requestRange(e.begin, e.end).then(function () {
  1229. tryFetch(resolve, reject);
  1230. }, reject);
  1231. return;
  1232. }
  1233. reject(e);
  1234. }
  1235. });
  1236. },
  1237. getCatalogObj: function XRef_getCatalogObj() {
  1238. return this.root;
  1239. }
  1240. };
  1241. return XRef;
  1242. }();
  1243. var NameOrNumberTree = function NameOrNumberTreeClosure() {
  1244. function NameOrNumberTree(root, xref) {
  1245. (0, _util.unreachable)('Cannot initialize NameOrNumberTree.');
  1246. }
  1247. NameOrNumberTree.prototype = {
  1248. getAll: function NameOrNumberTree_getAll() {
  1249. var dict = Object.create(null);
  1250. if (!this.root) {
  1251. return dict;
  1252. }
  1253. var xref = this.xref;
  1254. var processed = new _primitives.RefSet();
  1255. processed.put(this.root);
  1256. var queue = [this.root];
  1257. while (queue.length > 0) {
  1258. var i, n;
  1259. var obj = xref.fetchIfRef(queue.shift());
  1260. if (!(0, _primitives.isDict)(obj)) {
  1261. continue;
  1262. }
  1263. if (obj.has('Kids')) {
  1264. var kids = obj.get('Kids');
  1265. for (i = 0, n = kids.length; i < n; i++) {
  1266. var kid = kids[i];
  1267. if (processed.has(kid)) {
  1268. throw new _util.FormatError('Duplicate entry in "' + this._type + '" tree.');
  1269. }
  1270. queue.push(kid);
  1271. processed.put(kid);
  1272. }
  1273. continue;
  1274. }
  1275. var entries = obj.get(this._type);
  1276. if (Array.isArray(entries)) {
  1277. for (i = 0, n = entries.length; i < n; i += 2) {
  1278. dict[xref.fetchIfRef(entries[i])] = xref.fetchIfRef(entries[i + 1]);
  1279. }
  1280. }
  1281. }
  1282. return dict;
  1283. },
  1284. get: function NameOrNumberTree_get(key) {
  1285. if (!this.root) {
  1286. return null;
  1287. }
  1288. var xref = this.xref;
  1289. var kidsOrEntries = xref.fetchIfRef(this.root);
  1290. var loopCount = 0;
  1291. var MAX_LEVELS = 10;
  1292. var l, r, m;
  1293. while (kidsOrEntries.has('Kids')) {
  1294. if (++loopCount > MAX_LEVELS) {
  1295. (0, _util.warn)('Search depth limit reached for "' + this._type + '" tree.');
  1296. return null;
  1297. }
  1298. var kids = kidsOrEntries.get('Kids');
  1299. if (!Array.isArray(kids)) {
  1300. return null;
  1301. }
  1302. l = 0;
  1303. r = kids.length - 1;
  1304. while (l <= r) {
  1305. m = l + r >> 1;
  1306. var kid = xref.fetchIfRef(kids[m]);
  1307. var limits = kid.get('Limits');
  1308. if (key < xref.fetchIfRef(limits[0])) {
  1309. r = m - 1;
  1310. } else if (key > xref.fetchIfRef(limits[1])) {
  1311. l = m + 1;
  1312. } else {
  1313. kidsOrEntries = xref.fetchIfRef(kids[m]);
  1314. break;
  1315. }
  1316. }
  1317. if (l > r) {
  1318. return null;
  1319. }
  1320. }
  1321. var entries = kidsOrEntries.get(this._type);
  1322. if (Array.isArray(entries)) {
  1323. l = 0;
  1324. r = entries.length - 2;
  1325. while (l <= r) {
  1326. m = l + r & ~1;
  1327. var currentKey = xref.fetchIfRef(entries[m]);
  1328. if (key < currentKey) {
  1329. r = m - 2;
  1330. } else if (key > currentKey) {
  1331. l = m + 2;
  1332. } else {
  1333. return xref.fetchIfRef(entries[m + 1]);
  1334. }
  1335. }
  1336. }
  1337. return null;
  1338. }
  1339. };
  1340. return NameOrNumberTree;
  1341. }();
  1342. var NameTree = function NameTreeClosure() {
  1343. function NameTree(root, xref) {
  1344. this.root = root;
  1345. this.xref = xref;
  1346. this._type = 'Names';
  1347. }
  1348. _util.Util.inherit(NameTree, NameOrNumberTree, {});
  1349. return NameTree;
  1350. }();
  1351. var NumberTree = function NumberTreeClosure() {
  1352. function NumberTree(root, xref) {
  1353. this.root = root;
  1354. this.xref = xref;
  1355. this._type = 'Nums';
  1356. }
  1357. _util.Util.inherit(NumberTree, NameOrNumberTree, {});
  1358. return NumberTree;
  1359. }();
  1360. var FileSpec = function FileSpecClosure() {
  1361. function FileSpec(root, xref) {
  1362. if (!root || !(0, _primitives.isDict)(root)) {
  1363. return;
  1364. }
  1365. this.xref = xref;
  1366. this.root = root;
  1367. if (root.has('FS')) {
  1368. this.fs = root.get('FS');
  1369. }
  1370. this.description = root.has('Desc') ? (0, _util.stringToPDFString)(root.get('Desc')) : '';
  1371. if (root.has('RF')) {
  1372. (0, _util.warn)('Related file specifications are not supported');
  1373. }
  1374. this.contentAvailable = true;
  1375. if (!root.has('EF')) {
  1376. this.contentAvailable = false;
  1377. (0, _util.warn)('Non-embedded file specifications are not supported');
  1378. }
  1379. }
  1380. function pickPlatformItem(dict) {
  1381. if (dict.has('UF')) {
  1382. return dict.get('UF');
  1383. } else if (dict.has('F')) {
  1384. return dict.get('F');
  1385. } else if (dict.has('Unix')) {
  1386. return dict.get('Unix');
  1387. } else if (dict.has('Mac')) {
  1388. return dict.get('Mac');
  1389. } else if (dict.has('DOS')) {
  1390. return dict.get('DOS');
  1391. }
  1392. return null;
  1393. }
  1394. FileSpec.prototype = {
  1395. get filename() {
  1396. if (!this._filename && this.root) {
  1397. var filename = pickPlatformItem(this.root) || 'unnamed';
  1398. this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
  1399. }
  1400. return this._filename;
  1401. },
  1402. get content() {
  1403. if (!this.contentAvailable) {
  1404. return null;
  1405. }
  1406. if (!this.contentRef && this.root) {
  1407. this.contentRef = pickPlatformItem(this.root.get('EF'));
  1408. }
  1409. var content = null;
  1410. if (this.contentRef) {
  1411. var xref = this.xref;
  1412. var fileObj = xref.fetchIfRef(this.contentRef);
  1413. if (fileObj && (0, _primitives.isStream)(fileObj)) {
  1414. content = fileObj.getBytes();
  1415. } else {
  1416. (0, _util.warn)('Embedded file specification points to non-existing/invalid ' + 'content');
  1417. }
  1418. } else {
  1419. (0, _util.warn)('Embedded file specification does not have a content');
  1420. }
  1421. return content;
  1422. },
  1423. get serializable() {
  1424. return {
  1425. filename: this.filename,
  1426. content: this.content
  1427. };
  1428. }
  1429. };
  1430. return FileSpec;
  1431. }();
  1432. var ObjectLoader = function () {
  1433. function mayHaveChildren(value) {
  1434. return (0, _primitives.isRef)(value) || (0, _primitives.isDict)(value) || Array.isArray(value) || (0, _primitives.isStream)(value);
  1435. }
  1436. function addChildren(node, nodesToVisit) {
  1437. if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
  1438. var dict = (0, _primitives.isDict)(node) ? node : node.dict;
  1439. var dictKeys = dict.getKeys();
  1440. for (var i = 0, ii = dictKeys.length; i < ii; i++) {
  1441. var rawValue = dict.getRaw(dictKeys[i]);
  1442. if (mayHaveChildren(rawValue)) {
  1443. nodesToVisit.push(rawValue);
  1444. }
  1445. }
  1446. } else if (Array.isArray(node)) {
  1447. for (var _i = 0, _ii = node.length; _i < _ii; _i++) {
  1448. var value = node[_i];
  1449. if (mayHaveChildren(value)) {
  1450. nodesToVisit.push(value);
  1451. }
  1452. }
  1453. }
  1454. }
  1455. function ObjectLoader(dict, keys, xref) {
  1456. this.dict = dict;
  1457. this.keys = keys;
  1458. this.xref = xref;
  1459. this.refSet = null;
  1460. this.capability = null;
  1461. }
  1462. ObjectLoader.prototype = {
  1463. load: function load() {
  1464. this.capability = (0, _util.createPromiseCapability)();
  1465. if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
  1466. this.capability.resolve();
  1467. return this.capability.promise;
  1468. }
  1469. var keys = this.keys,
  1470. dict = this.dict;
  1471. this.refSet = new _primitives.RefSet();
  1472. var nodesToVisit = [];
  1473. for (var i = 0, ii = keys.length; i < ii; i++) {
  1474. var rawValue = dict.getRaw(keys[i]);
  1475. if (rawValue !== undefined) {
  1476. nodesToVisit.push(rawValue);
  1477. }
  1478. }
  1479. this._walk(nodesToVisit);
  1480. return this.capability.promise;
  1481. },
  1482. _walk: function _walk(nodesToVisit) {
  1483. var _this3 = this;
  1484. var nodesToRevisit = [];
  1485. var pendingRequests = [];
  1486. while (nodesToVisit.length) {
  1487. var currentNode = nodesToVisit.pop();
  1488. if ((0, _primitives.isRef)(currentNode)) {
  1489. if (this.refSet.has(currentNode)) {
  1490. continue;
  1491. }
  1492. try {
  1493. this.refSet.put(currentNode);
  1494. currentNode = this.xref.fetch(currentNode);
  1495. } catch (ex) {
  1496. if (!(ex instanceof _util.MissingDataException)) {
  1497. throw ex;
  1498. }
  1499. nodesToRevisit.push(currentNode);
  1500. pendingRequests.push({
  1501. begin: ex.begin,
  1502. end: ex.end
  1503. });
  1504. }
  1505. }
  1506. if (currentNode && currentNode.getBaseStreams) {
  1507. var baseStreams = currentNode.getBaseStreams();
  1508. var foundMissingData = false;
  1509. for (var i = 0, ii = baseStreams.length; i < ii; i++) {
  1510. var stream = baseStreams[i];
  1511. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  1512. foundMissingData = true;
  1513. pendingRequests.push({
  1514. begin: stream.start,
  1515. end: stream.end
  1516. });
  1517. }
  1518. }
  1519. if (foundMissingData) {
  1520. nodesToRevisit.push(currentNode);
  1521. }
  1522. }
  1523. addChildren(currentNode, nodesToVisit);
  1524. }
  1525. if (pendingRequests.length) {
  1526. this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
  1527. for (var _i2 = 0, _ii2 = nodesToRevisit.length; _i2 < _ii2; _i2++) {
  1528. var node = nodesToRevisit[_i2];
  1529. if ((0, _primitives.isRef)(node)) {
  1530. _this3.refSet.remove(node);
  1531. }
  1532. }
  1533. _this3._walk(nodesToRevisit);
  1534. }, this.capability.reject);
  1535. return;
  1536. }
  1537. this.refSet = null;
  1538. this.capability.resolve();
  1539. }
  1540. };
  1541. return ObjectLoader;
  1542. }();
  1543. exports.Catalog = Catalog;
  1544. exports.ObjectLoader = ObjectLoader;
  1545. exports.XRef = XRef;
  1546. exports.FileSpec = FileSpec;