obj.js 41 KB

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