2
0

obj.js 48 KB

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