obj.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451
  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) { 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.cache = [];
  988. this.stats = {
  989. streamTypes: [],
  990. fontTypes: []
  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 (!(0, _primitives.isRef)(obj)) {
  1440. return obj;
  1441. }
  1442. return this.fetch(obj, suppressEncryption);
  1443. },
  1444. fetch: function XRef_fetch(ref, suppressEncryption) {
  1445. if (!(0, _primitives.isRef)(ref)) {
  1446. throw new Error('ref object is not a reference');
  1447. }
  1448. var num = ref.num;
  1449. if (num in this.cache) {
  1450. var cacheEntry = this.cache[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. return this.cache[num] = null;
  1459. }
  1460. if (xrefEntry.uncompressed) {
  1461. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  1462. } else {
  1463. xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
  1464. }
  1465. if ((0, _primitives.isDict)(xrefEntry)) {
  1466. xrefEntry.objId = ref.toString();
  1467. } else if ((0, _primitives.isStream)(xrefEntry)) {
  1468. xrefEntry.dict.objId = ref.toString();
  1469. }
  1470. return xrefEntry;
  1471. },
  1472. fetchUncompressed: function fetchUncompressed(ref, xrefEntry) {
  1473. var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  1474. var gen = ref.gen;
  1475. var num = ref.num;
  1476. if (xrefEntry.gen !== gen) {
  1477. throw new _core_utils.XRefEntryException("Inconsistent generation in XRef: ".concat(ref));
  1478. }
  1479. var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
  1480. var parser = new _parser.Parser({
  1481. lexer: new _parser.Lexer(stream),
  1482. xref: this,
  1483. allowStreams: true
  1484. });
  1485. var obj1 = parser.getObj();
  1486. var obj2 = parser.getObj();
  1487. var obj3 = parser.getObj();
  1488. if (!Number.isInteger(obj1)) {
  1489. obj1 = parseInt(obj1, 10);
  1490. }
  1491. if (!Number.isInteger(obj2)) {
  1492. obj2 = parseInt(obj2, 10);
  1493. }
  1494. if (obj1 !== num || obj2 !== gen || !(obj3 instanceof _primitives.Cmd)) {
  1495. throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
  1496. }
  1497. if (obj3.cmd !== 'obj') {
  1498. if (obj3.cmd.startsWith('obj')) {
  1499. num = parseInt(obj3.cmd.substring(3), 10);
  1500. if (!Number.isNaN(num)) {
  1501. return num;
  1502. }
  1503. }
  1504. throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
  1505. }
  1506. if (this.encrypt && !suppressEncryption) {
  1507. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  1508. } else {
  1509. xrefEntry = parser.getObj();
  1510. }
  1511. if (!(0, _primitives.isStream)(xrefEntry)) {
  1512. this.cache[num] = xrefEntry;
  1513. }
  1514. return xrefEntry;
  1515. },
  1516. fetchCompressed: function fetchCompressed(ref, xrefEntry) {
  1517. var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  1518. var tableOffset = xrefEntry.offset;
  1519. var stream = this.fetch(_primitives.Ref.get(tableOffset, 0));
  1520. if (!(0, _primitives.isStream)(stream)) {
  1521. throw new _util.FormatError('bad ObjStm stream');
  1522. }
  1523. var first = stream.dict.get('First');
  1524. var n = stream.dict.get('N');
  1525. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1526. throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
  1527. }
  1528. var parser = new _parser.Parser({
  1529. lexer: new _parser.Lexer(stream),
  1530. xref: this,
  1531. allowStreams: true
  1532. });
  1533. var i,
  1534. entries = [],
  1535. num,
  1536. nums = [];
  1537. for (i = 0; i < n; ++i) {
  1538. num = parser.getObj();
  1539. if (!Number.isInteger(num)) {
  1540. throw new _util.FormatError("invalid object number in the ObjStm stream: ".concat(num));
  1541. }
  1542. nums.push(num);
  1543. var offset = parser.getObj();
  1544. if (!Number.isInteger(offset)) {
  1545. throw new _util.FormatError("invalid object offset in the ObjStm stream: ".concat(offset));
  1546. }
  1547. }
  1548. for (i = 0; i < n; ++i) {
  1549. entries.push(parser.getObj());
  1550. if ((0, _primitives.isCmd)(parser.buf1, 'endobj')) {
  1551. parser.shift();
  1552. }
  1553. num = nums[i];
  1554. var entry = this.entries[num];
  1555. if (entry && entry.offset === tableOffset && entry.gen === i) {
  1556. this.cache[num] = entries[i];
  1557. }
  1558. }
  1559. xrefEntry = entries[xrefEntry.gen];
  1560. if (xrefEntry === undefined) {
  1561. throw new _core_utils.XRefEntryException("Bad (compressed) XRef entry: ".concat(ref));
  1562. }
  1563. return xrefEntry;
  1564. },
  1565. fetchIfRefAsync: function () {
  1566. var _fetchIfRefAsync = _asyncToGenerator(
  1567. /*#__PURE__*/
  1568. _regenerator["default"].mark(function _callee(obj, suppressEncryption) {
  1569. return _regenerator["default"].wrap(function _callee$(_context) {
  1570. while (1) {
  1571. switch (_context.prev = _context.next) {
  1572. case 0:
  1573. if ((0, _primitives.isRef)(obj)) {
  1574. _context.next = 2;
  1575. break;
  1576. }
  1577. return _context.abrupt("return", obj);
  1578. case 2:
  1579. return _context.abrupt("return", this.fetchAsync(obj, suppressEncryption));
  1580. case 3:
  1581. case "end":
  1582. return _context.stop();
  1583. }
  1584. }
  1585. }, _callee, this);
  1586. }));
  1587. function fetchIfRefAsync(_x, _x2) {
  1588. return _fetchIfRefAsync.apply(this, arguments);
  1589. }
  1590. return fetchIfRefAsync;
  1591. }(),
  1592. fetchAsync: function () {
  1593. var _fetchAsync = _asyncToGenerator(
  1594. /*#__PURE__*/
  1595. _regenerator["default"].mark(function _callee2(ref, suppressEncryption) {
  1596. return _regenerator["default"].wrap(function _callee2$(_context2) {
  1597. while (1) {
  1598. switch (_context2.prev = _context2.next) {
  1599. case 0:
  1600. _context2.prev = 0;
  1601. return _context2.abrupt("return", this.fetch(ref, suppressEncryption));
  1602. case 4:
  1603. _context2.prev = 4;
  1604. _context2.t0 = _context2["catch"](0);
  1605. if (_context2.t0 instanceof _core_utils.MissingDataException) {
  1606. _context2.next = 8;
  1607. break;
  1608. }
  1609. throw _context2.t0;
  1610. case 8:
  1611. _context2.next = 10;
  1612. return this.pdfManager.requestRange(_context2.t0.begin, _context2.t0.end);
  1613. case 10:
  1614. return _context2.abrupt("return", this.fetchAsync(ref, suppressEncryption));
  1615. case 11:
  1616. case "end":
  1617. return _context2.stop();
  1618. }
  1619. }
  1620. }, _callee2, this, [[0, 4]]);
  1621. }));
  1622. function fetchAsync(_x3, _x4) {
  1623. return _fetchAsync.apply(this, arguments);
  1624. }
  1625. return fetchAsync;
  1626. }(),
  1627. getCatalogObj: function XRef_getCatalogObj() {
  1628. return this.root;
  1629. }
  1630. };
  1631. return XRef;
  1632. }();
  1633. exports.XRef = XRef;
  1634. var NameOrNumberTree =
  1635. /*#__PURE__*/
  1636. function () {
  1637. function NameOrNumberTree(root, xref, type) {
  1638. _classCallCheck(this, NameOrNumberTree);
  1639. if (this.constructor === NameOrNumberTree) {
  1640. (0, _util.unreachable)('Cannot initialize NameOrNumberTree.');
  1641. }
  1642. this.root = root;
  1643. this.xref = xref;
  1644. this._type = type;
  1645. }
  1646. _createClass(NameOrNumberTree, [{
  1647. key: "getAll",
  1648. value: function getAll() {
  1649. var dict = Object.create(null);
  1650. if (!this.root) {
  1651. return dict;
  1652. }
  1653. var xref = this.xref;
  1654. var processed = new _primitives.RefSet();
  1655. processed.put(this.root);
  1656. var queue = [this.root];
  1657. while (queue.length > 0) {
  1658. var obj = xref.fetchIfRef(queue.shift());
  1659. if (!(0, _primitives.isDict)(obj)) {
  1660. continue;
  1661. }
  1662. if (obj.has('Kids')) {
  1663. var kids = obj.get('Kids');
  1664. for (var i = 0, ii = kids.length; i < ii; i++) {
  1665. var kid = kids[i];
  1666. if (processed.has(kid)) {
  1667. throw new _util.FormatError("Duplicate entry in \"".concat(this._type, "\" tree."));
  1668. }
  1669. queue.push(kid);
  1670. processed.put(kid);
  1671. }
  1672. continue;
  1673. }
  1674. var entries = obj.get(this._type);
  1675. if (Array.isArray(entries)) {
  1676. for (var _i2 = 0, _ii = entries.length; _i2 < _ii; _i2 += 2) {
  1677. dict[xref.fetchIfRef(entries[_i2])] = xref.fetchIfRef(entries[_i2 + 1]);
  1678. }
  1679. }
  1680. }
  1681. return dict;
  1682. }
  1683. }, {
  1684. key: "get",
  1685. value: function get(key) {
  1686. if (!this.root) {
  1687. return null;
  1688. }
  1689. var xref = this.xref;
  1690. var kidsOrEntries = xref.fetchIfRef(this.root);
  1691. var loopCount = 0;
  1692. var MAX_LEVELS = 10;
  1693. while (kidsOrEntries.has('Kids')) {
  1694. if (++loopCount > MAX_LEVELS) {
  1695. (0, _util.warn)("Search depth limit reached for \"".concat(this._type, "\" tree."));
  1696. return null;
  1697. }
  1698. var kids = kidsOrEntries.get('Kids');
  1699. if (!Array.isArray(kids)) {
  1700. return null;
  1701. }
  1702. var l = 0,
  1703. r = kids.length - 1;
  1704. while (l <= r) {
  1705. var m = l + r >> 1;
  1706. var kid = xref.fetchIfRef(kids[m]);
  1707. var limits = kid.get('Limits');
  1708. if (key < xref.fetchIfRef(limits[0])) {
  1709. r = m - 1;
  1710. } else if (key > xref.fetchIfRef(limits[1])) {
  1711. l = m + 1;
  1712. } else {
  1713. kidsOrEntries = xref.fetchIfRef(kids[m]);
  1714. break;
  1715. }
  1716. }
  1717. if (l > r) {
  1718. return null;
  1719. }
  1720. }
  1721. var entries = kidsOrEntries.get(this._type);
  1722. if (Array.isArray(entries)) {
  1723. var _l = 0,
  1724. _r = entries.length - 2;
  1725. while (_l <= _r) {
  1726. var tmp = _l + _r >> 1,
  1727. _m = tmp + (tmp & 1);
  1728. var currentKey = xref.fetchIfRef(entries[_m]);
  1729. if (key < currentKey) {
  1730. _r = _m - 2;
  1731. } else if (key > currentKey) {
  1732. _l = _m + 2;
  1733. } else {
  1734. return xref.fetchIfRef(entries[_m + 1]);
  1735. }
  1736. }
  1737. (0, _util.info)("Falling back to an exhaustive search, for key \"".concat(key, "\", ") + "in \"".concat(this._type, "\" tree."));
  1738. for (var _m2 = 0, mm = entries.length; _m2 < mm; _m2 += 2) {
  1739. var _currentKey = xref.fetchIfRef(entries[_m2]);
  1740. if (_currentKey === key) {
  1741. (0, _util.warn)("The \"".concat(key, "\" key was found at an incorrect, ") + "i.e. out-of-order, position in \"".concat(this._type, "\" tree."));
  1742. return xref.fetchIfRef(entries[_m2 + 1]);
  1743. }
  1744. }
  1745. }
  1746. return null;
  1747. }
  1748. }]);
  1749. return NameOrNumberTree;
  1750. }();
  1751. var NameTree =
  1752. /*#__PURE__*/
  1753. function (_NameOrNumberTree) {
  1754. _inherits(NameTree, _NameOrNumberTree);
  1755. function NameTree(root, xref) {
  1756. _classCallCheck(this, NameTree);
  1757. return _possibleConstructorReturn(this, _getPrototypeOf(NameTree).call(this, root, xref, 'Names'));
  1758. }
  1759. return NameTree;
  1760. }(NameOrNumberTree);
  1761. var NumberTree =
  1762. /*#__PURE__*/
  1763. function (_NameOrNumberTree2) {
  1764. _inherits(NumberTree, _NameOrNumberTree2);
  1765. function NumberTree(root, xref) {
  1766. _classCallCheck(this, NumberTree);
  1767. return _possibleConstructorReturn(this, _getPrototypeOf(NumberTree).call(this, root, xref, 'Nums'));
  1768. }
  1769. return NumberTree;
  1770. }(NameOrNumberTree);
  1771. var FileSpec = function FileSpecClosure() {
  1772. function FileSpec(root, xref) {
  1773. if (!root || !(0, _primitives.isDict)(root)) {
  1774. return;
  1775. }
  1776. this.xref = xref;
  1777. this.root = root;
  1778. if (root.has('FS')) {
  1779. this.fs = root.get('FS');
  1780. }
  1781. this.description = root.has('Desc') ? (0, _util.stringToPDFString)(root.get('Desc')) : '';
  1782. if (root.has('RF')) {
  1783. (0, _util.warn)('Related file specifications are not supported');
  1784. }
  1785. this.contentAvailable = true;
  1786. if (!root.has('EF')) {
  1787. this.contentAvailable = false;
  1788. (0, _util.warn)('Non-embedded file specifications are not supported');
  1789. }
  1790. }
  1791. function pickPlatformItem(dict) {
  1792. if (dict.has('UF')) {
  1793. return dict.get('UF');
  1794. } else if (dict.has('F')) {
  1795. return dict.get('F');
  1796. } else if (dict.has('Unix')) {
  1797. return dict.get('Unix');
  1798. } else if (dict.has('Mac')) {
  1799. return dict.get('Mac');
  1800. } else if (dict.has('DOS')) {
  1801. return dict.get('DOS');
  1802. }
  1803. return null;
  1804. }
  1805. FileSpec.prototype = {
  1806. get filename() {
  1807. if (!this._filename && this.root) {
  1808. var filename = pickPlatformItem(this.root) || 'unnamed';
  1809. this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
  1810. }
  1811. return this._filename;
  1812. },
  1813. get content() {
  1814. if (!this.contentAvailable) {
  1815. return null;
  1816. }
  1817. if (!this.contentRef && this.root) {
  1818. this.contentRef = pickPlatformItem(this.root.get('EF'));
  1819. }
  1820. var content = null;
  1821. if (this.contentRef) {
  1822. var xref = this.xref;
  1823. var fileObj = xref.fetchIfRef(this.contentRef);
  1824. if (fileObj && (0, _primitives.isStream)(fileObj)) {
  1825. content = fileObj.getBytes();
  1826. } else {
  1827. (0, _util.warn)('Embedded file specification points to non-existing/invalid ' + 'content');
  1828. }
  1829. } else {
  1830. (0, _util.warn)('Embedded file specification does not have a content');
  1831. }
  1832. return content;
  1833. },
  1834. get serializable() {
  1835. return {
  1836. filename: this.filename,
  1837. content: this.content
  1838. };
  1839. }
  1840. };
  1841. return FileSpec;
  1842. }();
  1843. exports.FileSpec = FileSpec;
  1844. var ObjectLoader = function () {
  1845. function mayHaveChildren(value) {
  1846. return (0, _primitives.isRef)(value) || (0, _primitives.isDict)(value) || Array.isArray(value) || (0, _primitives.isStream)(value);
  1847. }
  1848. function addChildren(node, nodesToVisit) {
  1849. if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
  1850. var dict = (0, _primitives.isDict)(node) ? node : node.dict;
  1851. var dictKeys = dict.getKeys();
  1852. for (var i = 0, ii = dictKeys.length; i < ii; i++) {
  1853. var rawValue = dict.getRaw(dictKeys[i]);
  1854. if (mayHaveChildren(rawValue)) {
  1855. nodesToVisit.push(rawValue);
  1856. }
  1857. }
  1858. } else if (Array.isArray(node)) {
  1859. for (var _i3 = 0, _ii2 = node.length; _i3 < _ii2; _i3++) {
  1860. var value = node[_i3];
  1861. if (mayHaveChildren(value)) {
  1862. nodesToVisit.push(value);
  1863. }
  1864. }
  1865. }
  1866. }
  1867. function ObjectLoader(dict, keys, xref) {
  1868. this.dict = dict;
  1869. this.keys = keys;
  1870. this.xref = xref;
  1871. this.refSet = null;
  1872. this.capability = null;
  1873. }
  1874. ObjectLoader.prototype = {
  1875. load: function load() {
  1876. this.capability = (0, _util.createPromiseCapability)();
  1877. if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
  1878. this.capability.resolve();
  1879. return this.capability.promise;
  1880. }
  1881. var keys = this.keys,
  1882. dict = this.dict;
  1883. this.refSet = new _primitives.RefSet();
  1884. var nodesToVisit = [];
  1885. for (var i = 0, ii = keys.length; i < ii; i++) {
  1886. var rawValue = dict.getRaw(keys[i]);
  1887. if (rawValue !== undefined) {
  1888. nodesToVisit.push(rawValue);
  1889. }
  1890. }
  1891. this._walk(nodesToVisit);
  1892. return this.capability.promise;
  1893. },
  1894. _walk: function _walk(nodesToVisit) {
  1895. var _this3 = this;
  1896. var nodesToRevisit = [];
  1897. var pendingRequests = [];
  1898. while (nodesToVisit.length) {
  1899. var currentNode = nodesToVisit.pop();
  1900. if ((0, _primitives.isRef)(currentNode)) {
  1901. if (this.refSet.has(currentNode)) {
  1902. continue;
  1903. }
  1904. try {
  1905. this.refSet.put(currentNode);
  1906. currentNode = this.xref.fetch(currentNode);
  1907. } catch (ex) {
  1908. if (!(ex instanceof _core_utils.MissingDataException)) {
  1909. throw ex;
  1910. }
  1911. nodesToRevisit.push(currentNode);
  1912. pendingRequests.push({
  1913. begin: ex.begin,
  1914. end: ex.end
  1915. });
  1916. }
  1917. }
  1918. if (currentNode && currentNode.getBaseStreams) {
  1919. var baseStreams = currentNode.getBaseStreams();
  1920. var foundMissingData = false;
  1921. for (var i = 0, ii = baseStreams.length; i < ii; i++) {
  1922. var stream = baseStreams[i];
  1923. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  1924. foundMissingData = true;
  1925. pendingRequests.push({
  1926. begin: stream.start,
  1927. end: stream.end
  1928. });
  1929. }
  1930. }
  1931. if (foundMissingData) {
  1932. nodesToRevisit.push(currentNode);
  1933. }
  1934. }
  1935. addChildren(currentNode, nodesToVisit);
  1936. }
  1937. if (pendingRequests.length) {
  1938. this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
  1939. for (var _i4 = 0, _ii3 = nodesToRevisit.length; _i4 < _ii3; _i4++) {
  1940. var node = nodesToRevisit[_i4];
  1941. if ((0, _primitives.isRef)(node)) {
  1942. _this3.refSet.remove(node);
  1943. }
  1944. }
  1945. _this3._walk(nodesToRevisit);
  1946. }, this.capability.reject);
  1947. return;
  1948. }
  1949. this.refSet = null;
  1950. this.capability.resolve();
  1951. }
  1952. };
  1953. return ObjectLoader;
  1954. }();
  1955. exports.ObjectLoader = ObjectLoader;