Skip to content
Snippets Groups Projects
1.index.js 1.51 MiB
Newer Older
  • Learn to ignore specific revisions
  • 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000
          });
          return (0, _util.shadow)(this, '_parsedAnnotations', parsedAnnotations);
        }
      };
      return Page;
    }();
    var PDFDocument = function PDFDocumentClosure() {
      var FINGERPRINT_FIRST_BYTES = 1024;
      var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
      function PDFDocument(pdfManager, arg) {
        var stream;
        if ((0, _primitives.isStream)(arg)) {
          stream = arg;
        } else if ((0, _util.isArrayBuffer)(arg)) {
          stream = new _stream.Stream(arg);
        } else {
          throw new Error('PDFDocument: Unknown argument type');
        }
        if (stream.length <= 0) {
          throw new Error('PDFDocument: stream must have data');
        }
        this.pdfManager = pdfManager;
        this.stream = stream;
        this.xref = new _obj.XRef(stream, pdfManager);
        var evaluatorOptions = pdfManager.evaluatorOptions;
        this.pdfFunctionFactory = new _function.PDFFunctionFactory({
          xref: this.xref,
          isEvalSupported: evaluatorOptions.isEvalSupported
        });
        this._pagePromises = [];
      }
      function find(stream, needle, limit, backwards) {
        var pos = stream.pos;
        var end = stream.end;
        var strBuf = [];
        if (pos + limit > end) {
          limit = end - pos;
        }
        for (var n = 0; n < limit; ++n) {
          strBuf.push(String.fromCharCode(stream.getByte()));
        }
        var str = strBuf.join('');
        stream.pos = pos;
        var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
        if (index === -1) {
          return false;
        }
        stream.pos += index;
        return true;
      }
      var DocumentInfoValidators = {
        Title: _util.isString,
        Author: _util.isString,
        Subject: _util.isString,
        Keywords: _util.isString,
        Creator: _util.isString,
        Producer: _util.isString,
        CreationDate: _util.isString,
        ModDate: _util.isString,
        Trapped: _primitives.isName
      };
      PDFDocument.prototype = {
        parse: function PDFDocument_parse(recoveryMode) {
          this.setup(recoveryMode);
          var version = this.catalog.catDict.get('Version');
          if ((0, _primitives.isName)(version)) {
            this.pdfFormatVersion = version.name;
          }
          try {
            this.acroForm = this.catalog.catDict.get('AcroForm');
            if (this.acroForm) {
              this.xfa = this.acroForm.get('XFA');
              var fields = this.acroForm.get('Fields');
              if ((!fields || !Array.isArray(fields) || fields.length === 0) && !this.xfa) {
                this.acroForm = null;
              }
            }
          } catch (ex) {
            if (ex instanceof _util.MissingDataException) {
              throw ex;
            }
            (0, _util.info)('Something wrong with AcroForm entry');
            this.acroForm = null;
          }
        },
        get linearization() {
          var linearization = null;
          try {
            linearization = _parser.Linearization.create(this.stream);
          } catch (err) {
            if (err instanceof _util.MissingDataException) {
              throw err;
            }
            (0, _util.info)(err);
          }
          return (0, _util.shadow)(this, 'linearization', linearization);
        },
        get startXRef() {
          var stream = this.stream;
          var startXRef = 0;
          var linearization = this.linearization;
          if (linearization) {
            stream.reset();
            if (find(stream, 'endobj', 1024)) {
              startXRef = stream.pos + 6;
            }
          } else {
            var step = 1024;
            var found = false,
                pos = stream.end;
            while (!found && pos > 0) {
              pos -= step - 'startxref'.length;
              if (pos < 0) {
                pos = 0;
              }
              stream.pos = pos;
              found = find(stream, 'startxref', step, true);
            }
            if (found) {
              stream.skip(9);
              var ch;
              do {
                ch = stream.getByte();
              } while ((0, _util.isSpace)(ch));
              var str = '';
              while (ch >= 0x20 && ch <= 0x39) {
                str += String.fromCharCode(ch);
                ch = stream.getByte();
              }
              startXRef = parseInt(str, 10);
              if (isNaN(startXRef)) {
                startXRef = 0;
              }
            }
          }
          return (0, _util.shadow)(this, 'startXRef', startXRef);
        },
        checkHeader: function PDFDocument_checkHeader() {
          var stream = this.stream;
          stream.reset();
          if (find(stream, '%PDF-', 1024)) {
            stream.moveStart();
            var MAX_VERSION_LENGTH = 12;
            var version = '',
                ch;
            while ((ch = stream.getByte()) > 0x20) {
              if (version.length >= MAX_VERSION_LENGTH) {
                break;
              }
              version += String.fromCharCode(ch);
            }
            if (!this.pdfFormatVersion) {
              this.pdfFormatVersion = version.substring(5);
            }
            return;
          }
        },
        parseStartXRef: function PDFDocument_parseStartXRef() {
          var startXRef = this.startXRef;
          this.xref.setStartXRef(startXRef);
        },
        setup: function PDFDocument_setup(recoveryMode) {
          this.xref.parse(recoveryMode);
          this.catalog = new _obj.Catalog(this.pdfManager, this.xref);
        },
        get numPages() {
          var linearization = this.linearization;
          var num = linearization ? linearization.numPages : this.catalog.numPages;
          return (0, _util.shadow)(this, 'numPages', num);
        },
        get documentInfo() {
          var docInfo = {
            PDFFormatVersion: this.pdfFormatVersion,
            IsLinearized: !!this.linearization,
            IsAcroFormPresent: !!this.acroForm,
            IsXFAPresent: !!this.xfa
          };
          var infoDict = void 0;
          try {
            infoDict = this.xref.trailer.get('Info');
          } catch (err) {
            if (err instanceof _util.MissingDataException) {
              throw err;
            }
            (0, _util.info)('The document information dictionary is invalid.');
          }
          if ((0, _primitives.isDict)(infoDict)) {
            for (var key in DocumentInfoValidators) {
              if (infoDict.has(key)) {
                var value = infoDict.get(key);
                if (DocumentInfoValidators[key](value)) {
                  docInfo[key] = typeof value !== 'string' ? value : (0, _util.stringToPDFString)(value);
                } else {
                  (0, _util.info)('Bad value in document info for "' + key + '"');
                }
              }
            }
          }
          return (0, _util.shadow)(this, 'documentInfo', docInfo);
        },
        get fingerprint() {
          var xref = this.xref,
              hash,
              fileID = '';
          var idArray = xref.trailer.get('ID');
          if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
            hash = (0, _util.stringToBytes)(idArray[0]);
          } else {
            if (this.stream.ensureRange) {
              this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
            }
            hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
          }
          for (var i = 0, n = hash.length; i < n; i++) {
            var hex = hash[i].toString(16);
            fileID += hex.length === 1 ? '0' + hex : hex;
          }
          return (0, _util.shadow)(this, 'fingerprint', fileID);
        },
        _getLinearizationPage: function _getLinearizationPage(pageIndex) {
          var catalog = this.catalog,
              linearization = this.linearization;
    
          (0, _util.assert)(linearization && linearization.pageFirst === pageIndex);
          var ref = new _primitives.Ref(linearization.objectNumberFirst, 0);
          return this.xref.fetchAsync(ref).then(function (obj) {
            if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Type') && obj.has('Contents')) {
              if (ref && !catalog.pageKidsCountCache.has(ref)) {
                catalog.pageKidsCountCache.put(ref, 1);
              }
              return [obj, ref];
            }
            throw new _util.FormatError('The Linearization dictionary doesn\'t point ' + 'to a valid Page dictionary.');
          }).catch(function (reason) {
            (0, _util.info)(reason);
            return catalog.getPageDict(pageIndex);
          });
        },
        getPage: function getPage(pageIndex) {
          var _this5 = this;
    
          if (this._pagePromises[pageIndex] !== undefined) {
            return this._pagePromises[pageIndex];
          }
          var catalog = this.catalog,
              linearization = this.linearization;
    
          var promise = linearization && linearization.pageFirst === pageIndex ? this._getLinearizationPage(pageIndex) : catalog.getPageDict(pageIndex);
          return this._pagePromises[pageIndex] = promise.then(function (_ref10) {
            var _ref11 = _slicedToArray(_ref10, 2),
                pageDict = _ref11[0],
                ref = _ref11[1];
    
            return new Page({
              pdfManager: _this5.pdfManager,
              xref: _this5.xref,
              pageIndex: pageIndex,
              pageDict: pageDict,
              ref: ref,
              fontCache: catalog.fontCache,
              builtInCMapCache: catalog.builtInCMapCache,
              pdfFunctionFactory: _this5.pdfFunctionFactory
            });
          });
        },
    
        cleanup: function PDFDocument_cleanup() {
          return this.catalog.cleanup();
        }
      };
      return PDFDocument;
    }();
    exports.Page = Page;
    exports.PDFDocument = PDFDocument;
    
    /***/ }),
    /* 137 */
    /***/ (function(module, exports, __w_pdfjs_require__) {
    
    "use strict";
    
    
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.FileSpec = exports.XRef = exports.ObjectLoader = exports.Catalog = undefined;
    
    var _regenerator = __w_pdfjs_require__(131);
    
    var _regenerator2 = _interopRequireDefault(_regenerator);
    
    var _slicedToArray = function () { function sliceIterator(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"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
    
    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
    
    var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
    
    var _util = __w_pdfjs_require__(2);
    
    var _primitives = __w_pdfjs_require__(138);
    
    var _parser = __w_pdfjs_require__(139);
    
    var _chunked_stream = __w_pdfjs_require__(135);
    
    var _crypto = __w_pdfjs_require__(150);
    
    var _colorspace = __w_pdfjs_require__(151);
    
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
    
    function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
    
    function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
    
    function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
    
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    
    function fetchDestination(dest) {
      return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
    }
    
    var Catalog = function () {
      function Catalog(pdfManager, xref) {
        _classCallCheck(this, Catalog);
    
        this.pdfManager = pdfManager;
        this.xref = xref;
        this.catDict = xref.getCatalogObj();
        if (!(0, _primitives.isDict)(this.catDict)) {
          throw new _util.FormatError('Catalog object is not a dictionary.');
        }
        this.fontCache = new _primitives.RefSetCache();
        this.builtInCMapCache = new Map();
        this.pageKidsCountCache = new _primitives.RefSetCache();
      }
    
      _createClass(Catalog, [{
        key: '_readDocumentOutline',
        value: function _readDocumentOutline() {
          var obj = this.catDict.get('Outlines');
          if (!(0, _primitives.isDict)(obj)) {
            return null;
          }
          obj = obj.getRaw('First');
          if (!(0, _primitives.isRef)(obj)) {
            return null;
          }
          var root = { items: [] };
          var queue = [{
            obj: obj,
            parent: root
          }];
          var processed = new _primitives.RefSet();
          processed.put(obj);
          var xref = this.xref,
              blackColor = new Uint8ClampedArray(3);
          while (queue.length > 0) {
            var i = queue.shift();
            var outlineDict = xref.fetchIfRef(i.obj);
            if (outlineDict === null) {
              continue;
            }
            if (!outlineDict.has('Title')) {
              throw new _util.FormatError('Invalid outline item encountered.');
            }
            var data = {
              url: null,
              dest: null
            };
            Catalog.parseDestDictionary({
              destDict: outlineDict,
              resultObj: data,
              docBaseUrl: this.pdfManager.docBaseUrl
            });
            var title = outlineDict.get('Title');
            var flags = outlineDict.get('F') || 0;
            var color = outlineDict.getArray('C');
            var rgbColor = blackColor;
            if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
              rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
            }
            var outlineItem = {
              dest: data.dest,
              url: data.url,
              unsafeUrl: data.unsafeUrl,
              newWindow: data.newWindow,
              title: (0, _util.stringToPDFString)(title),
              color: rgbColor,
              count: outlineDict.get('Count'),
              bold: !!(flags & 2),
              italic: !!(flags & 1),
              items: []
            };
            i.parent.items.push(outlineItem);
            obj = outlineDict.getRaw('First');
            if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
              queue.push({
                obj: obj,
                parent: outlineItem
              });
              processed.put(obj);
            }
            obj = outlineDict.getRaw('Next');
            if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
              queue.push({
                obj: obj,
                parent: i.parent
              });
              processed.put(obj);
            }
          }
          return root.items.length > 0 ? root.items : null;
        }
      }, {
        key: '_readPermissions',
        value: function _readPermissions() {
          var encrypt = this.xref.trailer.get('Encrypt');
          if (!(0, _primitives.isDict)(encrypt)) {
            return null;
          }
          var flags = encrypt.get('P');
          if (!(0, _util.isNum)(flags)) {
            return null;
          }
          flags += Math.pow(2, 32);
          var permissions = [];
          for (var key in _util.PermissionFlag) {
            var value = _util.PermissionFlag[key];
            if (flags & value) {
              permissions.push(value);
            }
          }
          return permissions;
        }
      }, {
        key: 'getDestination',
        value: function getDestination(destinationId) {
          var obj = this._readDests();
          if (obj instanceof NameTree || obj instanceof _primitives.Dict) {
            return fetchDestination(obj.get(destinationId) || null);
          }
          return null;
        }
      }, {
        key: '_readDests',
        value: function _readDests() {
          var obj = this.catDict.get('Names');
          if (obj && obj.has('Dests')) {
            return new NameTree(obj.getRaw('Dests'), this.xref);
          } else if (this.catDict.has('Dests')) {
            return this.catDict.get('Dests');
          }
        }
      }, {
        key: '_readPageLabels',
        value: function _readPageLabels() {
          var obj = this.catDict.getRaw('PageLabels');
          if (!obj) {
            return null;
          }
          var pageLabels = new Array(this.numPages);
          var style = null,
              prefix = '';
          var numberTree = new NumberTree(obj, this.xref);
          var nums = numberTree.getAll();
          var currentLabel = '',
              currentIndex = 1;
          for (var i = 0, ii = this.numPages; i < ii; i++) {
            if (i in nums) {
              var labelDict = nums[i];
              if (!(0, _primitives.isDict)(labelDict)) {
                throw new _util.FormatError('PageLabel is not a dictionary.');
              }
              if (labelDict.has('Type') && !(0, _primitives.isName)(labelDict.get('Type'), 'PageLabel')) {
                throw new _util.FormatError('Invalid type in PageLabel dictionary.');
              }
              if (labelDict.has('S')) {
                var s = labelDict.get('S');
                if (!(0, _primitives.isName)(s)) {
                  throw new _util.FormatError('Invalid style in PageLabel dictionary.');
                }
                style = s.name;
              } else {
                style = null;
              }
              if (labelDict.has('P')) {
                var p = labelDict.get('P');
                if (!(0, _util.isString)(p)) {
                  throw new _util.FormatError('Invalid prefix in PageLabel dictionary.');
                }
                prefix = (0, _util.stringToPDFString)(p);
              } else {
                prefix = '';
              }
              if (labelDict.has('St')) {
                var st = labelDict.get('St');
                if (!(Number.isInteger(st) && st >= 1)) {
                  throw new _util.FormatError('Invalid start in PageLabel dictionary.');
                }
                currentIndex = st;
              } else {
                currentIndex = 1;
              }
            }
            switch (style) {
              case 'D':
                currentLabel = currentIndex;
                break;
              case 'R':
              case 'r':
                currentLabel = (0, _util.toRomanNumerals)(currentIndex, style === 'r');
                break;
              case 'A':
              case 'a':
                var LIMIT = 26;
                var A_UPPER_CASE = 0x41,
                    A_LOWER_CASE = 0x61;
                var baseCharCode = style === 'a' ? A_LOWER_CASE : A_UPPER_CASE;
                var letterIndex = currentIndex - 1;
                var character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
                var charBuf = [];
                for (var j = 0, jj = letterIndex / LIMIT | 0; j <= jj; j++) {
                  charBuf.push(character);
                }
                currentLabel = charBuf.join('');
                break;
              default:
                if (style) {
                  throw new _util.FormatError('Invalid style "' + style + '" in PageLabel dictionary.');
                }
                currentLabel = '';
            }
            pageLabels[i] = prefix + currentLabel;
            currentIndex++;
          }
          return pageLabels;
        }
      }, {
        key: 'cleanup',
        value: function cleanup() {
          var _this = this;
    
          this.pageKidsCountCache.clear();
          var promises = [];
          this.fontCache.forEach(function (promise) {
            promises.push(promise);
          });
          return Promise.all(promises).then(function (translatedFonts) {
            for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
              var font = translatedFonts[i].dict;
              delete font.translated;
            }
            _this.fontCache.clear();
            _this.builtInCMapCache.clear();
          });
        }
      }, {
        key: 'getPageDict',
        value: function getPageDict(pageIndex) {
          var capability = (0, _util.createPromiseCapability)();
          var nodesToVisit = [this.catDict.getRaw('Pages')];
          var xref = this.xref,
              pageKidsCountCache = this.pageKidsCountCache;
          var count = void 0,
              currentPageIndex = 0;
          function next() {
            var _loop = function _loop() {
              var currentNode = nodesToVisit.pop();
              if ((0, _primitives.isRef)(currentNode)) {
                count = pageKidsCountCache.get(currentNode);
                if (count > 0 && currentPageIndex + count < pageIndex) {
                  currentPageIndex += count;
                  return 'continue';
                }
                xref.fetchAsync(currentNode).then(function (obj) {
                  if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Kids')) {
                    if (pageIndex === currentPageIndex) {
                      if (currentNode && !pageKidsCountCache.has(currentNode)) {
                        pageKidsCountCache.put(currentNode, 1);
                      }
                      capability.resolve([obj, currentNode]);
                    } else {
                      currentPageIndex++;
                      next();
                    }
                    return;
                  }
                  nodesToVisit.push(obj);
                  next();
                }, capability.reject);
                return {
                  v: void 0
                };
              }
              if (!(0, _primitives.isDict)(currentNode)) {
                capability.reject(new _util.FormatError('Page dictionary kid reference points to wrong type of object.'));
                return {
                  v: void 0
                };
              }
              count = currentNode.get('Count');
              if (Number.isInteger(count) && count >= 0) {
                var objId = currentNode.objId;
                if (objId && !pageKidsCountCache.has(objId)) {
                  pageKidsCountCache.put(objId, count);
                }
                if (currentPageIndex + count <= pageIndex) {
                  currentPageIndex += count;
                  return 'continue';
                }
              }
              var kids = currentNode.get('Kids');
              if (!Array.isArray(kids)) {
                if ((0, _primitives.isName)(currentNode.get('Type'), 'Page') || !currentNode.has('Type') && currentNode.has('Contents')) {
                  if (currentPageIndex === pageIndex) {
                    capability.resolve([currentNode, null]);
                    return {
                      v: void 0
                    };
                  }
                  currentPageIndex++;
                  return 'continue';
                }
                capability.reject(new _util.FormatError('Page dictionary kids object is not an array.'));
                return {
                  v: void 0
                };
              }
              for (var last = kids.length - 1; last >= 0; last--) {
                nodesToVisit.push(kids[last]);
              }
            };
    
            while (nodesToVisit.length) {
              var _ret = _loop();
    
              switch (_ret) {
                case 'continue':
                  continue;
    
                default:
                  if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
              }
            }
            capability.reject(new Error('Page index ' + pageIndex + ' not found.'));
          }
          next();
          return capability.promise;
        }
      }, {
        key: 'getPageIndex',
        value: function getPageIndex(pageRef) {
          var xref = this.xref;
          function pagesBeforeRef(kidRef) {
            var total = 0,
                parentRef = void 0;
            return xref.fetchAsync(kidRef).then(function (node) {
              if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, 'Page') && !((0, _primitives.isDict)(node) && !node.has('Type') && node.has('Contents'))) {
                throw new _util.FormatError('The reference does not point to a /Page dictionary.');
              }
              if (!node) {
                return null;
              }
              if (!(0, _primitives.isDict)(node)) {
                throw new _util.FormatError('Node must be a dictionary.');
              }
              parentRef = node.getRaw('Parent');
              return node.getAsync('Parent');
            }).then(function (parent) {
              if (!parent) {
                return null;
              }
              if (!(0, _primitives.isDict)(parent)) {
                throw new _util.FormatError('Parent must be a dictionary.');
              }
              return parent.getAsync('Kids');
            }).then(function (kids) {
              if (!kids) {
                return null;
              }
              var kidPromises = [];
              var found = false;
              for (var i = 0, ii = kids.length; i < ii; i++) {
                var kid = kids[i];
                if (!(0, _primitives.isRef)(kid)) {
                  throw new _util.FormatError('Kid must be a reference.');
                }
                if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
                  found = true;
                  break;
                }
                kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
                  if (!(0, _primitives.isDict)(kid)) {
                    throw new _util.FormatError('Kid node must be a dictionary.');
                  }
                  if (kid.has('Count')) {
                    total += kid.get('Count');
                  } else {
                    total++;
                  }
                }));
              }
              if (!found) {
                throw new _util.FormatError('Kid reference not found in parent\'s kids.');
              }
              return Promise.all(kidPromises).then(function () {
                return [total, parentRef];
              });
            });
          }
          var total = 0;
          function next(ref) {
            return pagesBeforeRef(ref).then(function (args) {
              if (!args) {
                return total;
              }
    
              var _args = _slicedToArray(args, 2),
                  count = _args[0],
                  parentRef = _args[1];
    
              total += count;
              return next(parentRef);
            });
          }
          return next(pageRef);
        }
      }, {
        key: 'metadata',
        get: function get() {
          var streamRef = this.catDict.getRaw('Metadata');
          if (!(0, _primitives.isRef)(streamRef)) {
            return (0, _util.shadow)(this, 'metadata', null);
          }
          var suppressEncryption = !(this.xref.encrypt && this.xref.encrypt.encryptMetadata);
          var stream = this.xref.fetch(streamRef, suppressEncryption);
          var metadata = void 0;
          if (stream && (0, _primitives.isDict)(stream.dict)) {
            var type = stream.dict.get('Type');
            var subtype = stream.dict.get('Subtype');
            if ((0, _primitives.isName)(type, 'Metadata') && (0, _primitives.isName)(subtype, 'XML')) {
              try {
                metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
              } catch (e) {
                if (e instanceof _util.MissingDataException) {
                  throw e;
                }
                (0, _util.info)('Skipping invalid metadata.');
              }
            }
          }
          return (0, _util.shadow)(this, 'metadata', metadata);
        }
      }, {
        key: 'toplevelPagesDict',
        get: function get() {
          var pagesObj = this.catDict.get('Pages');
          if (!(0, _primitives.isDict)(pagesObj)) {
            throw new _util.FormatError('Invalid top-level pages dictionary.');
          }
          return (0, _util.shadow)(this, 'toplevelPagesDict', pagesObj);
        }
      }, {
        key: 'documentOutline',
        get: function get() {
          var obj = null;
          try {
            obj = this._readDocumentOutline();
          } catch (ex) {
            if (ex instanceof _util.MissingDataException) {
              throw ex;
            }
            (0, _util.warn)('Unable to read document outline.');
          }
          return (0, _util.shadow)(this, 'documentOutline', obj);
        }
      }, {
        key: 'permissions',
        get: function get() {
          var permissions = null;
          try {
            permissions = this._readPermissions();
          } catch (ex) {
            if (ex instanceof _util.MissingDataException) {
              throw ex;
            }
            (0, _util.warn)('Unable to read permissions.');
          }
          return (0, _util.shadow)(this, 'permissions', permissions);
        }
      }, {
        key: 'numPages',
        get: function get() {
          var obj = this.toplevelPagesDict.get('Count');
          if (!Number.isInteger(obj)) {
            throw new _util.FormatError('Page count in top-level pages dictionary is not an integer.');
          }
          return (0, _util.shadow)(this, 'numPages', obj);
        }
      }, {
        key: 'destinations',
        get: function get() {
          var obj = this._readDests(),
              dests = Object.create(null);
          if (obj instanceof NameTree) {
            var names = obj.getAll();
            for (var name in names) {
              dests[name] = fetchDestination(names[name]);
            }
          } else if (obj instanceof _primitives.Dict) {
            obj.forEach(function (key, value) {
              if (value) {
                dests[key] = fetchDestination(value);
              }
            });
          }
          return (0, _util.shadow)(this, 'destinations', dests);
        }
      }, {
        key: 'pageLabels',
        get: function get() {
          var obj = null;
          try {
            obj = this._readPageLabels();
          } catch (ex) {
            if (ex instanceof _util.MissingDataException) {
              throw ex;
            }
            (0, _util.warn)('Unable to read page labels.');
          }
          return (0, _util.shadow)(this, 'pageLabels', obj);
        }
      }, {
        key: 'pageMode',
        get: function get() {
          var obj = this.catDict.get('PageMode');
          var pageMode = 'UseNone';
          if ((0, _primitives.isName)(obj)) {
            switch (obj.name) {
              case 'UseNone':
              case 'UseOutlines':
              case 'UseThumbs':
              case 'FullScreen':
              case 'UseOC':
              case 'UseAttachments':
                pageMode = obj.name;
            }
          }
          return (0, _util.shadow)(this, 'pageMode', pageMode);
        }
      }, {
        key: 'attachments',
        get: function get() {
          var obj = this.catDict.get('Names');
          var attachments = null;
          if (obj && obj.has('EmbeddedFiles')) {
            var nameTree = new NameTree(obj.getRaw('EmbeddedFiles'), this.xref);
            var names = nameTree.getAll();
            for (var name in names) {
              var fs = new FileSpec(names[name], this.xref);
              if (!attachments) {
                attachments = Object.create(null);
              }
              attachments[(0, _util.stringToPDFString)(name)] = fs.serializable;
            }
          }
          return (0, _util.shadow)(this, 'attachments', attachments);
        }
      }, {
        key: 'javaScript',
        get: function get() {
          var obj = this.catDict.get('Names');
          var javaScript = null;
          function appendIfJavaScriptDict(jsDict) {
            var type = jsDict.get('S');
            if (!(0, _primitives.isName)(type, 'JavaScript')) {
              return;
            }
            var js = jsDict.get('JS');
            if ((0, _primitives.isStream)(js)) {
              js = (0, _util.bytesToString)(js.getBytes());
            } else if (!(0, _util.isString)(js)) {
              return;
            }
            if (!javaScript) {
              javaScript = [];
            }
            javaScript.push((0, _util.stringToPDFString)(js));
          }
          if (obj && obj.has('JavaScript')) {
            var nameTree = new NameTree(obj.getRaw('JavaScript'), this.xref);
            var names = nameTree.getAll();
            for (var name in names) {
              var jsDict = names[name];
              if ((0, _primitives.isDict)(jsDict)) {
                appendIfJavaScriptDict(jsDict);
              }
            }
          }
          var openActionDict = this.catDict.get('OpenAction');
          if ((0, _primitives.isDict)(openActionDict, 'Action')) {
            var actionType = openActionDict.get('S');
            if ((0, _primitives.isName)(actionType, 'Named')) {
              var action = openActionDict.get('N');
              if ((0, _primitives.isName)(action, 'Print')) {
                if (!javaScript) {
                  javaScript = [];
                }
                javaScript.push('print({});');
              }
            } else {
              appendIfJavaScriptDict(openActionDict);
            }
          }
          return (0, _util.shadow)(this, 'javaScript', javaScript);
        }
      }], [{
        key: 'parseDestDictionary',
        value: function parseDestDictionary(params) {
          function addDefaultProtocolToUrl(url) {
            if (url.indexOf('www.') === 0) {
              return 'http://' + url;
            }
            return url;
          }
          function tryConvertUrlEncoding(url) {
            try {
              return (0, _util.stringToUTF8String)(url);
            } catch (e) {
              return url;
            }
          }
          var destDict = params.destDict;
          if (!(0, _primitives.isDict)(destDict)) {
            (0, _util.warn)('parseDestDictionary: `destDict` must be a dictionary.');
            return;
          }
          var resultObj = params.resultObj;
          if ((typeof resultObj === 'undefined' ? 'undefined' : _typeof(resultObj)) !== 'object') {
            (0, _util.warn)('parseDestDictionary: `resultObj` must be an object.');
            return;
          }
          var docBaseUrl = params.docBaseUrl || null;
          var action = destDict.get('A'),
              url = void 0,
              dest = void 0;
          if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
            action = destDict.get('Dest');
          }
          if ((0, _primitives.isDict)(action)) {
            var actionType = action.get('S');
            if (!(0, _primitives.isName)(actionType)) {
              (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
              return;
            }
            var actionName = actionType.name;
            switch (actionName) {
              case 'URI':
                url = action.get('URI');
                if ((0, _primitives.isName)(url)) {
                  url = '/' + url.name;
                } else if ((0, _util.isString)(url)) {
                  url = addDefaultProtocolToUrl(url);
                }
                break;
              case 'GoTo':
                dest = action.get('D');
                break;
              case 'Launch':
              case 'GoToR':
                var urlDict = action.get('F');
                if ((0, _primitives.isDict)(urlDict)) {
                  url = urlDict.get('F') || null;
                } else if ((0, _util.isString)(urlDict)) {
                  url = urlDict;
                }
                var remoteDest = action.get('D');
                if (remoteDest) {
                  if ((0, _primitives.isName)(remoteDest)) {
                    remoteDest = remoteDest.name;
                  }
                  if ((0, _util.isString)(url)) {
                    var baseUrl = url.split('#')[0];
                    if ((0, _util.isString)(remoteDest)) {
                      url = baseUrl + '#' + remoteDest;
                    } else if (Array.isArray(remoteDest)) {
                      url = baseUrl + '#' + JSON.stringify(remoteDest);
                    }
                  }
                }
                var newWindow = action.get('NewWindow');
                if ((0, _util.isBool)(newWindow)) {
                  resultObj.newWindow = newWindow;
                }
                break;
              case 'Named':
                var namedAction = action.get('N');
                if ((0, _primitives.isName)(namedAction)) {