2
0

obj.js 64 KB

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