2
0

obj.js 54 KB

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