obj.js 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2019 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.FileSpec = exports.XRef = exports.ObjectLoader = exports.Catalog = void 0;
  27. var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  28. var _util = require("../shared/util");
  29. var _primitives = require("./primitives");
  30. var _parser = require("./parser");
  31. var _core_utils = require("./core_utils");
  32. var _chunked_stream = require("./chunked_stream");
  33. var _crypto = require("./crypto");
  34. var _colorspace = require("./colorspace");
  35. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  36. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  37. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  38. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  39. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  40. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  42. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  43. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
  44. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
  45. function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  46. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  47. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  48. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  49. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  50. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  51. function fetchDestination(dest) {
  52. return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
  53. }
  54. var Catalog =
  55. /*#__PURE__*/
  56. function () {
  57. function Catalog(pdfManager, xref) {
  58. _classCallCheck(this, Catalog);
  59. this.pdfManager = pdfManager;
  60. this.xref = xref;
  61. this.catDict = xref.getCatalogObj();
  62. if (!(0, _primitives.isDict)(this.catDict)) {
  63. throw new _util.FormatError('Catalog object is not a dictionary.');
  64. }
  65. this.fontCache = new _primitives.RefSetCache();
  66. this.builtInCMapCache = new Map();
  67. this.pageKidsCountCache = new _primitives.RefSetCache();
  68. }
  69. _createClass(Catalog, [{
  70. key: "_readDocumentOutline",
  71. value: function _readDocumentOutline() {
  72. var obj = this.catDict.get('Outlines');
  73. if (!(0, _primitives.isDict)(obj)) {
  74. return null;
  75. }
  76. obj = obj.getRaw('First');
  77. if (!(0, _primitives.isRef)(obj)) {
  78. return null;
  79. }
  80. var root = {
  81. items: []
  82. };
  83. var queue = [{
  84. obj: obj,
  85. parent: root
  86. }];
  87. var processed = new _primitives.RefSet();
  88. processed.put(obj);
  89. var xref = this.xref,
  90. blackColor = new Uint8ClampedArray(3);
  91. while (queue.length > 0) {
  92. var i = queue.shift();
  93. var outlineDict = xref.fetchIfRef(i.obj);
  94. if (outlineDict === null) {
  95. continue;
  96. }
  97. if (!outlineDict.has('Title')) {
  98. throw new _util.FormatError('Invalid outline item encountered.');
  99. }
  100. var data = {
  101. url: null,
  102. dest: null
  103. };
  104. Catalog.parseDestDictionary({
  105. destDict: outlineDict,
  106. resultObj: data,
  107. docBaseUrl: this.pdfManager.docBaseUrl
  108. });
  109. var title = outlineDict.get('Title');
  110. var flags = outlineDict.get('F') || 0;
  111. var color = outlineDict.getArray('C');
  112. var count = outlineDict.get('Count');
  113. var rgbColor = blackColor;
  114. if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
  115. rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
  116. }
  117. var outlineItem = {
  118. dest: data.dest,
  119. url: data.url,
  120. unsafeUrl: data.unsafeUrl,
  121. newWindow: data.newWindow,
  122. title: (0, _util.stringToPDFString)(title),
  123. color: rgbColor,
  124. count: Number.isInteger(count) ? count : undefined,
  125. bold: !!(flags & 2),
  126. italic: !!(flags & 1),
  127. items: []
  128. };
  129. i.parent.items.push(outlineItem);
  130. obj = outlineDict.getRaw('First');
  131. if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
  132. queue.push({
  133. obj: obj,
  134. parent: outlineItem
  135. });
  136. processed.put(obj);
  137. }
  138. obj = outlineDict.getRaw('Next');
  139. if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
  140. queue.push({
  141. obj: obj,
  142. parent: i.parent
  143. });
  144. processed.put(obj);
  145. }
  146. }
  147. return root.items.length > 0 ? root.items : null;
  148. }
  149. }, {
  150. key: "_readPermissions",
  151. value: function _readPermissions() {
  152. var encrypt = this.xref.trailer.get('Encrypt');
  153. if (!(0, _primitives.isDict)(encrypt)) {
  154. return null;
  155. }
  156. var flags = encrypt.get('P');
  157. if (!(0, _util.isNum)(flags)) {
  158. return null;
  159. }
  160. flags += Math.pow(2, 32);
  161. var permissions = [];
  162. for (var key in _util.PermissionFlag) {
  163. var value = _util.PermissionFlag[key];
  164. if (flags & value) {
  165. permissions.push(value);
  166. }
  167. }
  168. return permissions;
  169. }
  170. }, {
  171. key: "getDestination",
  172. value: function getDestination(destinationId) {
  173. var obj = this._readDests();
  174. if (obj instanceof NameTree || obj instanceof _primitives.Dict) {
  175. return fetchDestination(obj.get(destinationId) || null);
  176. }
  177. return null;
  178. }
  179. }, {
  180. key: "_readDests",
  181. value: function _readDests() {
  182. var obj = this.catDict.get('Names');
  183. if (obj && obj.has('Dests')) {
  184. return new NameTree(obj.getRaw('Dests'), this.xref);
  185. } else if (this.catDict.has('Dests')) {
  186. return this.catDict.get('Dests');
  187. }
  188. return undefined;
  189. }
  190. }, {
  191. key: "_readPageLabels",
  192. value: function _readPageLabels() {
  193. var obj = this.catDict.getRaw('PageLabels');
  194. if (!obj) {
  195. return null;
  196. }
  197. var pageLabels = new Array(this.numPages);
  198. var style = null,
  199. prefix = '';
  200. var numberTree = new NumberTree(obj, this.xref);
  201. var nums = numberTree.getAll();
  202. var currentLabel = '',
  203. currentIndex = 1;
  204. for (var i = 0, ii = this.numPages; i < ii; i++) {
  205. if (i in nums) {
  206. var labelDict = nums[i];
  207. if (!(0, _primitives.isDict)(labelDict)) {
  208. throw new _util.FormatError('PageLabel is not a dictionary.');
  209. }
  210. if (labelDict.has('Type') && !(0, _primitives.isName)(labelDict.get('Type'), 'PageLabel')) {
  211. throw new _util.FormatError('Invalid type in PageLabel dictionary.');
  212. }
  213. if (labelDict.has('S')) {
  214. var s = labelDict.get('S');
  215. if (!(0, _primitives.isName)(s)) {
  216. throw new _util.FormatError('Invalid style in PageLabel dictionary.');
  217. }
  218. style = s.name;
  219. } else {
  220. style = null;
  221. }
  222. if (labelDict.has('P')) {
  223. var p = labelDict.get('P');
  224. if (!(0, _util.isString)(p)) {
  225. throw new _util.FormatError('Invalid prefix in PageLabel dictionary.');
  226. }
  227. prefix = (0, _util.stringToPDFString)(p);
  228. } else {
  229. prefix = '';
  230. }
  231. if (labelDict.has('St')) {
  232. var st = labelDict.get('St');
  233. if (!(Number.isInteger(st) && st >= 1)) {
  234. throw new _util.FormatError('Invalid start in PageLabel dictionary.');
  235. }
  236. currentIndex = st;
  237. } else {
  238. currentIndex = 1;
  239. }
  240. }
  241. switch (style) {
  242. case 'D':
  243. currentLabel = currentIndex;
  244. break;
  245. case 'R':
  246. case 'r':
  247. currentLabel = (0, _core_utils.toRomanNumerals)(currentIndex, style === 'r');
  248. break;
  249. case 'A':
  250. case 'a':
  251. var LIMIT = 26;
  252. var A_UPPER_CASE = 0x41,
  253. A_LOWER_CASE = 0x61;
  254. var baseCharCode = style === 'a' ? A_LOWER_CASE : A_UPPER_CASE;
  255. var letterIndex = currentIndex - 1;
  256. var character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
  257. var charBuf = [];
  258. for (var j = 0, jj = letterIndex / LIMIT | 0; j <= jj; j++) {
  259. charBuf.push(character);
  260. }
  261. currentLabel = charBuf.join('');
  262. break;
  263. default:
  264. if (style) {
  265. throw new _util.FormatError("Invalid style \"".concat(style, "\" in PageLabel dictionary."));
  266. }
  267. currentLabel = '';
  268. }
  269. pageLabels[i] = prefix + currentLabel;
  270. currentIndex++;
  271. }
  272. return pageLabels;
  273. }
  274. }, {
  275. key: "fontFallback",
  276. value: function fontFallback(id, handler) {
  277. var promises = [];
  278. this.fontCache.forEach(function (promise) {
  279. promises.push(promise);
  280. });
  281. return Promise.all(promises).then(function (translatedFonts) {
  282. var _iteratorNormalCompletion = true;
  283. var _didIteratorError = false;
  284. var _iteratorError = undefined;
  285. try {
  286. for (var _iterator = translatedFonts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  287. var translatedFont = _step.value;
  288. if (translatedFont.loadedName === id) {
  289. translatedFont.fallback(handler);
  290. return;
  291. }
  292. }
  293. } catch (err) {
  294. _didIteratorError = true;
  295. _iteratorError = err;
  296. } finally {
  297. try {
  298. if (!_iteratorNormalCompletion && _iterator["return"] != null) {
  299. _iterator["return"]();
  300. }
  301. } finally {
  302. if (_didIteratorError) {
  303. throw _iteratorError;
  304. }
  305. }
  306. }
  307. });
  308. }
  309. }, {
  310. key: "cleanup",
  311. value: function cleanup() {
  312. var _this = this;
  313. (0, _primitives.clearPrimitiveCaches)();
  314. this.pageKidsCountCache.clear();
  315. var promises = [];
  316. this.fontCache.forEach(function (promise) {
  317. promises.push(promise);
  318. });
  319. return Promise.all(promises).then(function (translatedFonts) {
  320. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  321. var font = translatedFonts[i].dict;
  322. delete font.translated;
  323. }
  324. _this.fontCache.clear();
  325. _this.builtInCMapCache.clear();
  326. });
  327. }
  328. }, {
  329. key: "getPageDict",
  330. value: function getPageDict(pageIndex) {
  331. var capability = (0, _util.createPromiseCapability)();
  332. var nodesToVisit = [this.catDict.getRaw('Pages')];
  333. var xref = this.xref,
  334. pageKidsCountCache = this.pageKidsCountCache;
  335. var count,
  336. currentPageIndex = 0;
  337. function next() {
  338. var _loop = function _loop() {
  339. var currentNode = nodesToVisit.pop();
  340. if ((0, _primitives.isRef)(currentNode)) {
  341. count = pageKidsCountCache.get(currentNode);
  342. if (count > 0 && currentPageIndex + count < pageIndex) {
  343. currentPageIndex += count;
  344. return "continue";
  345. }
  346. xref.fetchAsync(currentNode).then(function (obj) {
  347. if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Kids')) {
  348. if (pageIndex === currentPageIndex) {
  349. if (currentNode && !pageKidsCountCache.has(currentNode)) {
  350. pageKidsCountCache.put(currentNode, 1);
  351. }
  352. capability.resolve([obj, currentNode]);
  353. } else {
  354. currentPageIndex++;
  355. next();
  356. }
  357. return;
  358. }
  359. nodesToVisit.push(obj);
  360. next();
  361. }, capability.reject);
  362. return {
  363. v: void 0
  364. };
  365. }
  366. if (!(0, _primitives.isDict)(currentNode)) {
  367. capability.reject(new _util.FormatError('Page dictionary kid reference points to wrong type of object.'));
  368. return {
  369. v: void 0
  370. };
  371. }
  372. count = currentNode.get('Count');
  373. if (Number.isInteger(count) && count >= 0) {
  374. var objId = currentNode.objId;
  375. if (objId && !pageKidsCountCache.has(objId)) {
  376. pageKidsCountCache.put(objId, count);
  377. }
  378. if (currentPageIndex + count <= pageIndex) {
  379. currentPageIndex += count;
  380. return "continue";
  381. }
  382. }
  383. var kids = currentNode.get('Kids');
  384. if (!Array.isArray(kids)) {
  385. if ((0, _primitives.isName)(currentNode.get('Type'), 'Page') || !currentNode.has('Type') && currentNode.has('Contents')) {
  386. if (currentPageIndex === pageIndex) {
  387. capability.resolve([currentNode, null]);
  388. return {
  389. v: void 0
  390. };
  391. }
  392. currentPageIndex++;
  393. return "continue";
  394. }
  395. capability.reject(new _util.FormatError('Page dictionary kids object is not an array.'));
  396. return {
  397. v: void 0
  398. };
  399. }
  400. for (var last = kids.length - 1; last >= 0; last--) {
  401. nodesToVisit.push(kids[last]);
  402. }
  403. };
  404. while (nodesToVisit.length) {
  405. var _ret = _loop();
  406. switch (_ret) {
  407. case "continue":
  408. continue;
  409. default:
  410. if (_typeof(_ret) === "object") return _ret.v;
  411. }
  412. }
  413. capability.reject(new Error("Page index ".concat(pageIndex, " not found.")));
  414. }
  415. next();
  416. return capability.promise;
  417. }
  418. }, {
  419. key: "getPageIndex",
  420. value: function getPageIndex(pageRef) {
  421. var xref = this.xref;
  422. function pagesBeforeRef(kidRef) {
  423. var total = 0,
  424. parentRef;
  425. return xref.fetchAsync(kidRef).then(function (node) {
  426. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, 'Page') && !((0, _primitives.isDict)(node) && !node.has('Type') && node.has('Contents'))) {
  427. throw new _util.FormatError('The reference does not point to a /Page dictionary.');
  428. }
  429. if (!node) {
  430. return null;
  431. }
  432. if (!(0, _primitives.isDict)(node)) {
  433. throw new _util.FormatError('Node must be a dictionary.');
  434. }
  435. parentRef = node.getRaw('Parent');
  436. return node.getAsync('Parent');
  437. }).then(function (parent) {
  438. if (!parent) {
  439. return null;
  440. }
  441. if (!(0, _primitives.isDict)(parent)) {
  442. throw new _util.FormatError('Parent must be a dictionary.');
  443. }
  444. return parent.getAsync('Kids');
  445. }).then(function (kids) {
  446. if (!kids) {
  447. return null;
  448. }
  449. var kidPromises = [];
  450. var found = false;
  451. for (var i = 0, ii = kids.length; i < ii; i++) {
  452. var kid = kids[i];
  453. if (!(0, _primitives.isRef)(kid)) {
  454. throw new _util.FormatError('Kid must be a reference.');
  455. }
  456. if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
  457. found = true;
  458. break;
  459. }
  460. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  461. if (!(0, _primitives.isDict)(kid)) {
  462. throw new _util.FormatError('Kid node must be a dictionary.');
  463. }
  464. if (kid.has('Count')) {
  465. total += kid.get('Count');
  466. } else {
  467. total++;
  468. }
  469. }));
  470. }
  471. if (!found) {
  472. throw new _util.FormatError('Kid reference not found in parent\'s kids.');
  473. }
  474. return Promise.all(kidPromises).then(function () {
  475. return [total, parentRef];
  476. });
  477. });
  478. }
  479. var total = 0;
  480. function next(ref) {
  481. return pagesBeforeRef(ref).then(function (args) {
  482. if (!args) {
  483. return total;
  484. }
  485. var _args = _slicedToArray(args, 2),
  486. count = _args[0],
  487. parentRef = _args[1];
  488. total += count;
  489. return next(parentRef);
  490. });
  491. }
  492. return next(pageRef);
  493. }
  494. }, {
  495. key: "metadata",
  496. get: function get() {
  497. var streamRef = this.catDict.getRaw('Metadata');
  498. if (!(0, _primitives.isRef)(streamRef)) {
  499. return (0, _util.shadow)(this, 'metadata', null);
  500. }
  501. var suppressEncryption = !(this.xref.encrypt && this.xref.encrypt.encryptMetadata);
  502. var stream = this.xref.fetch(streamRef, suppressEncryption);
  503. var metadata;
  504. if (stream && (0, _primitives.isDict)(stream.dict)) {
  505. var type = stream.dict.get('Type');
  506. var subtype = stream.dict.get('Subtype');
  507. if ((0, _primitives.isName)(type, 'Metadata') && (0, _primitives.isName)(subtype, 'XML')) {
  508. try {
  509. metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
  510. } catch (e) {
  511. if (e instanceof _core_utils.MissingDataException) {
  512. throw e;
  513. }
  514. (0, _util.info)('Skipping invalid metadata.');
  515. }
  516. }
  517. }
  518. return (0, _util.shadow)(this, 'metadata', metadata);
  519. }
  520. }, {
  521. key: "toplevelPagesDict",
  522. get: function get() {
  523. var pagesObj = this.catDict.get('Pages');
  524. if (!(0, _primitives.isDict)(pagesObj)) {
  525. throw new _util.FormatError('Invalid top-level pages dictionary.');
  526. }
  527. return (0, _util.shadow)(this, 'toplevelPagesDict', pagesObj);
  528. }
  529. }, {
  530. key: "documentOutline",
  531. get: function get() {
  532. var obj = null;
  533. try {
  534. obj = this._readDocumentOutline();
  535. } catch (ex) {
  536. if (ex instanceof _core_utils.MissingDataException) {
  537. throw ex;
  538. }
  539. (0, _util.warn)('Unable to read document outline.');
  540. }
  541. return (0, _util.shadow)(this, 'documentOutline', obj);
  542. }
  543. }, {
  544. key: "permissions",
  545. get: function get() {
  546. var permissions = null;
  547. try {
  548. permissions = this._readPermissions();
  549. } catch (ex) {
  550. if (ex instanceof _core_utils.MissingDataException) {
  551. throw ex;
  552. }
  553. (0, _util.warn)('Unable to read permissions.');
  554. }
  555. return (0, _util.shadow)(this, 'permissions', permissions);
  556. }
  557. }, {
  558. key: "numPages",
  559. get: function get() {
  560. var obj = this.toplevelPagesDict.get('Count');
  561. if (!Number.isInteger(obj)) {
  562. throw new _util.FormatError('Page count in top-level pages dictionary is not an integer.');
  563. }
  564. return (0, _util.shadow)(this, 'numPages', obj);
  565. }
  566. }, {
  567. key: "destinations",
  568. get: function get() {
  569. var obj = this._readDests(),
  570. dests = Object.create(null);
  571. if (obj instanceof NameTree) {
  572. var names = obj.getAll();
  573. for (var name in names) {
  574. dests[name] = fetchDestination(names[name]);
  575. }
  576. } else if (obj instanceof _primitives.Dict) {
  577. obj.forEach(function (key, value) {
  578. if (value) {
  579. dests[key] = fetchDestination(value);
  580. }
  581. });
  582. }
  583. return (0, _util.shadow)(this, 'destinations', dests);
  584. }
  585. }, {
  586. key: "pageLabels",
  587. get: function get() {
  588. var obj = null;
  589. try {
  590. obj = this._readPageLabels();
  591. } catch (ex) {
  592. if (ex instanceof _core_utils.MissingDataException) {
  593. throw ex;
  594. }
  595. (0, _util.warn)('Unable to read page labels.');
  596. }
  597. return (0, _util.shadow)(this, 'pageLabels', obj);
  598. }
  599. }, {
  600. key: "pageLayout",
  601. get: function get() {
  602. var obj = this.catDict.get('PageLayout');
  603. var pageLayout = '';
  604. if ((0, _primitives.isName)(obj)) {
  605. switch (obj.name) {
  606. case 'SinglePage':
  607. case 'OneColumn':
  608. case 'TwoColumnLeft':
  609. case 'TwoColumnRight':
  610. case 'TwoPageLeft':
  611. case 'TwoPageRight':
  612. pageLayout = obj.name;
  613. }
  614. }
  615. return (0, _util.shadow)(this, 'pageLayout', pageLayout);
  616. }
  617. }, {
  618. key: "pageMode",
  619. get: function get() {
  620. var obj = this.catDict.get('PageMode');
  621. var pageMode = 'UseNone';
  622. if ((0, _primitives.isName)(obj)) {
  623. switch (obj.name) {
  624. case 'UseNone':
  625. case 'UseOutlines':
  626. case 'UseThumbs':
  627. case 'FullScreen':
  628. case 'UseOC':
  629. case 'UseAttachments':
  630. pageMode = obj.name;
  631. }
  632. }
  633. return (0, _util.shadow)(this, 'pageMode', pageMode);
  634. }
  635. }, {
  636. key: "viewerPreferences",
  637. get: function get() {
  638. var _this2 = this;
  639. var ViewerPreferencesValidators = {
  640. HideToolbar: _util.isBool,
  641. HideMenubar: _util.isBool,
  642. HideWindowUI: _util.isBool,
  643. FitWindow: _util.isBool,
  644. CenterWindow: _util.isBool,
  645. DisplayDocTitle: _util.isBool,
  646. NonFullScreenPageMode: _primitives.isName,
  647. Direction: _primitives.isName,
  648. ViewArea: _primitives.isName,
  649. ViewClip: _primitives.isName,
  650. PrintArea: _primitives.isName,
  651. PrintClip: _primitives.isName,
  652. PrintScaling: _primitives.isName,
  653. Duplex: _primitives.isName,
  654. PickTrayByPDFSize: _util.isBool,
  655. PrintPageRange: Array.isArray,
  656. NumCopies: Number.isInteger
  657. };
  658. var obj = this.catDict.get('ViewerPreferences');
  659. var prefs = Object.create(null);
  660. if ((0, _primitives.isDict)(obj)) {
  661. for (var key in ViewerPreferencesValidators) {
  662. if (!obj.has(key)) {
  663. continue;
  664. }
  665. var value = obj.get(key);
  666. if (!ViewerPreferencesValidators[key](value)) {
  667. (0, _util.info)("Bad value in ViewerPreferences for \"".concat(key, "\"."));
  668. continue;
  669. }
  670. var prefValue = void 0;
  671. switch (key) {
  672. case 'NonFullScreenPageMode':
  673. switch (value.name) {
  674. case 'UseNone':
  675. case 'UseOutlines':
  676. case 'UseThumbs':
  677. case 'UseOC':
  678. prefValue = value.name;
  679. break;
  680. default:
  681. prefValue = 'UseNone';
  682. }
  683. break;
  684. case 'Direction':
  685. switch (value.name) {
  686. case 'L2R':
  687. case 'R2L':
  688. prefValue = value.name;
  689. break;
  690. default:
  691. prefValue = 'L2R';
  692. }
  693. break;
  694. case 'ViewArea':
  695. case 'ViewClip':
  696. case 'PrintArea':
  697. case 'PrintClip':
  698. switch (value.name) {
  699. case 'MediaBox':
  700. case 'CropBox':
  701. case 'BleedBox':
  702. case 'TrimBox':
  703. case 'ArtBox':
  704. prefValue = value.name;
  705. break;
  706. default:
  707. prefValue = 'CropBox';
  708. }
  709. break;
  710. case 'PrintScaling':
  711. switch (value.name) {
  712. case 'None':
  713. case 'AppDefault':
  714. prefValue = value.name;
  715. break;
  716. default:
  717. prefValue = 'AppDefault';
  718. }
  719. break;
  720. case 'Duplex':
  721. switch (value.name) {
  722. case 'Simplex':
  723. case 'DuplexFlipShortEdge':
  724. case 'DuplexFlipLongEdge':
  725. prefValue = value.name;
  726. break;
  727. default:
  728. prefValue = 'None';
  729. }
  730. break;
  731. case 'PrintPageRange':
  732. var length = value.length;
  733. if (length % 2 !== 0) {
  734. break;
  735. }
  736. var isValid = value.every(function (page, i, arr) {
  737. return Number.isInteger(page) && page > 0 && (i === 0 || page >= arr[i - 1]) && page <= _this2.numPages;
  738. });
  739. if (isValid) {
  740. prefValue = value;
  741. }
  742. break;
  743. case 'NumCopies':
  744. if (value > 0) {
  745. prefValue = value;
  746. }
  747. break;
  748. default:
  749. (0, _util.assert)(typeof value === 'boolean');
  750. prefValue = value;
  751. }
  752. if (prefValue !== undefined) {
  753. prefs[key] = prefValue;
  754. } else {
  755. (0, _util.info)("Bad value in ViewerPreferences for \"".concat(key, "\"."));
  756. }
  757. }
  758. }
  759. return (0, _util.shadow)(this, 'viewerPreferences', prefs);
  760. }
  761. }, {
  762. key: "openActionDestination",
  763. get: function get() {
  764. var obj = this.catDict.get('OpenAction');
  765. var openActionDest = null;
  766. if ((0, _primitives.isDict)(obj)) {
  767. var destDict = new _primitives.Dict(this.xref);
  768. destDict.set('A', obj);
  769. var resultObj = {
  770. url: null,
  771. dest: null
  772. };
  773. Catalog.parseDestDictionary({
  774. destDict: destDict,
  775. resultObj: resultObj
  776. });
  777. if (Array.isArray(resultObj.dest)) {
  778. openActionDest = resultObj.dest;
  779. }
  780. } else if (Array.isArray(obj)) {
  781. openActionDest = obj;
  782. }
  783. return (0, _util.shadow)(this, 'openActionDestination', openActionDest);
  784. }
  785. }, {
  786. key: "attachments",
  787. get: function get() {
  788. var obj = this.catDict.get('Names');
  789. var attachments = null;
  790. if (obj && obj.has('EmbeddedFiles')) {
  791. var nameTree = new NameTree(obj.getRaw('EmbeddedFiles'), this.xref);
  792. var names = nameTree.getAll();
  793. for (var name in names) {
  794. var fs = new FileSpec(names[name], this.xref);
  795. if (!attachments) {
  796. attachments = Object.create(null);
  797. }
  798. attachments[(0, _util.stringToPDFString)(name)] = fs.serializable;
  799. }
  800. }
  801. return (0, _util.shadow)(this, 'attachments', attachments);
  802. }
  803. }, {
  804. key: "javaScript",
  805. get: function get() {
  806. var obj = this.catDict.get('Names');
  807. var javaScript = null;
  808. function appendIfJavaScriptDict(jsDict) {
  809. var type = jsDict.get('S');
  810. if (!(0, _primitives.isName)(type, 'JavaScript')) {
  811. return;
  812. }
  813. var js = jsDict.get('JS');
  814. if ((0, _primitives.isStream)(js)) {
  815. js = (0, _util.bytesToString)(js.getBytes());
  816. } else if (!(0, _util.isString)(js)) {
  817. return;
  818. }
  819. if (!javaScript) {
  820. javaScript = [];
  821. }
  822. javaScript.push((0, _util.stringToPDFString)(js));
  823. }
  824. if (obj && obj.has('JavaScript')) {
  825. var nameTree = new NameTree(obj.getRaw('JavaScript'), this.xref);
  826. var names = nameTree.getAll();
  827. for (var name in names) {
  828. var jsDict = names[name];
  829. if ((0, _primitives.isDict)(jsDict)) {
  830. appendIfJavaScriptDict(jsDict);
  831. }
  832. }
  833. }
  834. var openActionDict = this.catDict.get('OpenAction');
  835. if ((0, _primitives.isDict)(openActionDict, 'Action')) {
  836. var actionType = openActionDict.get('S');
  837. if ((0, _primitives.isName)(actionType, 'Named')) {
  838. var action = openActionDict.get('N');
  839. if ((0, _primitives.isName)(action, 'Print')) {
  840. if (!javaScript) {
  841. javaScript = [];
  842. }
  843. javaScript.push('print({});');
  844. }
  845. } else {
  846. appendIfJavaScriptDict(openActionDict);
  847. }
  848. }
  849. return (0, _util.shadow)(this, 'javaScript', javaScript);
  850. }
  851. }], [{
  852. key: "parseDestDictionary",
  853. value: function parseDestDictionary(params) {
  854. function addDefaultProtocolToUrl(url) {
  855. return url.startsWith('www.') ? "http://".concat(url) : url;
  856. }
  857. function tryConvertUrlEncoding(url) {
  858. try {
  859. return (0, _util.stringToUTF8String)(url);
  860. } catch (e) {
  861. return url;
  862. }
  863. }
  864. var destDict = params.destDict;
  865. if (!(0, _primitives.isDict)(destDict)) {
  866. (0, _util.warn)('parseDestDictionary: `destDict` must be a dictionary.');
  867. return;
  868. }
  869. var resultObj = params.resultObj;
  870. if (_typeof(resultObj) !== 'object') {
  871. (0, _util.warn)('parseDestDictionary: `resultObj` must be an object.');
  872. return;
  873. }
  874. var docBaseUrl = params.docBaseUrl || null;
  875. var action = destDict.get('A'),
  876. url,
  877. dest;
  878. if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
  879. action = destDict.get('Dest');
  880. }
  881. if ((0, _primitives.isDict)(action)) {
  882. var actionType = action.get('S');
  883. if (!(0, _primitives.isName)(actionType)) {
  884. (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
  885. return;
  886. }
  887. var actionName = actionType.name;
  888. switch (actionName) {
  889. case 'URI':
  890. url = action.get('URI');
  891. if ((0, _primitives.isName)(url)) {
  892. url = '/' + url.name;
  893. } else if ((0, _util.isString)(url)) {
  894. url = addDefaultProtocolToUrl(url);
  895. }
  896. break;
  897. case 'GoTo':
  898. dest = action.get('D');
  899. break;
  900. case 'Launch':
  901. case 'GoToR':
  902. var urlDict = action.get('F');
  903. if ((0, _primitives.isDict)(urlDict)) {
  904. url = urlDict.get('F') || null;
  905. } else if ((0, _util.isString)(urlDict)) {
  906. url = urlDict;
  907. }
  908. var remoteDest = action.get('D');
  909. if (remoteDest) {
  910. if ((0, _primitives.isName)(remoteDest)) {
  911. remoteDest = remoteDest.name;
  912. }
  913. if ((0, _util.isString)(url)) {
  914. var baseUrl = url.split('#')[0];
  915. if ((0, _util.isString)(remoteDest)) {
  916. url = baseUrl + '#' + remoteDest;
  917. } else if (Array.isArray(remoteDest)) {
  918. url = baseUrl + '#' + JSON.stringify(remoteDest);
  919. }
  920. }
  921. }
  922. var newWindow = action.get('NewWindow');
  923. if ((0, _util.isBool)(newWindow)) {
  924. resultObj.newWindow = newWindow;
  925. }
  926. break;
  927. case 'Named':
  928. var namedAction = action.get('N');
  929. if ((0, _primitives.isName)(namedAction)) {
  930. resultObj.action = namedAction.name;
  931. }
  932. break;
  933. case 'JavaScript':
  934. var jsAction = action.get('JS');
  935. var js;
  936. if ((0, _primitives.isStream)(jsAction)) {
  937. js = (0, _util.bytesToString)(jsAction.getBytes());
  938. } else if ((0, _util.isString)(jsAction)) {
  939. js = jsAction;
  940. }
  941. if (js) {
  942. var URL_OPEN_METHODS = ['app.launchURL', 'window.open'];
  943. var regex = new RegExp('^\\s*(' + URL_OPEN_METHODS.join('|').split('.').join('\\.') + ')\\((?:\'|\")([^\'\"]*)(?:\'|\")(?:,\\s*(\\w+)\\)|\\))', 'i');
  944. var jsUrl = regex.exec((0, _util.stringToPDFString)(js));
  945. if (jsUrl && jsUrl[2]) {
  946. url = jsUrl[2];
  947. if (jsUrl[3] === 'true' && jsUrl[1] === 'app.launchURL') {
  948. resultObj.newWindow = true;
  949. }
  950. break;
  951. }
  952. }
  953. default:
  954. (0, _util.warn)("parseDestDictionary: unsupported action type \"".concat(actionName, "\"."));
  955. break;
  956. }
  957. } else if (destDict.has('Dest')) {
  958. dest = destDict.get('Dest');
  959. }
  960. if ((0, _util.isString)(url)) {
  961. url = tryConvertUrlEncoding(url);
  962. var absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
  963. if (absoluteUrl) {
  964. resultObj.url = absoluteUrl.href;
  965. }
  966. resultObj.unsafeUrl = url;
  967. }
  968. if (dest) {
  969. if ((0, _primitives.isName)(dest)) {
  970. dest = dest.name;
  971. }
  972. if ((0, _util.isString)(dest) || Array.isArray(dest)) {
  973. resultObj.dest = dest;
  974. }
  975. }
  976. }
  977. }]);
  978. return Catalog;
  979. }();
  980. exports.Catalog = Catalog;
  981. var XRef = function XRefClosure() {
  982. function XRef(stream, pdfManager) {
  983. this.stream = stream;
  984. this.pdfManager = pdfManager;
  985. this.entries = [];
  986. this.xrefstms = Object.create(null);
  987. this._cacheMap = new Map();
  988. this.stats = {
  989. streamTypes: Object.create(null),
  990. fontTypes: Object.create(null)
  991. };
  992. }
  993. XRef.prototype = {
  994. setStartXRef: function XRef_setStartXRef(startXRef) {
  995. this.startXRefQueue = [startXRef];
  996. },
  997. parse: function XRef_parse(recoveryMode) {
  998. var trailerDict;
  999. if (!recoveryMode) {
  1000. trailerDict = this.readXRef();
  1001. } else {
  1002. (0, _util.warn)('Indexing all PDF objects');
  1003. trailerDict = this.indexObjects();
  1004. }
  1005. trailerDict.assignXref(this);
  1006. this.trailer = trailerDict;
  1007. var encrypt;
  1008. try {
  1009. encrypt = trailerDict.get('Encrypt');
  1010. } catch (ex) {
  1011. if (ex instanceof _core_utils.MissingDataException) {
  1012. throw ex;
  1013. }
  1014. (0, _util.warn)("XRef.parse - Invalid \"Encrypt\" reference: \"".concat(ex, "\"."));
  1015. }
  1016. if ((0, _primitives.isDict)(encrypt)) {
  1017. var ids = trailerDict.get('ID');
  1018. var fileId = ids && ids.length ? ids[0] : '';
  1019. encrypt.suppressEncryption = true;
  1020. this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
  1021. }
  1022. var root;
  1023. try {
  1024. root = trailerDict.get('Root');
  1025. } catch (ex) {
  1026. if (ex instanceof _core_utils.MissingDataException) {
  1027. throw ex;
  1028. }
  1029. (0, _util.warn)("XRef.parse - Invalid \"Root\" reference: \"".concat(ex, "\"."));
  1030. }
  1031. if ((0, _primitives.isDict)(root) && root.has('Pages')) {
  1032. this.root = root;
  1033. } else {
  1034. if (!recoveryMode) {
  1035. throw new _core_utils.XRefParseException();
  1036. }
  1037. throw new _util.FormatError('Invalid root reference');
  1038. }
  1039. },
  1040. processXRefTable: function XRef_processXRefTable(parser) {
  1041. if (!('tableState' in this)) {
  1042. this.tableState = {
  1043. entryNum: 0,
  1044. streamPos: parser.lexer.stream.pos,
  1045. parserBuf1: parser.buf1,
  1046. parserBuf2: parser.buf2
  1047. };
  1048. }
  1049. var obj = this.readXRefTable(parser);
  1050. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  1051. throw new _util.FormatError('Invalid XRef table: could not find trailer dictionary');
  1052. }
  1053. var dict = parser.getObj();
  1054. if (!(0, _primitives.isDict)(dict) && dict.dict) {
  1055. dict = dict.dict;
  1056. }
  1057. if (!(0, _primitives.isDict)(dict)) {
  1058. throw new _util.FormatError('Invalid XRef table: could not parse trailer dictionary');
  1059. }
  1060. delete this.tableState;
  1061. return dict;
  1062. },
  1063. readXRefTable: function XRef_readXRefTable(parser) {
  1064. var stream = parser.lexer.stream;
  1065. var tableState = this.tableState;
  1066. stream.pos = tableState.streamPos;
  1067. parser.buf1 = tableState.parserBuf1;
  1068. parser.buf2 = tableState.parserBuf2;
  1069. var obj;
  1070. while (true) {
  1071. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  1072. if ((0, _primitives.isCmd)(obj = parser.getObj(), 'trailer')) {
  1073. break;
  1074. }
  1075. tableState.firstEntryNum = obj;
  1076. tableState.entryCount = parser.getObj();
  1077. }
  1078. var first = tableState.firstEntryNum;
  1079. var count = tableState.entryCount;
  1080. if (!Number.isInteger(first) || !Number.isInteger(count)) {
  1081. throw new _util.FormatError('Invalid XRef table: wrong types in subsection header');
  1082. }
  1083. for (var i = tableState.entryNum; i < count; i++) {
  1084. tableState.streamPos = stream.pos;
  1085. tableState.entryNum = i;
  1086. tableState.parserBuf1 = parser.buf1;
  1087. tableState.parserBuf2 = parser.buf2;
  1088. var entry = {};
  1089. entry.offset = parser.getObj();
  1090. entry.gen = parser.getObj();
  1091. var type = parser.getObj();
  1092. if (type instanceof _primitives.Cmd) {
  1093. switch (type.cmd) {
  1094. case 'f':
  1095. entry.free = true;
  1096. break;
  1097. case 'n':
  1098. entry.uncompressed = true;
  1099. break;
  1100. }
  1101. }
  1102. if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
  1103. throw new _util.FormatError("Invalid entry in XRef subsection: ".concat(first, ", ").concat(count));
  1104. }
  1105. if (i === 0 && entry.free && first === 1) {
  1106. first = 0;
  1107. }
  1108. if (!this.entries[i + first]) {
  1109. this.entries[i + first] = entry;
  1110. }
  1111. }
  1112. tableState.entryNum = 0;
  1113. tableState.streamPos = stream.pos;
  1114. tableState.parserBuf1 = parser.buf1;
  1115. tableState.parserBuf2 = parser.buf2;
  1116. delete tableState.firstEntryNum;
  1117. delete tableState.entryCount;
  1118. }
  1119. if (this.entries[0] && !this.entries[0].free) {
  1120. throw new _util.FormatError('Invalid XRef table: unexpected first object');
  1121. }
  1122. return obj;
  1123. },
  1124. processXRefStream: function XRef_processXRefStream(stream) {
  1125. if (!('streamState' in this)) {
  1126. var streamParameters = stream.dict;
  1127. var byteWidths = streamParameters.get('W');
  1128. var range = streamParameters.get('Index');
  1129. if (!range) {
  1130. range = [0, streamParameters.get('Size')];
  1131. }
  1132. this.streamState = {
  1133. entryRanges: range,
  1134. byteWidths: byteWidths,
  1135. entryNum: 0,
  1136. streamPos: stream.pos
  1137. };
  1138. }
  1139. this.readXRefStream(stream);
  1140. delete this.streamState;
  1141. return stream.dict;
  1142. },
  1143. readXRefStream: function XRef_readXRefStream(stream) {
  1144. var i, j;
  1145. var streamState = this.streamState;
  1146. stream.pos = streamState.streamPos;
  1147. var byteWidths = streamState.byteWidths;
  1148. var typeFieldWidth = byteWidths[0];
  1149. var offsetFieldWidth = byteWidths[1];
  1150. var generationFieldWidth = byteWidths[2];
  1151. var entryRanges = streamState.entryRanges;
  1152. while (entryRanges.length > 0) {
  1153. var first = entryRanges[0];
  1154. var n = entryRanges[1];
  1155. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1156. throw new _util.FormatError("Invalid XRef range fields: ".concat(first, ", ").concat(n));
  1157. }
  1158. if (!Number.isInteger(typeFieldWidth) || !Number.isInteger(offsetFieldWidth) || !Number.isInteger(generationFieldWidth)) {
  1159. throw new _util.FormatError("Invalid XRef entry fields length: ".concat(first, ", ").concat(n));
  1160. }
  1161. for (i = streamState.entryNum; i < n; ++i) {
  1162. streamState.entryNum = i;
  1163. streamState.streamPos = stream.pos;
  1164. var type = 0,
  1165. offset = 0,
  1166. generation = 0;
  1167. for (j = 0; j < typeFieldWidth; ++j) {
  1168. type = type << 8 | stream.getByte();
  1169. }
  1170. if (typeFieldWidth === 0) {
  1171. type = 1;
  1172. }
  1173. for (j = 0; j < offsetFieldWidth; ++j) {
  1174. offset = offset << 8 | stream.getByte();
  1175. }
  1176. for (j = 0; j < generationFieldWidth; ++j) {
  1177. generation = generation << 8 | stream.getByte();
  1178. }
  1179. var entry = {};
  1180. entry.offset = offset;
  1181. entry.gen = generation;
  1182. switch (type) {
  1183. case 0:
  1184. entry.free = true;
  1185. break;
  1186. case 1:
  1187. entry.uncompressed = true;
  1188. break;
  1189. case 2:
  1190. break;
  1191. default:
  1192. throw new _util.FormatError("Invalid XRef entry type: ".concat(type));
  1193. }
  1194. if (!this.entries[first + i]) {
  1195. this.entries[first + i] = entry;
  1196. }
  1197. }
  1198. streamState.entryNum = 0;
  1199. streamState.streamPos = stream.pos;
  1200. entryRanges.splice(0, 2);
  1201. }
  1202. },
  1203. indexObjects: function XRef_indexObjects() {
  1204. var TAB = 0x9,
  1205. LF = 0xA,
  1206. CR = 0xD,
  1207. SPACE = 0x20;
  1208. var PERCENT = 0x25,
  1209. LT = 0x3C;
  1210. function readToken(data, offset) {
  1211. var token = '',
  1212. ch = data[offset];
  1213. while (ch !== LF && ch !== CR && ch !== LT) {
  1214. if (++offset >= data.length) {
  1215. break;
  1216. }
  1217. token += String.fromCharCode(ch);
  1218. ch = data[offset];
  1219. }
  1220. return token;
  1221. }
  1222. function skipUntil(data, offset, what) {
  1223. var length = what.length,
  1224. dataLength = data.length;
  1225. var skipped = 0;
  1226. while (offset < dataLength) {
  1227. var i = 0;
  1228. while (i < length && data[offset + i] === what[i]) {
  1229. ++i;
  1230. }
  1231. if (i >= length) {
  1232. break;
  1233. }
  1234. offset++;
  1235. skipped++;
  1236. }
  1237. return skipped;
  1238. }
  1239. var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
  1240. var endobjRegExp = /\bendobj[\b\s]$/;
  1241. var nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s<])$/;
  1242. var CHECK_CONTENT_LENGTH = 25;
  1243. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  1244. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
  1245. var objBytes = new Uint8Array([111, 98, 106]);
  1246. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  1247. this.entries.length = 0;
  1248. var stream = this.stream;
  1249. stream.pos = 0;
  1250. var buffer = stream.getBytes();
  1251. var position = stream.start,
  1252. length = buffer.length;
  1253. var trailers = [],
  1254. xrefStms = [];
  1255. while (position < length) {
  1256. var ch = buffer[position];
  1257. if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
  1258. ++position;
  1259. continue;
  1260. }
  1261. if (ch === PERCENT) {
  1262. do {
  1263. ++position;
  1264. if (position >= length) {
  1265. break;
  1266. }
  1267. ch = buffer[position];
  1268. } while (ch !== LF && ch !== CR);
  1269. continue;
  1270. }
  1271. var token = readToken(buffer, position);
  1272. var m;
  1273. if (token.startsWith('xref') && (token.length === 4 || /\s/.test(token[4]))) {
  1274. position += skipUntil(buffer, position, trailerBytes);
  1275. trailers.push(position);
  1276. position += skipUntil(buffer, position, startxrefBytes);
  1277. } else if (m = objRegExp.exec(token)) {
  1278. var num = m[1] | 0,
  1279. gen = m[2] | 0;
  1280. if (typeof this.entries[num] === 'undefined') {
  1281. this.entries[num] = {
  1282. offset: position - stream.start,
  1283. gen: gen,
  1284. uncompressed: true
  1285. };
  1286. }
  1287. var contentLength = void 0,
  1288. startPos = position + token.length;
  1289. while (startPos < buffer.length) {
  1290. var endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
  1291. contentLength = endPos - position;
  1292. var checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
  1293. var tokenStr = (0, _util.bytesToString)(buffer.subarray(checkPos, endPos));
  1294. if (endobjRegExp.test(tokenStr)) {
  1295. break;
  1296. } else {
  1297. var objToken = nestedObjRegExp.exec(tokenStr);
  1298. if (objToken && objToken[1]) {
  1299. (0, _util.warn)('indexObjects: Found new "obj" inside of another "obj", ' + 'caused by missing "endobj" -- trying to recover.');
  1300. contentLength -= objToken[1].length;
  1301. break;
  1302. }
  1303. }
  1304. startPos = endPos;
  1305. }
  1306. var content = buffer.subarray(position, position + contentLength);
  1307. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  1308. if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
  1309. xrefStms.push(position - stream.start);
  1310. this.xrefstms[position - stream.start] = 1;
  1311. }
  1312. position += contentLength;
  1313. } else if (token.startsWith('trailer') && (token.length === 7 || /\s/.test(token[7]))) {
  1314. trailers.push(position);
  1315. position += skipUntil(buffer, position, startxrefBytes);
  1316. } else {
  1317. position += token.length + 1;
  1318. }
  1319. }
  1320. var i, ii;
  1321. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  1322. this.startXRefQueue.push(xrefStms[i]);
  1323. this.readXRef(true);
  1324. }
  1325. var trailerDict;
  1326. for (i = 0, ii = trailers.length; i < ii; ++i) {
  1327. stream.pos = trailers[i];
  1328. var parser = new _parser.Parser({
  1329. lexer: new _parser.Lexer(stream),
  1330. xref: this,
  1331. allowStreams: true,
  1332. recoveryMode: true
  1333. });
  1334. var obj = parser.getObj();
  1335. if (!(0, _primitives.isCmd)(obj, 'trailer')) {
  1336. continue;
  1337. }
  1338. var dict = parser.getObj();
  1339. if (!(0, _primitives.isDict)(dict)) {
  1340. continue;
  1341. }
  1342. var rootDict = void 0;
  1343. try {
  1344. rootDict = dict.get('Root');
  1345. } catch (ex) {
  1346. if (ex instanceof _core_utils.MissingDataException) {
  1347. throw ex;
  1348. }
  1349. continue;
  1350. }
  1351. if (!(0, _primitives.isDict)(rootDict) || !rootDict.has('Pages')) {
  1352. continue;
  1353. }
  1354. if (dict.has('ID')) {
  1355. return dict;
  1356. }
  1357. trailerDict = dict;
  1358. }
  1359. if (trailerDict) {
  1360. return trailerDict;
  1361. }
  1362. throw new _util.InvalidPDFException('Invalid PDF structure');
  1363. },
  1364. readXRef: function XRef_readXRef(recoveryMode) {
  1365. var stream = this.stream;
  1366. var startXRefParsedCache = Object.create(null);
  1367. try {
  1368. while (this.startXRefQueue.length) {
  1369. var startXRef = this.startXRefQueue[0];
  1370. if (startXRefParsedCache[startXRef]) {
  1371. (0, _util.warn)('readXRef - skipping XRef table since it was already parsed.');
  1372. this.startXRefQueue.shift();
  1373. continue;
  1374. }
  1375. startXRefParsedCache[startXRef] = true;
  1376. stream.pos = startXRef + stream.start;
  1377. var parser = new _parser.Parser({
  1378. lexer: new _parser.Lexer(stream),
  1379. xref: this,
  1380. allowStreams: true
  1381. });
  1382. var obj = parser.getObj();
  1383. var dict;
  1384. if ((0, _primitives.isCmd)(obj, 'xref')) {
  1385. dict = this.processXRefTable(parser);
  1386. if (!this.topDict) {
  1387. this.topDict = dict;
  1388. }
  1389. obj = dict.get('XRefStm');
  1390. if (Number.isInteger(obj)) {
  1391. var pos = obj;
  1392. if (!(pos in this.xrefstms)) {
  1393. this.xrefstms[pos] = 1;
  1394. this.startXRefQueue.push(pos);
  1395. }
  1396. }
  1397. } else if (Number.isInteger(obj)) {
  1398. if (!Number.isInteger(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), 'obj') || !(0, _primitives.isStream)(obj = parser.getObj())) {
  1399. throw new _util.FormatError('Invalid XRef stream');
  1400. }
  1401. dict = this.processXRefStream(obj);
  1402. if (!this.topDict) {
  1403. this.topDict = dict;
  1404. }
  1405. if (!dict) {
  1406. throw new _util.FormatError('Failed to read XRef stream');
  1407. }
  1408. } else {
  1409. throw new _util.FormatError('Invalid XRef stream header');
  1410. }
  1411. obj = dict.get('Prev');
  1412. if (Number.isInteger(obj)) {
  1413. this.startXRefQueue.push(obj);
  1414. } else if ((0, _primitives.isRef)(obj)) {
  1415. this.startXRefQueue.push(obj.num);
  1416. }
  1417. this.startXRefQueue.shift();
  1418. }
  1419. return this.topDict;
  1420. } catch (e) {
  1421. if (e instanceof _core_utils.MissingDataException) {
  1422. throw e;
  1423. }
  1424. (0, _util.info)('(while reading XRef): ' + e);
  1425. }
  1426. if (recoveryMode) {
  1427. return undefined;
  1428. }
  1429. throw new _core_utils.XRefParseException();
  1430. },
  1431. getEntry: function XRef_getEntry(i) {
  1432. var xrefEntry = this.entries[i];
  1433. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  1434. return xrefEntry;
  1435. }
  1436. return null;
  1437. },
  1438. fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
  1439. if (obj instanceof _primitives.Ref) {
  1440. return this.fetch(obj, suppressEncryption);
  1441. }
  1442. return obj;
  1443. },
  1444. fetch: function XRef_fetch(ref, suppressEncryption) {
  1445. if (!(ref instanceof _primitives.Ref)) {
  1446. throw new Error('ref object is not a reference');
  1447. }
  1448. var num = ref.num;
  1449. if (this._cacheMap.has(num)) {
  1450. var cacheEntry = this._cacheMap.get(num);
  1451. if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
  1452. cacheEntry.objId = ref.toString();
  1453. }
  1454. return cacheEntry;
  1455. }
  1456. var xrefEntry = this.getEntry(num);
  1457. if (xrefEntry === null) {
  1458. this._cacheMap.set(num, xrefEntry);
  1459. return xrefEntry;
  1460. }
  1461. if (xrefEntry.uncompressed) {
  1462. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  1463. } else {
  1464. xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
  1465. }
  1466. if ((0, _primitives.isDict)(xrefEntry)) {
  1467. xrefEntry.objId = ref.toString();
  1468. } else if ((0, _primitives.isStream)(xrefEntry)) {
  1469. xrefEntry.dict.objId = ref.toString();
  1470. }
  1471. return xrefEntry;
  1472. },
  1473. fetchUncompressed: function fetchUncompressed(ref, xrefEntry) {
  1474. var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  1475. var gen = ref.gen;
  1476. var num = ref.num;
  1477. if (xrefEntry.gen !== gen) {
  1478. throw new _core_utils.XRefEntryException("Inconsistent generation in XRef: ".concat(ref));
  1479. }
  1480. var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
  1481. var parser = new _parser.Parser({
  1482. lexer: new _parser.Lexer(stream),
  1483. xref: this,
  1484. allowStreams: true
  1485. });
  1486. var obj1 = parser.getObj();
  1487. var obj2 = parser.getObj();
  1488. var obj3 = parser.getObj();
  1489. if (!Number.isInteger(obj1)) {
  1490. obj1 = parseInt(obj1, 10);
  1491. }
  1492. if (!Number.isInteger(obj2)) {
  1493. obj2 = parseInt(obj2, 10);
  1494. }
  1495. if (obj1 !== num || obj2 !== gen || !(obj3 instanceof _primitives.Cmd)) {
  1496. throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
  1497. }
  1498. if (obj3.cmd !== 'obj') {
  1499. if (obj3.cmd.startsWith('obj')) {
  1500. num = parseInt(obj3.cmd.substring(3), 10);
  1501. if (!Number.isNaN(num)) {
  1502. return num;
  1503. }
  1504. }
  1505. throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
  1506. }
  1507. if (this.encrypt && !suppressEncryption) {
  1508. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  1509. } else {
  1510. xrefEntry = parser.getObj();
  1511. }
  1512. if (!(0, _primitives.isStream)(xrefEntry)) {
  1513. this._cacheMap.set(num, xrefEntry);
  1514. }
  1515. return xrefEntry;
  1516. },
  1517. fetchCompressed: function fetchCompressed(ref, xrefEntry) {
  1518. var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  1519. var tableOffset = xrefEntry.offset;
  1520. var stream = this.fetch(_primitives.Ref.get(tableOffset, 0));
  1521. if (!(0, _primitives.isStream)(stream)) {
  1522. throw new _util.FormatError('bad ObjStm stream');
  1523. }
  1524. var first = stream.dict.get('First');
  1525. var n = stream.dict.get('N');
  1526. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1527. throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
  1528. }
  1529. var parser = new _parser.Parser({
  1530. lexer: new _parser.Lexer(stream),
  1531. xref: this,
  1532. allowStreams: true
  1533. });
  1534. var i,
  1535. entries = [],
  1536. num,
  1537. nums = [];
  1538. for (i = 0; i < n; ++i) {
  1539. num = parser.getObj();
  1540. if (!Number.isInteger(num)) {
  1541. throw new _util.FormatError("invalid object number in the ObjStm stream: ".concat(num));
  1542. }
  1543. nums.push(num);
  1544. var offset = parser.getObj();
  1545. if (!Number.isInteger(offset)) {
  1546. throw new _util.FormatError("invalid object offset in the ObjStm stream: ".concat(offset));
  1547. }
  1548. }
  1549. for (i = 0; i < n; ++i) {
  1550. entries.push(parser.getObj());
  1551. if ((0, _primitives.isCmd)(parser.buf1, 'endobj')) {
  1552. parser.shift();
  1553. }
  1554. num = nums[i];
  1555. var entry = this.entries[num];
  1556. if (entry && entry.offset === tableOffset && entry.gen === i) {
  1557. this._cacheMap.set(num, entries[i]);
  1558. }
  1559. }
  1560. xrefEntry = entries[xrefEntry.gen];
  1561. if (xrefEntry === undefined) {
  1562. throw new _core_utils.XRefEntryException("Bad (compressed) XRef entry: ".concat(ref));
  1563. }
  1564. return xrefEntry;
  1565. },
  1566. fetchIfRefAsync: function () {
  1567. var _fetchIfRefAsync = _asyncToGenerator(
  1568. /*#__PURE__*/
  1569. _regenerator["default"].mark(function _callee(obj, suppressEncryption) {
  1570. return _regenerator["default"].wrap(function _callee$(_context) {
  1571. while (1) {
  1572. switch (_context.prev = _context.next) {
  1573. case 0:
  1574. if (!(obj instanceof _primitives.Ref)) {
  1575. _context.next = 2;
  1576. break;
  1577. }
  1578. return _context.abrupt("return", this.fetchAsync(obj, suppressEncryption));
  1579. case 2:
  1580. return _context.abrupt("return", obj);
  1581. case 3:
  1582. case "end":
  1583. return _context.stop();
  1584. }
  1585. }
  1586. }, _callee, this);
  1587. }));
  1588. function fetchIfRefAsync(_x, _x2) {
  1589. return _fetchIfRefAsync.apply(this, arguments);
  1590. }
  1591. return fetchIfRefAsync;
  1592. }(),
  1593. fetchAsync: function () {
  1594. var _fetchAsync = _asyncToGenerator(
  1595. /*#__PURE__*/
  1596. _regenerator["default"].mark(function _callee2(ref, suppressEncryption) {
  1597. return _regenerator["default"].wrap(function _callee2$(_context2) {
  1598. while (1) {
  1599. switch (_context2.prev = _context2.next) {
  1600. case 0:
  1601. _context2.prev = 0;
  1602. return _context2.abrupt("return", this.fetch(ref, suppressEncryption));
  1603. case 4:
  1604. _context2.prev = 4;
  1605. _context2.t0 = _context2["catch"](0);
  1606. if (_context2.t0 instanceof _core_utils.MissingDataException) {
  1607. _context2.next = 8;
  1608. break;
  1609. }
  1610. throw _context2.t0;
  1611. case 8:
  1612. _context2.next = 10;
  1613. return this.pdfManager.requestRange(_context2.t0.begin, _context2.t0.end);
  1614. case 10:
  1615. return _context2.abrupt("return", this.fetchAsync(ref, suppressEncryption));
  1616. case 11:
  1617. case "end":
  1618. return _context2.stop();
  1619. }
  1620. }
  1621. }, _callee2, this, [[0, 4]]);
  1622. }));
  1623. function fetchAsync(_x3, _x4) {
  1624. return _fetchAsync.apply(this, arguments);
  1625. }
  1626. return fetchAsync;
  1627. }(),
  1628. getCatalogObj: function XRef_getCatalogObj() {
  1629. return this.root;
  1630. }
  1631. };
  1632. return XRef;
  1633. }();
  1634. exports.XRef = XRef;
  1635. var NameOrNumberTree =
  1636. /*#__PURE__*/
  1637. function () {
  1638. function NameOrNumberTree(root, xref, type) {
  1639. _classCallCheck(this, NameOrNumberTree);
  1640. if (this.constructor === NameOrNumberTree) {
  1641. (0, _util.unreachable)('Cannot initialize NameOrNumberTree.');
  1642. }
  1643. this.root = root;
  1644. this.xref = xref;
  1645. this._type = type;
  1646. }
  1647. _createClass(NameOrNumberTree, [{
  1648. key: "getAll",
  1649. value: function getAll() {
  1650. var dict = Object.create(null);
  1651. if (!this.root) {
  1652. return dict;
  1653. }
  1654. var xref = this.xref;
  1655. var processed = new _primitives.RefSet();
  1656. processed.put(this.root);
  1657. var queue = [this.root];
  1658. while (queue.length > 0) {
  1659. var obj = xref.fetchIfRef(queue.shift());
  1660. if (!(0, _primitives.isDict)(obj)) {
  1661. continue;
  1662. }
  1663. if (obj.has('Kids')) {
  1664. var kids = obj.get('Kids');
  1665. for (var i = 0, ii = kids.length; i < ii; i++) {
  1666. var kid = kids[i];
  1667. if (processed.has(kid)) {
  1668. throw new _util.FormatError("Duplicate entry in \"".concat(this._type, "\" tree."));
  1669. }
  1670. queue.push(kid);
  1671. processed.put(kid);
  1672. }
  1673. continue;
  1674. }
  1675. var entries = obj.get(this._type);
  1676. if (Array.isArray(entries)) {
  1677. for (var _i2 = 0, _ii = entries.length; _i2 < _ii; _i2 += 2) {
  1678. dict[xref.fetchIfRef(entries[_i2])] = xref.fetchIfRef(entries[_i2 + 1]);
  1679. }
  1680. }
  1681. }
  1682. return dict;
  1683. }
  1684. }, {
  1685. key: "get",
  1686. value: function get(key) {
  1687. if (!this.root) {
  1688. return null;
  1689. }
  1690. var xref = this.xref;
  1691. var kidsOrEntries = xref.fetchIfRef(this.root);
  1692. var loopCount = 0;
  1693. var MAX_LEVELS = 10;
  1694. while (kidsOrEntries.has('Kids')) {
  1695. if (++loopCount > MAX_LEVELS) {
  1696. (0, _util.warn)("Search depth limit reached for \"".concat(this._type, "\" tree."));
  1697. return null;
  1698. }
  1699. var kids = kidsOrEntries.get('Kids');
  1700. if (!Array.isArray(kids)) {
  1701. return null;
  1702. }
  1703. var l = 0,
  1704. r = kids.length - 1;
  1705. while (l <= r) {
  1706. var m = l + r >> 1;
  1707. var kid = xref.fetchIfRef(kids[m]);
  1708. var limits = kid.get('Limits');
  1709. if (key < xref.fetchIfRef(limits[0])) {
  1710. r = m - 1;
  1711. } else if (key > xref.fetchIfRef(limits[1])) {
  1712. l = m + 1;
  1713. } else {
  1714. kidsOrEntries = xref.fetchIfRef(kids[m]);
  1715. break;
  1716. }
  1717. }
  1718. if (l > r) {
  1719. return null;
  1720. }
  1721. }
  1722. var entries = kidsOrEntries.get(this._type);
  1723. if (Array.isArray(entries)) {
  1724. var _l = 0,
  1725. _r = entries.length - 2;
  1726. while (_l <= _r) {
  1727. var tmp = _l + _r >> 1,
  1728. _m = tmp + (tmp & 1);
  1729. var currentKey = xref.fetchIfRef(entries[_m]);
  1730. if (key < currentKey) {
  1731. _r = _m - 2;
  1732. } else if (key > currentKey) {
  1733. _l = _m + 2;
  1734. } else {
  1735. return xref.fetchIfRef(entries[_m + 1]);
  1736. }
  1737. }
  1738. (0, _util.info)("Falling back to an exhaustive search, for key \"".concat(key, "\", ") + "in \"".concat(this._type, "\" tree."));
  1739. for (var _m2 = 0, mm = entries.length; _m2 < mm; _m2 += 2) {
  1740. var _currentKey = xref.fetchIfRef(entries[_m2]);
  1741. if (_currentKey === key) {
  1742. (0, _util.warn)("The \"".concat(key, "\" key was found at an incorrect, ") + "i.e. out-of-order, position in \"".concat(this._type, "\" tree."));
  1743. return xref.fetchIfRef(entries[_m2 + 1]);
  1744. }
  1745. }
  1746. }
  1747. return null;
  1748. }
  1749. }]);
  1750. return NameOrNumberTree;
  1751. }();
  1752. var NameTree =
  1753. /*#__PURE__*/
  1754. function (_NameOrNumberTree) {
  1755. _inherits(NameTree, _NameOrNumberTree);
  1756. function NameTree(root, xref) {
  1757. _classCallCheck(this, NameTree);
  1758. return _possibleConstructorReturn(this, _getPrototypeOf(NameTree).call(this, root, xref, 'Names'));
  1759. }
  1760. return NameTree;
  1761. }(NameOrNumberTree);
  1762. var NumberTree =
  1763. /*#__PURE__*/
  1764. function (_NameOrNumberTree2) {
  1765. _inherits(NumberTree, _NameOrNumberTree2);
  1766. function NumberTree(root, xref) {
  1767. _classCallCheck(this, NumberTree);
  1768. return _possibleConstructorReturn(this, _getPrototypeOf(NumberTree).call(this, root, xref, 'Nums'));
  1769. }
  1770. return NumberTree;
  1771. }(NameOrNumberTree);
  1772. var FileSpec = function FileSpecClosure() {
  1773. function FileSpec(root, xref) {
  1774. if (!root || !(0, _primitives.isDict)(root)) {
  1775. return;
  1776. }
  1777. this.xref = xref;
  1778. this.root = root;
  1779. if (root.has('FS')) {
  1780. this.fs = root.get('FS');
  1781. }
  1782. this.description = root.has('Desc') ? (0, _util.stringToPDFString)(root.get('Desc')) : '';
  1783. if (root.has('RF')) {
  1784. (0, _util.warn)('Related file specifications are not supported');
  1785. }
  1786. this.contentAvailable = true;
  1787. if (!root.has('EF')) {
  1788. this.contentAvailable = false;
  1789. (0, _util.warn)('Non-embedded file specifications are not supported');
  1790. }
  1791. }
  1792. function pickPlatformItem(dict) {
  1793. if (dict.has('UF')) {
  1794. return dict.get('UF');
  1795. } else if (dict.has('F')) {
  1796. return dict.get('F');
  1797. } else if (dict.has('Unix')) {
  1798. return dict.get('Unix');
  1799. } else if (dict.has('Mac')) {
  1800. return dict.get('Mac');
  1801. } else if (dict.has('DOS')) {
  1802. return dict.get('DOS');
  1803. }
  1804. return null;
  1805. }
  1806. FileSpec.prototype = {
  1807. get filename() {
  1808. if (!this._filename && this.root) {
  1809. var filename = pickPlatformItem(this.root) || 'unnamed';
  1810. this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
  1811. }
  1812. return this._filename;
  1813. },
  1814. get content() {
  1815. if (!this.contentAvailable) {
  1816. return null;
  1817. }
  1818. if (!this.contentRef && this.root) {
  1819. this.contentRef = pickPlatformItem(this.root.get('EF'));
  1820. }
  1821. var content = null;
  1822. if (this.contentRef) {
  1823. var xref = this.xref;
  1824. var fileObj = xref.fetchIfRef(this.contentRef);
  1825. if (fileObj && (0, _primitives.isStream)(fileObj)) {
  1826. content = fileObj.getBytes();
  1827. } else {
  1828. (0, _util.warn)('Embedded file specification points to non-existing/invalid ' + 'content');
  1829. }
  1830. } else {
  1831. (0, _util.warn)('Embedded file specification does not have a content');
  1832. }
  1833. return content;
  1834. },
  1835. get serializable() {
  1836. return {
  1837. filename: this.filename,
  1838. content: this.content
  1839. };
  1840. }
  1841. };
  1842. return FileSpec;
  1843. }();
  1844. exports.FileSpec = FileSpec;
  1845. var ObjectLoader = function () {
  1846. function mayHaveChildren(value) {
  1847. return (0, _primitives.isRef)(value) || (0, _primitives.isDict)(value) || Array.isArray(value) || (0, _primitives.isStream)(value);
  1848. }
  1849. function addChildren(node, nodesToVisit) {
  1850. if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
  1851. var dict = (0, _primitives.isDict)(node) ? node : node.dict;
  1852. var dictKeys = dict.getKeys();
  1853. for (var i = 0, ii = dictKeys.length; i < ii; i++) {
  1854. var rawValue = dict.getRaw(dictKeys[i]);
  1855. if (mayHaveChildren(rawValue)) {
  1856. nodesToVisit.push(rawValue);
  1857. }
  1858. }
  1859. } else if (Array.isArray(node)) {
  1860. for (var _i3 = 0, _ii2 = node.length; _i3 < _ii2; _i3++) {
  1861. var value = node[_i3];
  1862. if (mayHaveChildren(value)) {
  1863. nodesToVisit.push(value);
  1864. }
  1865. }
  1866. }
  1867. }
  1868. function ObjectLoader(dict, keys, xref) {
  1869. this.dict = dict;
  1870. this.keys = keys;
  1871. this.xref = xref;
  1872. this.refSet = null;
  1873. this.capability = null;
  1874. }
  1875. ObjectLoader.prototype = {
  1876. load: function load() {
  1877. this.capability = (0, _util.createPromiseCapability)();
  1878. if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
  1879. this.capability.resolve();
  1880. return this.capability.promise;
  1881. }
  1882. var keys = this.keys,
  1883. dict = this.dict;
  1884. this.refSet = new _primitives.RefSet();
  1885. var nodesToVisit = [];
  1886. for (var i = 0, ii = keys.length; i < ii; i++) {
  1887. var rawValue = dict.getRaw(keys[i]);
  1888. if (rawValue !== undefined) {
  1889. nodesToVisit.push(rawValue);
  1890. }
  1891. }
  1892. this._walk(nodesToVisit);
  1893. return this.capability.promise;
  1894. },
  1895. _walk: function _walk(nodesToVisit) {
  1896. var _this3 = this;
  1897. var nodesToRevisit = [];
  1898. var pendingRequests = [];
  1899. while (nodesToVisit.length) {
  1900. var currentNode = nodesToVisit.pop();
  1901. if ((0, _primitives.isRef)(currentNode)) {
  1902. if (this.refSet.has(currentNode)) {
  1903. continue;
  1904. }
  1905. try {
  1906. this.refSet.put(currentNode);
  1907. currentNode = this.xref.fetch(currentNode);
  1908. } catch (ex) {
  1909. if (!(ex instanceof _core_utils.MissingDataException)) {
  1910. throw ex;
  1911. }
  1912. nodesToRevisit.push(currentNode);
  1913. pendingRequests.push({
  1914. begin: ex.begin,
  1915. end: ex.end
  1916. });
  1917. }
  1918. }
  1919. if (currentNode && currentNode.getBaseStreams) {
  1920. var baseStreams = currentNode.getBaseStreams();
  1921. var foundMissingData = false;
  1922. for (var i = 0, ii = baseStreams.length; i < ii; i++) {
  1923. var stream = baseStreams[i];
  1924. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  1925. foundMissingData = true;
  1926. pendingRequests.push({
  1927. begin: stream.start,
  1928. end: stream.end
  1929. });
  1930. }
  1931. }
  1932. if (foundMissingData) {
  1933. nodesToRevisit.push(currentNode);
  1934. }
  1935. }
  1936. addChildren(currentNode, nodesToVisit);
  1937. }
  1938. if (pendingRequests.length) {
  1939. this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
  1940. for (var _i4 = 0, _ii3 = nodesToRevisit.length; _i4 < _ii3; _i4++) {
  1941. var node = nodesToRevisit[_i4];
  1942. if ((0, _primitives.isRef)(node)) {
  1943. _this3.refSet.remove(node);
  1944. }
  1945. }
  1946. _this3._walk(nodesToRevisit);
  1947. }, this.capability.reject);
  1948. return;
  1949. }
  1950. this.refSet = null;
  1951. this.capability.resolve();
  1952. }
  1953. };
  1954. return ObjectLoader;
  1955. }();
  1956. exports.ObjectLoader = ObjectLoader;