obj.js 47 KB

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