obj.js 41 KB

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