Changeset 104953 in spip-zone for _plugins_/pdfjs


Ignore:
Timestamp:
Jun 23, 2017, 5:05:40 PM (2 years ago)
Author:
kent1@…
Message:

La librairie à jour

Location:
_plugins_/pdfjs
Files:
7 added
179 edited

Legend:

Unmodified
Added
Removed
  • _plugins_/pdfjs/lib/pdfjs/build/pdf.js

    r90280 r104953  
    1 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
    2 /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
    3 /* Copyright 2012 Mozilla Foundation
     1/* Copyright 2017 Mozilla Foundation
    42 *
    53 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1513 * limitations under the License.
    1614 */
    17 /*jshint globalstrict: false */
    18 /* globals PDFJS */
    1915
    20 // Initializing PDFJS global object (if still undefined)
    21 if (typeof PDFJS === 'undefined') {
    22   (typeof window !== 'undefined' ? window : this).PDFJS = {};
    23 }
     16(function webpackUniversalModuleDefinition(root, factory) {
     17        if(typeof exports === 'object' && typeof module === 'object')
     18                module.exports = factory();
     19        else if(typeof define === 'function' && define.amd)
     20                define("pdfjs-dist/build/pdf", [], factory);
     21        else if(typeof exports === 'object')
     22                exports["pdfjs-dist/build/pdf"] = factory();
     23        else
     24                root["pdfjs-dist/build/pdf"] = root.pdfjsDistBuildPdf = factory();
     25})(this, function() {
     26return /******/ (function(modules) { // webpackBootstrap
     27/******/        // The module cache
     28/******/        var installedModules = {};
    2429
    25 PDFJS.version = '1.1.3';
    26 PDFJS.build = '05991e9';
     30/******/        // The require function
     31/******/        function __w_pdfjs_require__(moduleId) {
    2732
    28 (function pdfjsWrapper() {
    29   // Use strict in our context only - users might not want it
    30   'use strict';
     33/******/                // Check if module is in cache
     34/******/                if(installedModules[moduleId])
     35/******/                        return installedModules[moduleId].exports;
    3136
    32 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
    33 /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
    34 /* Copyright 2012 Mozilla Foundation
    35  *
    36  * Licensed under the Apache License, Version 2.0 (the "License");
    37  * you may not use this file except in compliance with the License.
    38  * You may obtain a copy of the License at
    39  *
    40  *     http://www.apache.org/licenses/LICENSE-2.0
    41  *
    42  * Unless required by applicable law or agreed to in writing, software
    43  * distributed under the License is distributed on an "AS IS" BASIS,
    44  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    45  * See the License for the specific language governing permissions and
    46  * limitations under the License.
    47  */
    48 /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
    49            Promise */
     37/******/                // Create a new module (and put it into the cache)
     38/******/                var module = installedModules[moduleId] = {
     39/******/                        i: moduleId,
     40/******/                        l: false,
     41/******/                        exports: {}
     42/******/                };
    5043
    51 'use strict';
     44/******/                // Execute the module function
     45/******/                modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__);
    5246
    53 var globalScope = (typeof window === 'undefined') ? this : window;
     47/******/                // Flag the module as loaded
     48/******/                module.l = true;
    5449
    55 var isWorker = (typeof window === 'undefined');
     50/******/                // Return the exports of the module
     51/******/                return module.exports;
     52/******/        }
    5653
     54
     55/******/        // expose the modules object (__webpack_modules__)
     56/******/        __w_pdfjs_require__.m = modules;
     57
     58/******/        // expose the module cache
     59/******/        __w_pdfjs_require__.c = installedModules;
     60
     61/******/        // identity function for calling harmony imports with the correct context
     62/******/        __w_pdfjs_require__.i = function(value) { return value; };
     63
     64/******/        // define getter function for harmony exports
     65/******/        __w_pdfjs_require__.d = function(exports, name, getter) {
     66/******/                if(!__w_pdfjs_require__.o(exports, name)) {
     67/******/                        Object.defineProperty(exports, name, {
     68/******/                                configurable: false,
     69/******/                                enumerable: true,
     70/******/                                get: getter
     71/******/                        });
     72/******/                }
     73/******/        };
     74
     75/******/        // getDefaultExport function for compatibility with non-harmony modules
     76/******/        __w_pdfjs_require__.n = function(module) {
     77/******/                var getter = module && module.__esModule ?
     78/******/                        function getDefault() { return module['default']; } :
     79/******/                        function getModuleExports() { return module; };
     80/******/                __w_pdfjs_require__.d(getter, 'a', getter);
     81/******/                return getter;
     82/******/        };
     83
     84/******/        // Object.prototype.hasOwnProperty.call
     85/******/        __w_pdfjs_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
     86
     87/******/        // __webpack_public_path__
     88/******/        __w_pdfjs_require__.p = "";
     89
     90/******/        // Load entry module and return exports
     91/******/        return __w_pdfjs_require__(__w_pdfjs_require__.s = 14);
     92/******/ })
     93/************************************************************************/
     94/******/ ([
     95/* 0 */
     96/***/ (function(module, exports, __w_pdfjs_require__) {
     97
     98"use strict";
     99/* WEBPACK VAR INJECTION */(function(global) {
     100
     101var compatibility = __w_pdfjs_require__(13);
     102var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : undefined;
    57103var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
    58 
    59104var TextRenderingMode = {
    60105  FILL: 0,
     
    69114  ADD_TO_PATH_FLAG: 4
    70115};
    71 
    72116var ImageKind = {
    73117  GRAYSCALE_1BPP: 1,
     
    75119  RGBA_32BPP: 3
    76120};
    77 
    78121var AnnotationType = {
    79   WIDGET: 1,
    80   TEXT: 2,
    81   LINK: 3
     122  TEXT: 1,
     123  LINK: 2,
     124  FREETEXT: 3,
     125  LINE: 4,
     126  SQUARE: 5,
     127  CIRCLE: 6,
     128  POLYGON: 7,
     129  POLYLINE: 8,
     130  HIGHLIGHT: 9,
     131  UNDERLINE: 10,
     132  SQUIGGLY: 11,
     133  STRIKEOUT: 12,
     134  STAMP: 13,
     135  CARET: 14,
     136  INK: 15,
     137  POPUP: 16,
     138  FILEATTACHMENT: 17,
     139  SOUND: 18,
     140  MOVIE: 19,
     141  WIDGET: 20,
     142  SCREEN: 21,
     143  PRINTERMARK: 22,
     144  TRAPNET: 23,
     145  WATERMARK: 24,
     146  THREED: 25,
     147  REDACT: 26
    82148};
    83 
     149var AnnotationFlag = {
     150  INVISIBLE: 0x01,
     151  HIDDEN: 0x02,
     152  PRINT: 0x04,
     153  NOZOOM: 0x08,
     154  NOROTATE: 0x10,
     155  NOVIEW: 0x20,
     156  READONLY: 0x40,
     157  LOCKED: 0x80,
     158  TOGGLENOVIEW: 0x100,
     159  LOCKEDCONTENTS: 0x200
     160};
     161var AnnotationFieldFlag = {
     162  READONLY: 0x0000001,
     163  REQUIRED: 0x0000002,
     164  NOEXPORT: 0x0000004,
     165  MULTILINE: 0x0001000,
     166  PASSWORD: 0x0002000,
     167  NOTOGGLETOOFF: 0x0004000,
     168  RADIO: 0x0008000,
     169  PUSHBUTTON: 0x0010000,
     170  COMBO: 0x0020000,
     171  EDIT: 0x0040000,
     172  SORT: 0x0080000,
     173  FILESELECT: 0x0100000,
     174  MULTISELECT: 0x0200000,
     175  DONOTSPELLCHECK: 0x0400000,
     176  DONOTSCROLL: 0x0800000,
     177  COMB: 0x1000000,
     178  RICHTEXT: 0x2000000,
     179  RADIOSINUNISON: 0x2000000,
     180  COMMITONSELCHANGE: 0x4000000
     181};
     182var AnnotationBorderStyleType = {
     183  SOLID: 1,
     184  DASHED: 2,
     185  BEVELED: 3,
     186  INSET: 4,
     187  UNDERLINE: 5
     188};
    84189var StreamType = {
    85190  UNKNOWN: 0,
     
    94199  RL: 9
    95200};
    96 
    97201var FontType = {
    98202  UNKNOWN: 0,
     
    108212  MMTYPE1: 10
    109213};
    110 
    111 // The global PDFJS object exposes the API
    112 // In production, it will be declared outside a global wrapper
    113 // In development, it will be declared here
    114 if (!globalScope.PDFJS) {
    115   globalScope.PDFJS = {};
    116 }
    117 
    118 globalScope.PDFJS.pdfBug = false;
    119 
    120 PDFJS.VERBOSITY_LEVELS = {
     214var VERBOSITY_LEVELS = {
    121215  errors: 0,
    122216  warnings: 1,
    123217  infos: 5
    124218};
    125 
    126 // All the possible operations for an operator list.
    127 var OPS = PDFJS.OPS = {
    128   // Intentionally start from 1 so it is easy to spot bad operators that will be
    129   // 0's.
     219var CMapCompressionType = {
     220  NONE: 0,
     221  BINARY: 1,
     222  STREAM: 2
     223};
     224var OPS = {
    130225  dependency: 1,
    131226  setLineWidth: 2,
     
    220315  constructPath: 91
    221316};
    222 
    223 // A notice for devs. These are good for things that are helpful to devs, such
    224 // as warning that Workers were disabled, which is important to devs but not
    225 // end users.
     317var verbosity = VERBOSITY_LEVELS.warnings;
     318function setVerbosityLevel(level) {
     319  verbosity = level;
     320}
     321function getVerbosityLevel() {
     322  return verbosity;
     323}
    226324function info(msg) {
    227   if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
     325  if (verbosity >= VERBOSITY_LEVELS.infos) {
    228326    console.log('Info: ' + msg);
    229327  }
    230328}
    231 
    232 // Non-fatal warnings.
    233329function warn(msg) {
    234   if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
     330  if (verbosity >= VERBOSITY_LEVELS.warnings) {
    235331    console.log('Warning: ' + msg);
    236332  }
    237333}
    238 
    239 // Fatal errors that should trigger the fallback UI and halt execution by
    240 // throwing an exception.
     334function deprecated(details) {
     335  console.log('Deprecated API usage: ' + details);
     336}
    241337function error(msg) {
    242   // If multiple arguments were passed, pass them all to the log function.
    243   if (arguments.length > 1) {
    244     var logArguments = ['Error:'];
    245     logArguments.push.apply(logArguments, arguments);
    246     console.log.apply(console, logArguments);
    247     // Join the arguments into a single string for the lines below.
    248     msg = [].join.call(arguments, ' ');
    249   } else {
     338  if (verbosity >= VERBOSITY_LEVELS.errors) {
    250339    console.log('Error: ' + msg);
    251   }
    252   console.log(backtrace());
    253   UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
     340    console.log(backtrace());
     341  }
    254342  throw new Error(msg);
    255343}
    256 
    257344function backtrace() {
    258345  try {
     
    262349  }
    263350}
    264 
    265351function assert(cond, msg) {
    266352  if (!cond) {
     
    268354  }
    269355}
    270 
    271 var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
     356var UNSUPPORTED_FEATURES = {
    272357  unknown: 'unknown',
    273358  forms: 'forms',
     
    277362  font: 'font'
    278363};
    279 
    280 var UnsupportedManager = PDFJS.UnsupportedManager =
    281   (function UnsupportedManagerClosure() {
    282   var listeners = [];
    283   return {
    284     listen: function (cb) {
    285       listeners.push(cb);
    286     },
    287     notify: function (featureId) {
    288       warn('Unsupported feature "' + featureId + '"');
    289       for (var i = 0, ii = listeners.length; i < ii; i++) {
    290         listeners[i](featureId);
    291       }
    292     }
    293   };
    294 })();
    295 
    296 // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
    297 // absolute URL, it will be returned as is.
    298 function combineUrl(baseUrl, url) {
    299   if (!url) {
    300     return baseUrl;
    301   }
    302   if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
    303     return url;
    304   }
    305   var i;
    306   if (url.charAt(0) === '/') {
    307     // absolute path
    308     i = baseUrl.indexOf('://');
    309     if (url.charAt(1) === '/') {
    310       ++i;
    311     } else {
    312       i = baseUrl.indexOf('/', i + 3);
    313     }
    314     return baseUrl.substring(0, i) + url;
    315   } else {
    316     // relative path
    317     var pathLength = baseUrl.length;
    318     i = baseUrl.lastIndexOf('#');
    319     pathLength = i >= 0 ? i : pathLength;
    320     i = baseUrl.lastIndexOf('?', pathLength);
    321     pathLength = i >= 0 ? i : pathLength;
    322     var prefixLength = baseUrl.lastIndexOf('/', pathLength);
    323     return baseUrl.substring(0, prefixLength + 1) + url;
    324   }
     364function isSameOrigin(baseUrl, otherUrl) {
     365  try {
     366    var base = new URL(baseUrl);
     367    if (!base.origin || base.origin === 'null') {
     368      return false;
     369    }
     370  } catch (e) {
     371    return false;
     372  }
     373  var other = new URL(otherUrl, base);
     374  return base.origin === other.origin;
    325375}
    326 
    327 // Validates if URL is safe and allowed, e.g. to avoid XSS.
    328 function isValidUrl(url, allowRelative) {
     376function isValidProtocol(url) {
    329377  if (!url) {
    330378    return false;
    331379  }
    332   // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
    333   // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
    334   var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
    335   if (!protocol) {
    336     return allowRelative;
    337   }
    338   protocol = protocol[0].toLowerCase();
    339   switch (protocol) {
    340     case 'http':
    341     case 'https':
    342     case 'ftp':
    343     case 'mailto':
    344     case 'tel':
     380  switch (url.protocol) {
     381    case 'http:':
     382    case 'https:':
     383    case 'ftp:':
     384    case 'mailto:':
     385    case 'tel:':
    345386      return true;
    346387    default:
     
    348389  }
    349390}
    350 PDFJS.isValidUrl = isValidUrl;
    351 
     391function createValidAbsoluteUrl(url, baseUrl) {
     392  if (!url) {
     393    return null;
     394  }
     395  try {
     396    var absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
     397    if (isValidProtocol(absoluteUrl)) {
     398      return absoluteUrl;
     399    }
     400  } catch (ex) {}
     401  return null;
     402}
    352403function shadow(obj, prop, value) {
    353   Object.defineProperty(obj, prop, { value: value,
    354                                      enumerable: true,
    355                                      configurable: true,
    356                                      writable: false });
     404  Object.defineProperty(obj, prop, {
     405    value: value,
     406    enumerable: true,
     407    configurable: true,
     408    writable: false
     409  });
    357410  return value;
    358411}
    359 PDFJS.shadow = shadow;
    360 
    361 var PasswordResponses = PDFJS.PasswordResponses = {
     412function getLookupTableFactory(initializer) {
     413  var lookup;
     414  return function () {
     415    if (initializer) {
     416      lookup = Object.create(null);
     417      initializer(lookup);
     418      initializer = null;
     419    }
     420    return lookup;
     421  };
     422}
     423var PasswordResponses = {
    362424  NEED_PASSWORD: 1,
    363425  INCORRECT_PASSWORD: 2
    364426};
    365 
    366 var PasswordException = (function PasswordExceptionClosure() {
     427var PasswordException = function PasswordExceptionClosure() {
    367428  function PasswordException(msg, code) {
    368429    this.name = 'PasswordException';
     
    370431    this.code = code;
    371432  }
    372 
    373433  PasswordException.prototype = new Error();
    374434  PasswordException.constructor = PasswordException;
    375 
    376435  return PasswordException;
    377 })();
    378 PDFJS.PasswordException = PasswordException;
    379 
    380 var UnknownErrorException = (function UnknownErrorExceptionClosure() {
     436}();
     437var UnknownErrorException = function UnknownErrorExceptionClosure() {
    381438  function UnknownErrorException(msg, details) {
    382439    this.name = 'UnknownErrorException';
     
    384441    this.details = details;
    385442  }
    386 
    387443  UnknownErrorException.prototype = new Error();
    388444  UnknownErrorException.constructor = UnknownErrorException;
    389 
    390445  return UnknownErrorException;
    391 })();
    392 PDFJS.UnknownErrorException = UnknownErrorException;
    393 
    394 var InvalidPDFException = (function InvalidPDFExceptionClosure() {
     446}();
     447var InvalidPDFException = function InvalidPDFExceptionClosure() {
    395448  function InvalidPDFException(msg) {
    396449    this.name = 'InvalidPDFException';
    397450    this.message = msg;
    398451  }
    399 
    400452  InvalidPDFException.prototype = new Error();
    401453  InvalidPDFException.constructor = InvalidPDFException;
    402 
    403454  return InvalidPDFException;
    404 })();
    405 PDFJS.InvalidPDFException = InvalidPDFException;
    406 
    407 var MissingPDFException = (function MissingPDFExceptionClosure() {
     455}();
     456var MissingPDFException = function MissingPDFExceptionClosure() {
    408457  function MissingPDFException(msg) {
    409458    this.name = 'MissingPDFException';
    410459    this.message = msg;
    411460  }
    412 
    413461  MissingPDFException.prototype = new Error();
    414462  MissingPDFException.constructor = MissingPDFException;
    415 
    416463  return MissingPDFException;
    417 })();
    418 PDFJS.MissingPDFException = MissingPDFException;
    419 
    420 var UnexpectedResponseException =
    421     (function UnexpectedResponseExceptionClosure() {
     464}();
     465var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
    422466  function UnexpectedResponseException(msg, status) {
    423467    this.name = 'UnexpectedResponseException';
     
    425469    this.status = status;
    426470  }
    427 
    428471  UnexpectedResponseException.prototype = new Error();
    429472  UnexpectedResponseException.constructor = UnexpectedResponseException;
    430 
    431473  return UnexpectedResponseException;
    432 })();
    433 PDFJS.UnexpectedResponseException = UnexpectedResponseException;
    434 
    435 var NotImplementedException = (function NotImplementedExceptionClosure() {
     474}();
     475var NotImplementedException = function NotImplementedExceptionClosure() {
    436476  function NotImplementedException(msg) {
    437477    this.message = msg;
    438478  }
    439 
    440479  NotImplementedException.prototype = new Error();
    441480  NotImplementedException.prototype.name = 'NotImplementedException';
    442481  NotImplementedException.constructor = NotImplementedException;
    443 
    444482  return NotImplementedException;
    445 })();
    446 
    447 var MissingDataException = (function MissingDataExceptionClosure() {
     483}();
     484var MissingDataException = function MissingDataExceptionClosure() {
    448485  function MissingDataException(begin, end) {
    449486    this.begin = begin;
     
    451488    this.message = 'Missing data [' + begin + ', ' + end + ')';
    452489  }
    453 
    454490  MissingDataException.prototype = new Error();
    455491  MissingDataException.prototype.name = 'MissingDataException';
    456492  MissingDataException.constructor = MissingDataException;
    457 
    458493  return MissingDataException;
    459 })();
    460 
    461 var XRefParseException = (function XRefParseExceptionClosure() {
     494}();
     495var XRefParseException = function XRefParseExceptionClosure() {
    462496  function XRefParseException(msg) {
    463497    this.message = msg;
    464498  }
    465 
    466499  XRefParseException.prototype = new Error();
    467500  XRefParseException.prototype.name = 'XRefParseException';
    468501  XRefParseException.constructor = XRefParseException;
    469 
    470502  return XRefParseException;
    471 })();
    472 
    473 
     503}();
     504var NullCharactersRegExp = /\x00/g;
     505function removeNullCharacters(str) {
     506  if (typeof str !== 'string') {
     507    warn('The argument for removeNullCharacters must be a string.');
     508    return str;
     509  }
     510  return str.replace(NullCharactersRegExp, '');
     511}
    474512function bytesToString(bytes) {
    475   assert(bytes !== null && typeof bytes === 'object' &&
    476          bytes.length !== undefined, 'Invalid argument for bytesToString');
     513  assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
    477514  var length = bytes.length;
    478515  var MAX_ARGUMENT_COUNT = 8192;
     
    488525  return strBuf.join('');
    489526}
    490 
    491527function stringToBytes(str) {
    492528  assert(typeof str === 'string', 'Invalid argument for stringToBytes');
     
    498534  return bytes;
    499535}
    500 
     536function arrayByteLength(arr) {
     537  if (arr.length !== undefined) {
     538    return arr.length;
     539  }
     540  assert(arr.byteLength !== undefined);
     541  return arr.byteLength;
     542}
     543function arraysToBytes(arr) {
     544  if (arr.length === 1 && arr[0] instanceof Uint8Array) {
     545    return arr[0];
     546  }
     547  var resultLength = 0;
     548  var i,
     549      ii = arr.length;
     550  var item, itemLength;
     551  for (i = 0; i < ii; i++) {
     552    item = arr[i];
     553    itemLength = arrayByteLength(item);
     554    resultLength += itemLength;
     555  }
     556  var pos = 0;
     557  var data = new Uint8Array(resultLength);
     558  for (i = 0; i < ii; i++) {
     559    item = arr[i];
     560    if (!(item instanceof Uint8Array)) {
     561      if (typeof item === 'string') {
     562        item = stringToBytes(item);
     563      } else {
     564        item = new Uint8Array(item);
     565      }
     566    }
     567    itemLength = item.byteLength;
     568    data.set(item, pos);
     569    pos += itemLength;
     570  }
     571  return data;
     572}
    501573function string32(value) {
    502   return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
    503                              (value >> 8) & 0xff, value & 0xff);
     574  return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
    504575}
    505 
    506576function log2(x) {
    507   var n = 1, i = 0;
     577  var n = 1,
     578      i = 0;
    508579  while (x > n) {
    509580    n <<= 1;
     
    512583  return i;
    513584}
    514 
    515585function readInt8(data, start) {
    516   return (data[start] << 24) >> 24;
     586  return data[start] << 24 >> 24;
    517587}
    518 
    519588function readUint16(data, offset) {
    520   return (data[offset] << 8) | data[offset + 1];
     589  return data[offset] << 8 | data[offset + 1];
    521590}
    522 
    523591function readUint32(data, offset) {
    524   return ((data[offset] << 24) | (data[offset + 1] << 16) |
    525          (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
     592  return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
    526593}
    527 
    528 // Lazy test the endianness of the platform
    529 // NOTE: This will be 'true' for simulated TypedArrays
    530594function isLittleEndian() {
    531595  var buffer8 = new Uint8Array(2);
    532596  buffer8[0] = 1;
    533597  var buffer16 = new Uint16Array(buffer8.buffer);
    534   return (buffer16[0] === 1);
     598  return buffer16[0] === 1;
    535599}
    536 
    537 Object.defineProperty(PDFJS, 'isLittleEndian', {
    538   configurable: true,
    539   get: function PDFJS_isLittleEndian() {
    540     return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
    541   }
    542 });
    543 
    544   // Lazy test if the userAgant support CanvasTypedArrays
    545 function hasCanvasTypedArrays() {
    546   var canvas = document.createElement('canvas');
    547   canvas.width = canvas.height = 1;
    548   var ctx = canvas.getContext('2d');
    549   var imageData = ctx.createImageData(1, 1);
    550   return (typeof imageData.data.buffer !== 'undefined');
     600function isEvalSupported() {
     601  try {
     602    new Function('');
     603    return true;
     604  } catch (e) {
     605    return false;
     606  }
    551607}
    552 
    553 Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
    554   configurable: true,
    555   get: function PDFJS_hasCanvasTypedArrays() {
    556     return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
    557   }
    558 });
    559 
    560 var Uint32ArrayView = (function Uint32ArrayViewClosure() {
    561 
     608var Uint32ArrayView = function Uint32ArrayViewClosure() {
    562609  function Uint32ArrayView(buffer, length) {
    563610    this.buffer = buffer;
    564611    this.byteLength = buffer.length;
    565     this.length = length === undefined ? (this.byteLength >> 2) : length;
     612    this.length = length === undefined ? this.byteLength >> 2 : length;
    566613    ensureUint32ArrayViewProps(this.length);
    567614  }
    568615  Uint32ArrayView.prototype = Object.create(null);
    569 
    570616  var uint32ArrayViewSetters = 0;
    571617  function createUint32ArrayProp(index) {
    572618    return {
    573619      get: function () {
    574         var buffer = this.buffer, offset = index << 2;
    575         return (buffer[offset] | (buffer[offset + 1] << 8) |
    576           (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
     620        var buffer = this.buffer,
     621            offset = index << 2;
     622        return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
    577623      },
    578624      set: function (value) {
    579         var buffer = this.buffer, offset = index << 2;
     625        var buffer = this.buffer,
     626            offset = index << 2;
    580627        buffer[offset] = value & 255;
    581         buffer[offset + 1] = (value >> 8) & 255;
    582         buffer[offset + 2] = (value >> 16) & 255;
    583         buffer[offset + 3] = (value >>> 24) & 255;
     628        buffer[offset + 1] = value >> 8 & 255;
     629        buffer[offset + 2] = value >> 16 & 255;
     630        buffer[offset + 3] = value >>> 24 & 255;
    584631      }
    585632    };
    586633  }
    587 
    588634  function ensureUint32ArrayViewProps(length) {
    589635    while (uint32ArrayViewSetters < length) {
    590       Object.defineProperty(Uint32ArrayView.prototype,
    591         uint32ArrayViewSetters,
    592         createUint32ArrayProp(uint32ArrayViewSetters));
     636      Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters));
    593637      uint32ArrayViewSetters++;
    594638    }
    595639  }
    596 
    597640  return Uint32ArrayView;
    598 })();
    599 
     641}();
     642exports.Uint32ArrayView = Uint32ArrayView;
    600643var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
    601 
    602 var Util = PDFJS.Util = (function UtilClosure() {
     644var Util = function UtilClosure() {
    603645  function Util() {}
    604 
    605646  var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
    606 
    607   // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
    608   // creating many intermediate strings.
    609647  Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
    610648    rgbBuf[1] = r;
     
    613651    return rgbBuf.join('');
    614652  };
    615 
    616   // Concatenates two transformation matrices together and returns the result.
    617653  Util.transform = function Util_transform(m1, m2) {
    618     return [
    619       m1[0] * m2[0] + m1[2] * m2[1],
    620       m1[1] * m2[0] + m1[3] * m2[1],
    621       m1[0] * m2[2] + m1[2] * m2[3],
    622       m1[1] * m2[2] + m1[3] * m2[3],
    623       m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
    624       m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
    625     ];
     654    return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
    626655  };
    627 
    628   // For 2d affine transforms
    629656  Util.applyTransform = function Util_applyTransform(p, m) {
    630657    var xt = p[0] * m[0] + p[1] * m[2] + m[4];
     
    632659    return [xt, yt];
    633660  };
    634 
    635661  Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
    636662    var d = m[0] * m[3] - m[1] * m[2];
     
    639665    return [xt, yt];
    640666  };
    641 
    642   // Applies the transform to the rectangle and finds the minimum axially
    643   // aligned bounding box.
    644   Util.getAxialAlignedBoundingBox =
    645     function Util_getAxialAlignedBoundingBox(r, m) {
    646 
     667  Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
    647668    var p1 = Util.applyTransform(r, m);
    648669    var p2 = Util.applyTransform(r.slice(2, 4), m);
    649670    var p3 = Util.applyTransform([r[0], r[3]], m);
    650671    var p4 = Util.applyTransform([r[2], r[1]], m);
    651     return [
    652       Math.min(p1[0], p2[0], p3[0], p4[0]),
    653       Math.min(p1[1], p2[1], p3[1], p4[1]),
    654       Math.max(p1[0], p2[0], p3[0], p4[0]),
    655       Math.max(p1[1], p2[1], p3[1], p4[1])
    656     ];
     672    return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
    657673  };
    658 
    659674  Util.inverseTransform = function Util_inverseTransform(m) {
    660675    var d = m[0] * m[3] - m[1] * m[2];
    661     return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
    662       (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
     676    return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
    663677  };
    664 
    665   // Apply a generic 3d matrix M on a 3-vector v:
    666   //   | a b c |   | X |
    667   //   | d e f | x | Y |
    668   //   | g h i |   | Z |
    669   // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
    670   // with v as [X,Y,Z]
    671678  Util.apply3dTransform = function Util_apply3dTransform(m, v) {
    672     return [
    673       m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
    674       m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
    675       m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
    676     ];
     679    return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
    677680  };
    678 
    679   // This calculation uses Singular Value Decomposition.
    680   // The SVD can be represented with formula A = USV. We are interested in the
    681   // matrix S here because it represents the scale values.
    682   Util.singularValueDecompose2dScale =
    683     function Util_singularValueDecompose2dScale(m) {
    684 
     681  Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
    685682    var transpose = [m[0], m[2], m[1], m[3]];
    686 
    687     // Multiply matrix m with its transpose.
    688683    var a = m[0] * transpose[0] + m[1] * transpose[2];
    689684    var b = m[0] * transpose[1] + m[1] * transpose[3];
    690685    var c = m[2] * transpose[0] + m[3] * transpose[2];
    691686    var d = m[2] * transpose[1] + m[3] * transpose[3];
    692 
    693     // Solve the second degree polynomial to get roots.
    694687    var first = (a + d) / 2;
    695688    var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
    696689    var sx = first + second || 1;
    697690    var sy = first - second || 1;
    698 
    699     // Scale values are the square roots of the eigenvalues.
    700691    return [Math.sqrt(sx), Math.sqrt(sy)];
    701692  };
    702 
    703   // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
    704   // For coordinate systems whose origin lies in the bottom-left, this
    705   // means normalization to (BL,TR) ordering. For systems with origin in the
    706   // top-left, this means (TL,BR) ordering.
    707693  Util.normalizeRect = function Util_normalizeRect(rect) {
    708     var r = rect.slice(0); // clone rect
     694    var r = rect.slice(0);
    709695    if (rect[0] > rect[2]) {
    710696      r[0] = rect[2];
     
    717703    return r;
    718704  };
    719 
    720   // Returns a rectangle [x1, y1, x2, y2] corresponding to the
    721   // intersection of rect1 and rect2. If no intersection, returns 'false'
    722   // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
    723705  Util.intersect = function Util_intersect(rect1, rect2) {
    724706    function compare(a, b) {
    725707      return a - b;
    726708    }
    727 
    728     // Order points along the axes
    729709    var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
    730710        orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
    731711        result = [];
    732 
    733712    rect1 = Util.normalizeRect(rect1);
    734713    rect2 = Util.normalizeRect(rect2);
    735 
    736     // X: first and second points belong to different rectangles?
    737     if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
    738         (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
    739       // Intersection must be between second and third points
     714    if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
    740715      result[0] = orderedX[1];
    741716      result[2] = orderedX[2];
     
    743718      return false;
    744719    }
    745 
    746     // Y: first and second points belong to different rectangles?
    747     if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
    748         (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
    749       // Intersection must be between second and third points
     720    if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
    750721      result[1] = orderedY[1];
    751722      result[3] = orderedY[2];
     
    753724      return false;
    754725    }
    755 
    756726    return result;
    757727  };
    758 
    759728  Util.sign = function Util_sign(num) {
    760729    return num < 0 ? -1 : 1;
    761730  };
    762 
     731  var ROMAN_NUMBER_MAP = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
     732  Util.toRoman = function Util_toRoman(number, lowerCase) {
     733    assert(isInt(number) && number > 0, 'The number should be a positive integer.');
     734    var pos,
     735        romanBuf = [];
     736    while (number >= 1000) {
     737      number -= 1000;
     738      romanBuf.push('M');
     739    }
     740    pos = number / 100 | 0;
     741    number %= 100;
     742    romanBuf.push(ROMAN_NUMBER_MAP[pos]);
     743    pos = number / 10 | 0;
     744    number %= 10;
     745    romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
     746    romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
     747    var romanStr = romanBuf.join('');
     748    return lowerCase ? romanStr.toLowerCase() : romanStr;
     749  };
    763750  Util.appendToArray = function Util_appendToArray(arr1, arr2) {
    764751    Array.prototype.push.apply(arr1, arr2);
    765752  };
    766 
    767753  Util.prependToArray = function Util_prependToArray(arr1, arr2) {
    768754    Array.prototype.unshift.apply(arr1, arr2);
    769755  };
    770 
    771756  Util.extendObj = function extendObj(obj1, obj2) {
    772757    for (var key in obj2) {
     
    774759    }
    775760  };
    776 
    777   Util.getInheritableProperty = function Util_getInheritableProperty(dict,
    778                                                                      name) {
     761  Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) {
    779762    while (dict && !dict.has(name)) {
    780763      dict = dict.get('Parent');
     
    783766      return null;
    784767    }
    785     return dict.get(name);
     768    return getArray ? dict.getArray(name) : dict.get(name);
    786769  };
    787 
    788770  Util.inherit = function Util_inherit(sub, base, prototype) {
    789771    sub.prototype = Object.create(base.prototype);
     
    793775    }
    794776  };
    795 
    796777  Util.loadScript = function Util_loadScript(src, callback) {
    797778    var script = document.createElement('script');
     
    799780    script.setAttribute('src', src);
    800781    if (callback) {
    801       script.onload = function() {
     782      script.onload = function () {
    802783        if (!loaded) {
    803784          callback();
     
    808789    document.getElementsByTagName('head')[0].appendChild(script);
    809790  };
    810 
    811791  return Util;
    812 })();
    813 
    814 /**
    815  * PDF page viewport created based on scale, rotation and offset.
    816  * @class
    817  * @alias PDFJS.PageViewport
    818  */
    819 var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
    820   /**
    821    * @constructor
    822    * @private
    823    * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
    824    * @param scale {number} scale of the viewport.
    825    * @param rotation {number} rotations of the viewport in degrees.
    826    * @param offsetX {number} offset X
    827    * @param offsetY {number} offset Y
    828    * @param dontFlip {boolean} if true, axis Y will not be flipped.
    829    */
     792}();
     793var PageViewport = function PageViewportClosure() {
    830794  function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
    831795    this.viewBox = viewBox;
     
    834798    this.offsetX = offsetX;
    835799    this.offsetY = offsetY;
    836 
    837     // creating transform to convert pdf coordinate system to the normal
    838     // canvas like coordinates taking in account scale and rotation
    839800    var centerX = (viewBox[2] + viewBox[0]) / 2;
    840801    var centerY = (viewBox[3] + viewBox[1]) / 2;
     
    844805    switch (rotation) {
    845806      case 180:
    846         rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
     807        rotateA = -1;
     808        rotateB = 0;
     809        rotateC = 0;
     810        rotateD = 1;
    847811        break;
    848812      case 90:
    849         rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
     813        rotateA = 0;
     814        rotateB = 1;
     815        rotateC = 1;
     816        rotateD = 0;
    850817        break;
    851818      case 270:
    852         rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
     819        rotateA = 0;
     820        rotateB = -1;
     821        rotateC = -1;
     822        rotateD = 0;
    853823        break;
    854       //case 0:
    855824      default:
    856         rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
     825        rotateA = 1;
     826        rotateB = 0;
     827        rotateC = 0;
     828        rotateD = -1;
    857829        break;
    858830    }
    859 
    860831    if (dontFlip) {
    861       rotateC = -rotateC; rotateD = -rotateD;
    862     }
    863 
     832      rotateC = -rotateC;
     833      rotateD = -rotateD;
     834    }
    864835    var offsetCanvasX, offsetCanvasY;
    865836    var width, height;
     
    875846      height = Math.abs(viewBox[3] - viewBox[1]) * scale;
    876847    }
    877     // creating transform for the following operations:
    878     // translate(-centerX, -centerY), rotate and flip vertically,
    879     // scale, and translate(offsetCanvasX, offsetCanvasY)
    880     this.transform = [
    881       rotateA * scale,
    882       rotateB * scale,
    883       rotateC * scale,
    884       rotateD * scale,
    885       offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
    886       offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
    887     ];
    888 
     848    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
    889849    this.width = width;
    890850    this.height = height;
    891851    this.fontScale = scale;
    892852  }
    893   PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
    894     /**
    895      * Clones viewport with additional properties.
    896      * @param args {Object} (optional) If specified, may contain the 'scale' or
    897      * 'rotation' properties to override the corresponding properties in
    898      * the cloned viewport.
    899      * @returns {PDFJS.PageViewport} Cloned viewport.
    900      */
     853  PageViewport.prototype = {
    901854    clone: function PageViewPort_clone(args) {
    902855      args = args || {};
    903856      var scale = 'scale' in args ? args.scale : this.scale;
    904857      var rotation = 'rotation' in args ? args.rotation : this.rotation;
    905       return new PageViewport(this.viewBox.slice(), scale, rotation,
    906                               this.offsetX, this.offsetY, args.dontFlip);
    907     },
    908     /**
    909      * Converts PDF point to the viewport coordinates. For examples, useful for
    910      * converting PDF location into canvas pixel coordinates.
    911      * @param x {number} X coordinate.
    912      * @param y {number} Y coordinate.
    913      * @returns {Object} Object that contains 'x' and 'y' properties of the
    914      * point in the viewport coordinate space.
    915      * @see {@link convertToPdfPoint}
    916      * @see {@link convertToViewportRectangle}
    917      */
     858      return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip);
     859    },
    918860    convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
    919861      return Util.applyTransform([x, y], this.transform);
    920862    },
    921     /**
    922      * Converts PDF rectangle to the viewport coordinates.
    923      * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
    924      * @returns {Array} Contains corresponding coordinates of the rectangle
    925      * in the viewport coordinate space.
    926      * @see {@link convertToViewportPoint}
    927      */
    928     convertToViewportRectangle:
    929       function PageViewport_convertToViewportRectangle(rect) {
     863    convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) {
    930864      var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
    931865      var br = Util.applyTransform([rect[2], rect[3]], this.transform);
    932866      return [tl[0], tl[1], br[0], br[1]];
    933867    },
    934     /**
    935      * Converts viewport coordinates to the PDF location. For examples, useful
    936      * for converting canvas pixel location into PDF one.
    937      * @param x {number} X coordinate.
    938      * @param y {number} Y coordinate.
    939      * @returns {Object} Object that contains 'x' and 'y' properties of the
    940      * point in the PDF coordinate space.
    941      * @see {@link convertToViewportPoint}
    942      */
    943868    convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
    944869      return Util.applyInverseTransform([x, y], this.transform);
     
    946871  };
    947872  return PageViewport;
    948 })();
    949 
    950 var PDFStringTranslateTable = [
    951   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    952   0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
    953   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    954   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    955   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    956   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
    957   0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
    958   0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
    959   0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
    960 ];
    961 
     873}();
     874var PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC];
    962875function stringToPDFString(str) {
    963   var i, n = str.length, strBuf = [];
     876  var i,
     877      n = str.length,
     878      strBuf = [];
    964879  if (str[0] === '\xFE' && str[1] === '\xFF') {
    965     // UTF16BE BOM
    966880    for (i = 2; i < n; i += 2) {
    967       strBuf.push(String.fromCharCode(
    968         (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
     881      strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
    969882    }
    970883  } else {
     
    976889  return strBuf.join('');
    977890}
    978 
    979891function stringToUTF8String(str) {
    980892  return decodeURIComponent(escape(str));
    981893}
    982 
     894function utf8StringToString(str) {
     895  return unescape(encodeURIComponent(str));
     896}
    983897function isEmptyObj(obj) {
    984898  for (var key in obj) {
     
    987901  return true;
    988902}
    989 
    990903function isBool(v) {
    991904  return typeof v === 'boolean';
    992905}
    993 
    994906function isInt(v) {
    995   return typeof v === 'number' && ((v | 0) === v);
     907  return typeof v === 'number' && (v | 0) === v;
    996908}
    997 
    998909function isNum(v) {
    999910  return typeof v === 'number';
    1000911}
    1001 
    1002912function isString(v) {
    1003913  return typeof v === 'string';
    1004914}
    1005 
    1006 function isName(v) {
    1007   return v instanceof Name;
    1008 }
    1009 
    1010 function isCmd(v, cmd) {
    1011   return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
    1012 }
    1013 
    1014 function isDict(v, type) {
    1015   if (!(v instanceof Dict)) {
    1016     return false;
    1017   }
    1018   if (!type) {
    1019     return true;
    1020   }
    1021   var dictType = v.get('Type');
    1022   return isName(dictType) && dictType.name === type;
    1023 }
    1024 
    1025915function isArray(v) {
    1026916  return v instanceof Array;
    1027917}
    1028 
    1029 function isStream(v) {
    1030   return typeof v === 'object' && v !== null && v.getBytes !== undefined;
    1031 }
    1032 
    1033918function isArrayBuffer(v) {
    1034919  return typeof v === 'object' && v !== null && v.byteLength !== undefined;
    1035920}
    1036 
    1037 function isRef(v) {
    1038   return v instanceof Ref;
     921function isSpace(ch) {
     922  return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
    1039923}
    1040 
    1041 /**
    1042  * Promise Capability object.
    1043  *
    1044  * @typedef {Object} PromiseCapability
    1045  * @property {Promise} promise - A promise object.
    1046  * @property {function} resolve - Fullfills the promise.
    1047  * @property {function} reject - Rejects the promise.
    1048  */
    1049 
    1050 /**
    1051  * Creates a promise capability object.
    1052  * @alias PDFJS.createPromiseCapability
    1053  *
    1054  * @return {PromiseCapability} A capability object contains:
    1055  * - a Promise, resolve and reject methods.
    1056  */
     924function isNodeJS() {
     925  if (typeof __pdfjsdev_webpack__ === 'undefined') {
     926    return typeof process === 'object' && process + '' === '[object process]';
     927  }
     928  return false;
     929}
    1057930function createPromiseCapability() {
    1058931  var capability = {};
     
    1063936  return capability;
    1064937}
    1065 
    1066 PDFJS.createPromiseCapability = createPromiseCapability;
    1067 
    1068 /**
    1069  * Polyfill for Promises:
    1070  * The following promise implementation tries to generally implement the
    1071  * Promise/A+ spec. Some notable differences from other promise libaries are:
    1072  * - There currently isn't a seperate deferred and promise object.
    1073  * - Unhandled rejections eventually show an error if they aren't handled.
    1074  *
    1075  * Based off of the work in:
    1076  * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
    1077  */
    1078 (function PromiseClosure() {
    1079   if (globalScope.Promise) {
    1080     // Promises existing in the DOM/Worker, checking presence of all/resolve
    1081     if (typeof globalScope.Promise.all !== 'function') {
    1082       globalScope.Promise.all = function (iterable) {
    1083         var count = 0, results = [], resolve, reject;
    1084         var promise = new globalScope.Promise(function (resolve_, reject_) {
    1085           resolve = resolve_;
    1086           reject = reject_;
    1087         });
    1088         iterable.forEach(function (p, i) {
    1089           count++;
    1090           p.then(function (result) {
    1091             results[i] = result;
    1092             count--;
    1093             if (count === 0) {
    1094               resolve(results);
    1095             }
    1096           }, reject);
    1097         });
    1098         if (count === 0) {
    1099           resolve(results);
    1100         }
    1101         return promise;
    1102       };
    1103     }
    1104     if (typeof globalScope.Promise.resolve !== 'function') {
    1105       globalScope.Promise.resolve = function (value) {
    1106         return new globalScope.Promise(function (resolve) { resolve(value); });
    1107       };
    1108     }
    1109     if (typeof globalScope.Promise.reject !== 'function') {
    1110       globalScope.Promise.reject = function (reason) {
    1111         return new globalScope.Promise(function (resolve, reject) {
    1112           reject(reason);
    1113         });
    1114       };
    1115     }
    1116     if (typeof globalScope.Promise.prototype.catch !== 'function') {
    1117       globalScope.Promise.prototype.catch = function (onReject) {
    1118         return globalScope.Promise.prototype.then(undefined, onReject);
    1119       };
    1120     }
    1121     return;
    1122   }
    1123   var STATUS_PENDING = 0;
    1124   var STATUS_RESOLVED = 1;
    1125   var STATUS_REJECTED = 2;
    1126 
    1127   // In an attempt to avoid silent exceptions, unhandled rejections are
    1128   // tracked and if they aren't handled in a certain amount of time an
    1129   // error is logged.
    1130   var REJECTION_TIMEOUT = 500;
    1131 
    1132   var HandlerManager = {
    1133     handlers: [],
    1134     running: false,
    1135     unhandledRejections: [],
    1136     pendingRejectionCheck: false,
    1137 
    1138     scheduleHandlers: function scheduleHandlers(promise) {
    1139       if (promise._status === STATUS_PENDING) {
    1140         return;
    1141       }
    1142 
    1143       this.handlers = this.handlers.concat(promise._handlers);
    1144       promise._handlers = [];
    1145 
    1146       if (this.running) {
    1147         return;
    1148       }
    1149       this.running = true;
    1150 
    1151       setTimeout(this.runHandlers.bind(this), 0);
    1152     },
    1153 
    1154     runHandlers: function runHandlers() {
    1155       var RUN_TIMEOUT = 1; // ms
    1156       var timeoutAt = Date.now() + RUN_TIMEOUT;
    1157       while (this.handlers.length > 0) {
    1158         var handler = this.handlers.shift();
    1159 
    1160         var nextStatus = handler.thisPromise._status;
    1161         var nextValue = handler.thisPromise._value;
    1162 
    1163         try {
    1164           if (nextStatus === STATUS_RESOLVED) {
    1165             if (typeof handler.onResolve === 'function') {
    1166               nextValue = handler.onResolve(nextValue);
    1167             }
    1168           } else if (typeof handler.onReject === 'function') {
    1169               nextValue = handler.onReject(nextValue);
    1170               nextStatus = STATUS_RESOLVED;
    1171 
    1172               if (handler.thisPromise._unhandledRejection) {
    1173                 this.removeUnhandeledRejection(handler.thisPromise);
    1174               }
    1175           }
    1176         } catch (ex) {
    1177           nextStatus = STATUS_REJECTED;
    1178           nextValue = ex;
    1179         }
    1180 
    1181         handler.nextPromise._updateStatus(nextStatus, nextValue);
    1182         if (Date.now() >= timeoutAt) {
    1183           break;
    1184         }
    1185       }
    1186 
    1187       if (this.handlers.length > 0) {
    1188         setTimeout(this.runHandlers.bind(this), 0);
    1189         return;
    1190       }
    1191 
    1192       this.running = false;
    1193     },
    1194 
    1195     addUnhandledRejection: function addUnhandledRejection(promise) {
    1196       this.unhandledRejections.push({
    1197         promise: promise,
    1198         time: Date.now()
    1199       });
    1200       this.scheduleRejectionCheck();
    1201     },
    1202 
    1203     removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
    1204       promise._unhandledRejection = false;
    1205       for (var i = 0; i < this.unhandledRejections.length; i++) {
    1206         if (this.unhandledRejections[i].promise === promise) {
    1207           this.unhandledRejections.splice(i);
    1208           i--;
    1209         }
    1210       }
    1211     },
    1212 
    1213     scheduleRejectionCheck: function scheduleRejectionCheck() {
    1214       if (this.pendingRejectionCheck) {
    1215         return;
    1216       }
    1217       this.pendingRejectionCheck = true;
    1218       setTimeout(function rejectionCheck() {
    1219         this.pendingRejectionCheck = false;
    1220         var now = Date.now();
    1221         for (var i = 0; i < this.unhandledRejections.length; i++) {
    1222           if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
    1223             var unhandled = this.unhandledRejections[i].promise._value;
    1224             var msg = 'Unhandled rejection: ' + unhandled;
    1225             if (unhandled.stack) {
    1226               msg += '\n' + unhandled.stack;
    1227             }
    1228             warn(msg);
    1229             this.unhandledRejections.splice(i);
    1230             i--;
    1231           }
    1232         }
    1233         if (this.unhandledRejections.length) {
    1234           this.scheduleRejectionCheck();
    1235         }
    1236       }.bind(this), REJECTION_TIMEOUT);
    1237     }
    1238   };
    1239 
    1240   function Promise(resolver) {
    1241     this._status = STATUS_PENDING;
    1242     this._handlers = [];
    1243     try {
    1244       resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
    1245     } catch (e) {
    1246       this._reject(e);
    1247     }
    1248   }
    1249   /**
    1250    * Builds a promise that is resolved when all the passed in promises are
    1251    * resolved.
    1252    * @param {array} array of data and/or promises to wait for.
    1253    * @return {Promise} New dependant promise.
    1254    */
    1255   Promise.all = function Promise_all(promises) {
    1256     var resolveAll, rejectAll;
    1257     var deferred = new Promise(function (resolve, reject) {
    1258       resolveAll = resolve;
    1259       rejectAll = reject;
    1260     });
    1261     var unresolved = promises.length;
    1262     var results = [];
    1263     if (unresolved === 0) {
    1264       resolveAll(results);
    1265       return deferred;
    1266     }
    1267     function reject(reason) {
    1268       if (deferred._status === STATUS_REJECTED) {
    1269         return;
    1270       }
    1271       results = [];
    1272       rejectAll(reason);
    1273     }
    1274     for (var i = 0, ii = promises.length; i < ii; ++i) {
    1275       var promise = promises[i];
    1276       var resolve = (function(i) {
    1277         return function(value) {
    1278           if (deferred._status === STATUS_REJECTED) {
    1279             return;
    1280           }
    1281           results[i] = value;
    1282           unresolved--;
    1283           if (unresolved === 0) {
    1284             resolveAll(results);
    1285           }
    1286         };
    1287       })(i);
    1288       if (Promise.isPromise(promise)) {
    1289         promise.then(resolve, reject);
    1290       } else {
    1291         resolve(promise);
    1292       }
    1293     }
    1294     return deferred;
    1295   };
    1296 
    1297   /**
    1298    * Checks if the value is likely a promise (has a 'then' function).
    1299    * @return {boolean} true if value is thenable
    1300    */
    1301   Promise.isPromise = function Promise_isPromise(value) {
    1302     return value && typeof value.then === 'function';
    1303   };
    1304 
    1305   /**
    1306    * Creates resolved promise
    1307    * @param value resolve value
    1308    * @returns {Promise}
    1309    */
    1310   Promise.resolve = function Promise_resolve(value) {
    1311     return new Promise(function (resolve) { resolve(value); });
    1312   };
    1313 
    1314   /**
    1315    * Creates rejected promise
    1316    * @param reason rejection value
    1317    * @returns {Promise}
    1318    */
    1319   Promise.reject = function Promise_reject(reason) {
    1320     return new Promise(function (resolve, reject) { reject(reason); });
    1321   };
    1322 
    1323   Promise.prototype = {
    1324     _status: null,
    1325     _value: null,
    1326     _handlers: null,
    1327     _unhandledRejection: null,
    1328 
    1329     _updateStatus: function Promise__updateStatus(status, value) {
    1330       if (this._status === STATUS_RESOLVED ||
    1331           this._status === STATUS_REJECTED) {
    1332         return;
    1333       }
    1334 
    1335       if (status === STATUS_RESOLVED &&
    1336           Promise.isPromise(value)) {
    1337         value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
    1338                    this._updateStatus.bind(this, STATUS_REJECTED));
    1339         return;
    1340       }
    1341 
    1342       this._status = status;
    1343       this._value = value;
    1344 
    1345       if (status === STATUS_REJECTED && this._handlers.length === 0) {
    1346         this._unhandledRejection = true;
    1347         HandlerManager.addUnhandledRejection(this);
    1348       }
    1349 
    1350       HandlerManager.scheduleHandlers(this);
    1351     },
    1352 
    1353     _resolve: function Promise_resolve(value) {
    1354       this._updateStatus(STATUS_RESOLVED, value);
    1355     },
    1356 
    1357     _reject: function Promise_reject(reason) {
    1358       this._updateStatus(STATUS_REJECTED, reason);
    1359     },
    1360 
    1361     then: function Promise_then(onResolve, onReject) {
    1362       var nextPromise = new Promise(function (resolve, reject) {
    1363         this.resolve = resolve;
    1364         this.reject = reject;
    1365       });
    1366       this._handlers.push({
    1367         thisPromise: this,
    1368         onResolve: onResolve,
    1369         onReject: onReject,
    1370         nextPromise: nextPromise
    1371       });
    1372       HandlerManager.scheduleHandlers(this);
    1373       return nextPromise;
    1374     },
    1375 
    1376     catch: function Promise_catch(onReject) {
    1377       return this.then(undefined, onReject);
    1378     }
    1379   };
    1380 
    1381   globalScope.Promise = Promise;
    1382 })();
    1383 
    1384 var StatTimer = (function StatTimerClosure() {
     938var StatTimer = function StatTimerClosure() {
    1385939  function rpad(str, pad, length) {
    1386940    while (str.length < length) {
     
    1390944  }
    1391945  function StatTimer() {
    1392     this.started = {};
     946    this.started = Object.create(null);
    1393947    this.times = [];
    1394948    this.enabled = true;
     
    1416970        'end': Date.now()
    1417971      });
    1418       // Remove timer from started so it can be called again.
    1419972      delete this.started[name];
    1420973    },
     
    1423976      var times = this.times;
    1424977      var out = '';
    1425       // Find the longest name for padding purposes.
    1426978      var longest = 0;
    1427979      for (i = 0, ii = times.length; i < ii; ++i) {
     
    1440992  };
    1441993  return StatTimer;
    1442 })();
    1443 
    1444 PDFJS.createBlob = function createBlob(data, contentType) {
     994}();
     995var createBlob = function createBlob(data, contentType) {
    1445996  if (typeof Blob !== 'undefined') {
    1446997    return new Blob([data], { type: contentType });
    1447998  }
    1448   // Blob builder is deprecated in FF14 and removed in FF18.
    1449   var bb = new MozBlobBuilder();
    1450   bb.append(data);
    1451   return bb.getBlob(contentType);
     999  warn('The "Blob" constructor is not supported.');
    14521000};
    1453 
    1454 PDFJS.createObjectURL = (function createObjectURLClosure() {
    1455   // Blob/createObjectURL is not available, falling back to data schema.
    1456   var digits =
    1457     'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    1458 
    1459   return function createObjectURL(data, contentType) {
    1460     if (!PDFJS.disableCreateObjectURL &&
    1461         typeof URL !== 'undefined' && URL.createObjectURL) {
    1462       var blob = PDFJS.createBlob(data, contentType);
     1001var createObjectURL = function createObjectURLClosure() {
     1002  var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
     1003  return function createObjectURL(data, contentType, forceDataSchema) {
     1004    if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) {
     1005      var blob = createBlob(data, contentType);
    14631006      return URL.createObjectURL(blob);
    14641007    }
    1465 
    14661008    var buffer = 'data:' + contentType + ';base64,';
    14671009    for (var i = 0, ii = data.length; i < ii; i += 3) {
     
    14691011      var b2 = data[i + 1] & 0xFF;
    14701012      var b3 = data[i + 2] & 0xFF;
    1471       var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
    1472       var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
    1473       var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
     1013      var d1 = b1 >> 2,
     1014          d2 = (b1 & 3) << 4 | b2 >> 4;
     1015      var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
     1016      var d4 = i + 2 < ii ? b3 & 0x3F : 64;
    14741017      buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
    14751018    }
    14761019    return buffer;
    14771020  };
    1478 })();
    1479 
    1480 function MessageHandler(name, comObj) {
    1481   this.name = name;
     1021}();
     1022function MessageHandler(sourceName, targetName, comObj) {
     1023  this.sourceName = sourceName;
     1024  this.targetName = targetName;
    14821025  this.comObj = comObj;
    14831026  this.callbackIndex = 1;
    14841027  this.postMessageTransfers = true;
    1485   var callbacksCapabilities = this.callbacksCapabilities = {};
    1486   var ah = this.actionHandler = {};
    1487 
    1488   ah['console_log'] = [function ahConsoleLog(data) {
    1489     console.log.apply(console, data);
    1490   }];
    1491   ah['console_error'] = [function ahConsoleError(data) {
    1492     console.error.apply(console, data);
    1493   }];
    1494   ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
    1495     UnsupportedManager.notify(data);
    1496   }];
    1497 
    1498   comObj.onmessage = function messageHandlerComObjOnMessage(event) {
     1028  var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
     1029  var ah = this.actionHandler = Object.create(null);
     1030  this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
    14991031    var data = event.data;
     1032    if (data.targetName !== this.sourceName) {
     1033      return;
     1034    }
    15001035    if (data.isReply) {
    15011036      var callbackId = data.callbackId;
     
    15141049      var action = ah[data.action];
    15151050      if (data.callbackId) {
     1051        var sourceName = this.sourceName;
     1052        var targetName = data.sourceName;
    15161053        Promise.resolve().then(function () {
    15171054          return action[0].call(action[1], data.data);
    15181055        }).then(function (result) {
    15191056          comObj.postMessage({
     1057            sourceName: sourceName,
     1058            targetName: targetName,
    15201059            isReply: true,
    15211060            callbackId: data.callbackId,
     
    15231062          });
    15241063        }, function (reason) {
     1064          if (reason instanceof Error) {
     1065            reason = reason + '';
     1066          }
    15251067          comObj.postMessage({
     1068            sourceName: sourceName,
     1069            targetName: targetName,
    15261070            isReply: true,
    15271071            callbackId: data.callbackId,
     
    15351079      error('Unknown action from worker: ' + data.action);
    15361080    }
    1537   };
     1081  }.bind(this);
     1082  comObj.addEventListener('message', this._onComObjOnMessage);
    15381083}
    1539 
    15401084MessageHandler.prototype = {
    15411085  on: function messageHandlerOn(actionName, handler, scope) {
     
    15461090    ah[actionName] = [handler, scope];
    15471091  },
    1548   /**
    1549    * Sends a message to the comObj to invoke the action with the supplied data.
    1550    * @param {String} actionName Action to call.
    1551    * @param {JSON} data JSON data to send.
    1552    * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
    1553    */
    15541092  send: function messageHandlerSend(actionName, data, transfers) {
    15551093    var message = {
     1094      sourceName: this.sourceName,
     1095      targetName: this.targetName,
    15561096      action: actionName,
    15571097      data: data
     
    15591099    this.postMessage(message, transfers);
    15601100  },
    1561   /**
    1562    * Sends a message to the comObj to invoke the action with the supplied data.
    1563    * Expects that other side will callback with the response.
    1564    * @param {String} actionName Action to call.
    1565    * @param {JSON} data JSON data to send.
    1566    * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
    1567    * @returns {Promise} Promise to be resolved with response data.
    1568    */
    1569   sendWithPromise:
    1570     function messageHandlerSendWithPromise(actionName, data, transfers) {
     1101  sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) {
    15711102    var callbackId = this.callbackIndex++;
    15721103    var message = {
     1104      sourceName: this.sourceName,
     1105      targetName: this.targetName,
    15731106      action: actionName,
    15741107      data: data,
     
    15841117    return capability.promise;
    15851118  },
    1586   /**
    1587    * Sends raw message to the comObj.
    1588    * @private
    1589    * @param message {Object} Raw message.
    1590    * @param transfers List of transfers/ArrayBuffers, or undefined.
    1591    */
    15921119  postMessage: function (message, transfers) {
    15931120    if (transfers && this.postMessageTransfers) {
     
    15961123      this.comObj.postMessage(message);
    15971124    }
     1125  },
     1126  destroy: function () {
     1127    this.comObj.removeEventListener('message', this._onComObjOnMessage);
    15981128  }
    15991129};
    1600 
    16011130function loadJpegStream(id, imageUrl, objs) {
    16021131  var img = new Image();
    1603   img.onload = (function loadJpegStream_onloadClosure() {
     1132  img.onload = function loadJpegStream_onloadClosure() {
    16041133    objs.resolve(id, img);
    1605   });
    1606   img.onerror = (function loadJpegStream_onerrorClosure() {
     1134  };
     1135  img.onerror = function loadJpegStream_onerrorClosure() {
    16071136    objs.resolve(id, null);
    16081137    warn('Error during JPEG image loading');
    1609   });
     1138  };
    16101139  img.src = imageUrl;
    16111140}
     1141exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
     1142exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
     1143exports.OPS = OPS;
     1144exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
     1145exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
     1146exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
     1147exports.AnnotationFieldFlag = AnnotationFieldFlag;
     1148exports.AnnotationFlag = AnnotationFlag;
     1149exports.AnnotationType = AnnotationType;
     1150exports.FontType = FontType;
     1151exports.ImageKind = ImageKind;
     1152exports.CMapCompressionType = CMapCompressionType;
     1153exports.InvalidPDFException = InvalidPDFException;
     1154exports.MessageHandler = MessageHandler;
     1155exports.MissingDataException = MissingDataException;
     1156exports.MissingPDFException = MissingPDFException;
     1157exports.NotImplementedException = NotImplementedException;
     1158exports.PageViewport = PageViewport;
     1159exports.PasswordException = PasswordException;
     1160exports.PasswordResponses = PasswordResponses;
     1161exports.StatTimer = StatTimer;
     1162exports.StreamType = StreamType;
     1163exports.TextRenderingMode = TextRenderingMode;
     1164exports.UnexpectedResponseException = UnexpectedResponseException;
     1165exports.UnknownErrorException = UnknownErrorException;
     1166exports.Util = Util;
     1167exports.XRefParseException = XRefParseException;
     1168exports.arrayByteLength = arrayByteLength;
     1169exports.arraysToBytes = arraysToBytes;
     1170exports.assert = assert;
     1171exports.bytesToString = bytesToString;
     1172exports.createBlob = createBlob;
     1173exports.createPromiseCapability = createPromiseCapability;
     1174exports.createObjectURL = createObjectURL;
     1175exports.deprecated = deprecated;
     1176exports.error = error;
     1177exports.getLookupTableFactory = getLookupTableFactory;
     1178exports.getVerbosityLevel = getVerbosityLevel;
     1179exports.globalScope = globalScope;
     1180exports.info = info;
     1181exports.isArray = isArray;
     1182exports.isArrayBuffer = isArrayBuffer;
     1183exports.isBool = isBool;
     1184exports.isEmptyObj = isEmptyObj;
     1185exports.isInt = isInt;
     1186exports.isNum = isNum;
     1187exports.isString = isString;
     1188exports.isSpace = isSpace;
     1189exports.isNodeJS = isNodeJS;
     1190exports.isSameOrigin = isSameOrigin;
     1191exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
     1192exports.isLittleEndian = isLittleEndian;
     1193exports.isEvalSupported = isEvalSupported;
     1194exports.loadJpegStream = loadJpegStream;
     1195exports.log2 = log2;
     1196exports.readInt8 = readInt8;
     1197exports.readUint16 = readUint16;
     1198exports.readUint32 = readUint32;
     1199exports.removeNullCharacters = removeNullCharacters;
     1200exports.setVerbosityLevel = setVerbosityLevel;
     1201exports.shadow = shadow;
     1202exports.string32 = string32;
     1203exports.stringToBytes = stringToBytes;
     1204exports.stringToPDFString = stringToPDFString;
     1205exports.stringToUTF8String = stringToUTF8String;
     1206exports.utf8StringToString = utf8StringToString;
     1207exports.warn = warn;
     1208/* WEBPACK VAR INJECTION */}.call(exports, __w_pdfjs_require__(6)))
     1209
     1210/***/ }),
     1211/* 1 */
     1212/***/ (function(module, exports, __w_pdfjs_require__) {
     1213
     1214"use strict";
    16121215
    16131216
    1614 /**
    1615  * The maximum allowed image size in total pixels e.g. width * height. Images
    1616  * above this value will not be drawn. Use -1 for no limit.
    1617  * @var {number}
    1618  */
    1619 PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
    1620                       -1 : PDFJS.maxImageSize);
     1217var sharedUtil = __w_pdfjs_require__(0);
     1218var assert = sharedUtil.assert;
     1219var removeNullCharacters = sharedUtil.removeNullCharacters;
     1220var warn = sharedUtil.warn;
     1221var deprecated = sharedUtil.deprecated;
     1222var createValidAbsoluteUrl = sharedUtil.createValidAbsoluteUrl;
     1223var stringToBytes = sharedUtil.stringToBytes;
     1224var CMapCompressionType = sharedUtil.CMapCompressionType;
     1225var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
     1226function DOMCanvasFactory() {}
     1227DOMCanvasFactory.prototype = {
     1228  create: function DOMCanvasFactory_create(width, height) {
     1229    assert(width > 0 && height > 0, 'invalid canvas size');
     1230    var canvas = document.createElement('canvas');
     1231    var context = canvas.getContext('2d');
     1232    canvas.width = width;
     1233    canvas.height = height;
     1234    return {
     1235      canvas: canvas,
     1236      context: context
     1237    };
     1238  },
     1239  reset: function DOMCanvasFactory_reset(canvasAndContextPair, width, height) {
     1240    assert(canvasAndContextPair.canvas, 'canvas is not specified');
     1241    assert(width > 0 && height > 0, 'invalid canvas size');
     1242    canvasAndContextPair.canvas.width = width;
     1243    canvasAndContextPair.canvas.height = height;
     1244  },
     1245  destroy: function DOMCanvasFactory_destroy(canvasAndContextPair) {
     1246    assert(canvasAndContextPair.canvas, 'canvas is not specified');
     1247    canvasAndContextPair.canvas.width = 0;
     1248    canvasAndContextPair.canvas.height = 0;
     1249    canvasAndContextPair.canvas = null;
     1250    canvasAndContextPair.context = null;
     1251  }
     1252};
     1253var DOMCMapReaderFactory = function DOMCMapReaderFactoryClosure() {
     1254  function DOMCMapReaderFactory(params) {
     1255    this.baseUrl = params.baseUrl || null;
     1256    this.isCompressed = params.isCompressed || false;
     1257  }
     1258  DOMCMapReaderFactory.prototype = {
     1259    fetch: function (params) {
     1260      var name = params.name;
     1261      if (!name) {
     1262        return Promise.reject(new Error('CMap name must be specified.'));
     1263      }
     1264      return new Promise(function (resolve, reject) {
     1265        var url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');
     1266        var request = new XMLHttpRequest();
     1267        request.open('GET', url, true);
     1268        if (this.isCompressed) {
     1269          request.responseType = 'arraybuffer';
     1270        }
     1271        request.onreadystatechange = function () {
     1272          if (request.readyState !== XMLHttpRequest.DONE) {
     1273            return;
     1274          }
     1275          if (request.status === 200 || request.status === 0) {
     1276            var data;
     1277            if (this.isCompressed && request.response) {
     1278              data = new Uint8Array(request.response);
     1279            } else if (!this.isCompressed && request.responseText) {
     1280              data = stringToBytes(request.responseText);
     1281            }
     1282            if (data) {
     1283              resolve({
     1284                cMapData: data,
     1285                compressionType: this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE
     1286              });
     1287              return;
     1288            }
     1289          }
     1290          reject(new Error('Unable to load ' + (this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url));
     1291        }.bind(this);
     1292        request.send(null);
     1293      }.bind(this));
     1294    }
     1295  };
     1296  return DOMCMapReaderFactory;
     1297}();
     1298var CustomStyle = function CustomStyleClosure() {
     1299  var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
     1300  var _cache = Object.create(null);
     1301  function CustomStyle() {}
     1302  CustomStyle.getProp = function get(propName, element) {
     1303    if (arguments.length === 1 && typeof _cache[propName] === 'string') {
     1304      return _cache[propName];
     1305    }
     1306    element = element || document.documentElement;
     1307    var style = element.style,
     1308        prefixed,
     1309        uPropName;
     1310    if (typeof style[propName] === 'string') {
     1311      return _cache[propName] = propName;
     1312    }
     1313    uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
     1314    for (var i = 0, l = prefixes.length; i < l; i++) {
     1315      prefixed = prefixes[i] + uPropName;
     1316      if (typeof style[prefixed] === 'string') {
     1317        return _cache[propName] = prefixed;
     1318      }
     1319    }
     1320    return _cache[propName] = 'undefined';
     1321  };
     1322  CustomStyle.setProp = function set(propName, element, str) {
     1323    var prop = this.getProp(propName);
     1324    if (prop !== 'undefined') {
     1325      element.style[prop] = str;
     1326    }
     1327  };
     1328  return CustomStyle;
     1329}();
     1330var RenderingCancelledException = function RenderingCancelledException() {
     1331  function RenderingCancelledException(msg, type) {
     1332    this.message = msg;
     1333    this.type = type;
     1334  }
     1335  RenderingCancelledException.prototype = new Error();
     1336  RenderingCancelledException.prototype.name = 'RenderingCancelledException';
     1337  RenderingCancelledException.constructor = RenderingCancelledException;
     1338  return RenderingCancelledException;
     1339}();
     1340var hasCanvasTypedArrays;
     1341hasCanvasTypedArrays = function hasCanvasTypedArrays() {
     1342  var canvas = document.createElement('canvas');
     1343  canvas.width = canvas.height = 1;
     1344  var ctx = canvas.getContext('2d');
     1345  var imageData = ctx.createImageData(1, 1);
     1346  return typeof imageData.data.buffer !== 'undefined';
     1347};
     1348var LinkTarget = {
     1349  NONE: 0,
     1350  SELF: 1,
     1351  BLANK: 2,
     1352  PARENT: 3,
     1353  TOP: 4
     1354};
     1355var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top'];
     1356function addLinkAttributes(link, params) {
     1357  var url = params && params.url;
     1358  link.href = link.title = url ? removeNullCharacters(url) : '';
     1359  if (url) {
     1360    var target = params.target;
     1361    if (typeof target === 'undefined') {
     1362      target = getDefaultSetting('externalLinkTarget');
     1363    }
     1364    link.target = LinkTargetStringMap[target];
     1365    var rel = params.rel;
     1366    if (typeof rel === 'undefined') {
     1367      rel = getDefaultSetting('externalLinkRel');
     1368    }
     1369    link.rel = rel;
     1370  }
     1371}
     1372function getFilenameFromUrl(url) {
     1373  var anchor = url.indexOf('#');
     1374  var query = url.indexOf('?');
     1375  var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
     1376  return url.substring(url.lastIndexOf('/', end) + 1, end);
     1377}
     1378function getDefaultSetting(id) {
     1379  var globalSettings = sharedUtil.globalScope.PDFJS;
     1380  switch (id) {
     1381    case 'pdfBug':
     1382      return globalSettings ? globalSettings.pdfBug : false;
     1383    case 'disableAutoFetch':
     1384      return globalSettings ? globalSettings.disableAutoFetch : false;
     1385    case 'disableStream':
     1386      return globalSettings ? globalSettings.disableStream : false;
     1387    case 'disableRange':
     1388      return globalSettings ? globalSettings.disableRange : false;
     1389    case 'disableFontFace':
     1390      return globalSettings ? globalSettings.disableFontFace : false;
     1391    case 'disableCreateObjectURL':
     1392      return globalSettings ? globalSettings.disableCreateObjectURL : false;
     1393    case 'disableWebGL':
     1394      return globalSettings ? globalSettings.disableWebGL : true;
     1395    case 'cMapUrl':
     1396      return globalSettings ? globalSettings.cMapUrl : null;
     1397    case 'cMapPacked':
     1398      return globalSettings ? globalSettings.cMapPacked : false;
     1399    case 'postMessageTransfers':
     1400      return globalSettings ? globalSettings.postMessageTransfers : true;
     1401    case 'workerPort':
     1402      return globalSettings ? globalSettings.workerPort : null;
     1403    case 'workerSrc':
     1404      return globalSettings ? globalSettings.workerSrc : null;
     1405    case 'disableWorker':
     1406      return globalSettings ? globalSettings.disableWorker : false;
     1407    case 'maxImageSize':
     1408      return globalSettings ? globalSettings.maxImageSize : -1;
     1409    case 'imageResourcesPath':
     1410      return globalSettings ? globalSettings.imageResourcesPath : '';
     1411    case 'isEvalSupported':
     1412      return globalSettings ? globalSettings.isEvalSupported : true;
     1413    case 'externalLinkTarget':
     1414      if (!globalSettings) {
     1415        return LinkTarget.NONE;
     1416      }
     1417      switch (globalSettings.externalLinkTarget) {
     1418        case LinkTarget.NONE:
     1419        case LinkTarget.SELF:
     1420        case LinkTarget.BLANK:
     1421        case LinkTarget.PARENT:
     1422        case LinkTarget.TOP:
     1423          return globalSettings.externalLinkTarget;
     1424      }
     1425      warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
     1426      globalSettings.externalLinkTarget = LinkTarget.NONE;
     1427      return LinkTarget.NONE;
     1428    case 'externalLinkRel':
     1429      return globalSettings ? globalSettings.externalLinkRel : DEFAULT_LINK_REL;
     1430    case 'enableStats':
     1431      return !!(globalSettings && globalSettings.enableStats);
     1432    case 'pdfjsNext':
     1433      return !!(globalSettings && globalSettings.pdfjsNext);
     1434    default:
     1435      throw new Error('Unknown default setting: ' + id);
     1436  }
     1437}
     1438function isExternalLinkTargetSet() {
     1439  var externalLinkTarget = getDefaultSetting('externalLinkTarget');
     1440  switch (externalLinkTarget) {
     1441    case LinkTarget.NONE:
     1442      return false;
     1443    case LinkTarget.SELF:
     1444    case LinkTarget.BLANK:
     1445    case LinkTarget.PARENT:
     1446    case LinkTarget.TOP:
     1447      return true;
     1448  }
     1449}
     1450function isValidUrl(url, allowRelative) {
     1451  deprecated('isValidUrl(), please use createValidAbsoluteUrl() instead.');
     1452  var baseUrl = allowRelative ? 'http://example.com' : null;
     1453  return createValidAbsoluteUrl(url, baseUrl) !== null;
     1454}
     1455exports.CustomStyle = CustomStyle;
     1456exports.addLinkAttributes = addLinkAttributes;
     1457exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
     1458exports.isValidUrl = isValidUrl;
     1459exports.getFilenameFromUrl = getFilenameFromUrl;
     1460exports.LinkTarget = LinkTarget;
     1461exports.RenderingCancelledException = RenderingCancelledException;
     1462exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
     1463exports.getDefaultSetting = getDefaultSetting;
     1464exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
     1465exports.DOMCanvasFactory = DOMCanvasFactory;
     1466exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
    16211467
    1622 /**
    1623  * The url of where the predefined Adobe CMaps are located. Include trailing
    1624  * slash.
    1625  * @var {string}
    1626  */
    1627 PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
     1468/***/ }),
     1469/* 2 */
     1470/***/ (function(module, exports, __w_pdfjs_require__) {
    16281471
    1629 /**
    1630  * Specifies if CMaps are binary packed.
    1631  * @var {boolean}
    1632  */
    1633 PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
     1472"use strict";
    16341473
    1635 /**
    1636  * By default fonts are converted to OpenType fonts and loaded via font face
    1637  * rules. If disabled, the font will be rendered using a built in font renderer
    1638  * that constructs the glyphs with primitive path commands.
    1639  * @var {boolean}
    1640  */
    1641 PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
    1642                          false : PDFJS.disableFontFace);
    16431474
    1644 /**
    1645  * Path for image resources, mainly for annotation icons. Include trailing
    1646  * slash.
    1647  * @var {string}
    1648  */
    1649 PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
    1650                             '' : PDFJS.imageResourcesPath);
     1475var sharedUtil = __w_pdfjs_require__(0);
     1476var displayDOMUtils = __w_pdfjs_require__(1);
     1477var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
     1478var AnnotationType = sharedUtil.AnnotationType;
     1479var stringToPDFString = sharedUtil.stringToPDFString;
     1480var Util = sharedUtil.Util;
     1481var addLinkAttributes = displayDOMUtils.addLinkAttributes;
     1482var LinkTarget = displayDOMUtils.LinkTarget;
     1483var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
     1484var warn = sharedUtil.warn;
     1485var CustomStyle = displayDOMUtils.CustomStyle;
     1486var getDefaultSetting = displayDOMUtils.getDefaultSetting;
     1487function AnnotationElementFactory() {}
     1488AnnotationElementFactory.prototype = {
     1489  create: function AnnotationElementFactory_create(parameters) {
     1490    var subtype = parameters.data.annotationType;
     1491    switch (subtype) {
     1492      case AnnotationType.LINK:
     1493        return new LinkAnnotationElement(parameters);
     1494      case AnnotationType.TEXT:
     1495        return new TextAnnotationElement(parameters);
     1496      case AnnotationType.WIDGET:
     1497        var fieldType = parameters.data.fieldType;
     1498        switch (fieldType) {
     1499          case 'Tx':
     1500            return new TextWidgetAnnotationElement(parameters);
     1501          case 'Btn':
     1502            if (parameters.data.radioButton) {
     1503              return new RadioButtonWidgetAnnotationElement(parameters);
     1504            } else if (parameters.data.checkBox) {
     1505              return new CheckboxWidgetAnnotationElement(parameters);
     1506            }
     1507            warn('Unimplemented button widget annotation: pushbutton');
     1508            break;
     1509          case 'Ch':
     1510            return new ChoiceWidgetAnnotationElement(parameters);
     1511        }
     1512        return new WidgetAnnotationElement(parameters);
     1513      case AnnotationType.POPUP:
     1514        return new PopupAnnotationElement(parameters);
     1515      case AnnotationType.LINE:
     1516        return new LineAnnotationElement(parameters);
     1517      case AnnotationType.HIGHLIGHT:
     1518        return new HighlightAnnotationElement(parameters);
     1519      case AnnotationType.UNDERLINE:
     1520        return new UnderlineAnnotationElement(parameters);
     1521      case AnnotationType.SQUIGGLY:
     1522        return new SquigglyAnnotationElement(parameters);
     1523      case AnnotationType.STRIKEOUT:
     1524        return new StrikeOutAnnotationElement(parameters);
     1525      case AnnotationType.FILEATTACHMENT:
     1526        return new FileAttachmentAnnotationElement(parameters);
     1527      default:
     1528        return new AnnotationElement(parameters);
     1529    }
     1530  }
     1531};
     1532var AnnotationElement = function AnnotationElementClosure() {
     1533  function AnnotationElement(parameters, isRenderable, ignoreBorder) {
     1534    this.isRenderable = isRenderable || false;
     1535    this.data = parameters.data;
     1536    this.layer = parameters.layer;
     1537    this.page = parameters.page;
     1538    this.viewport = parameters.viewport;
     1539    this.linkService = parameters.linkService;
     1540    this.downloadManager = parameters.downloadManager;
     1541    this.imageResourcesPath = parameters.imageResourcesPath;
     1542    this.renderInteractiveForms = parameters.renderInteractiveForms;
     1543    if (isRenderable) {
     1544      this.container = this._createContainer(ignoreBorder);
     1545    }
     1546  }
     1547  AnnotationElement.prototype = {
     1548    _createContainer: function AnnotationElement_createContainer(ignoreBorder) {
     1549      var data = this.data,
     1550          page = this.page,
     1551          viewport = this.viewport;
     1552      var container = document.createElement('section');
     1553      var width = data.rect[2] - data.rect[0];
     1554      var height = data.rect[3] - data.rect[1];
     1555      container.setAttribute('data-annotation-id', data.id);
     1556      var rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
     1557      CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
     1558      CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
     1559      if (!ignoreBorder && data.borderStyle.width > 0) {
     1560        container.style.borderWidth = data.borderStyle.width + 'px';
     1561        if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
     1562          width = width - 2 * data.borderStyle.width;
     1563          height = height - 2 * data.borderStyle.width;
     1564        }
     1565        var horizontalRadius = data.borderStyle.horizontalCornerRadius;
     1566        var verticalRadius = data.borderStyle.verticalCornerRadius;
     1567        if (horizontalRadius > 0 || verticalRadius > 0) {
     1568          var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
     1569          CustomStyle.setProp('borderRadius', container, radius);
     1570        }
     1571        switch (data.borderStyle.style) {
     1572          case AnnotationBorderStyleType.SOLID:
     1573            container.style.borderStyle = 'solid';
     1574            break;
     1575          case AnnotationBorderStyleType.DASHED:
     1576            container.style.borderStyle = 'dashed';
     1577            break;
     1578          case AnnotationBorderStyleType.BEVELED:
     1579            warn('Unimplemented border style: beveled');
     1580            break;
     1581          case AnnotationBorderStyleType.INSET:
     1582            warn('Unimplemented border style: inset');
     1583            break;
     1584          case AnnotationBorderStyleType.UNDERLINE:
     1585            container.style.borderBottomStyle = 'solid';
     1586            break;
     1587          default:
     1588            break;
     1589        }
     1590        if (data.color) {
     1591          container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
     1592        } else {
     1593          container.style.borderWidth = 0;
     1594        }
     1595      }
     1596      container.style.left = rect[0] + 'px';
     1597      container.style.top = rect[1] + 'px';
     1598      container.style.width = width + 'px';
     1599      container.style.height = height + 'px';
     1600      return container;
     1601    },
     1602    _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
     1603      if (!trigger) {
     1604        trigger = document.createElement('div');
     1605        trigger.style.height = container.style.height;
     1606        trigger.style.width = container.style.width;
     1607        container.appendChild(trigger);
     1608      }
     1609      var popupElement = new PopupElement({
     1610        container: container,
     1611        trigger: trigger,
     1612        color: data.color,
     1613        title: data.title,
     1614        contents: data.contents,
     1615        hideWrapper: true
     1616      });
     1617      var popup = popupElement.render();
     1618      popup.style.left = container.style.width;
     1619      container.appendChild(popup);
     1620    },
     1621    render: function AnnotationElement_render() {
     1622      throw new Error('Abstract method AnnotationElement.render called');
     1623    }
     1624  };
     1625  return AnnotationElement;
     1626}();
     1627var LinkAnnotationElement = function LinkAnnotationElementClosure() {
     1628  function LinkAnnotationElement(parameters) {
     1629    AnnotationElement.call(this, parameters, true);
     1630  }
     1631  Util.inherit(LinkAnnotationElement, AnnotationElement, {
     1632    render: function LinkAnnotationElement_render() {
     1633      this.container.className = 'linkAnnotation';
     1634      var link = document.createElement('a');
     1635      addLinkAttributes(link, {
     1636        url: this.data.url,
     1637        target: this.data.newWindow ? LinkTarget.BLANK : undefined
     1638      });
     1639      if (!this.data.url) {
     1640        if (this.data.action) {
     1641          this._bindNamedAction(link, this.data.action);
     1642        } else {
     1643          this._bindLink(link, this.data.dest);
     1644        }
     1645      }
     1646      this.container.appendChild(link);
     1647      return this.container;
     1648    },
     1649    _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
     1650      var self = this;
     1651      link.href = this.linkService.getDestinationHash(destination);
     1652      link.onclick = function () {
     1653        if (destination) {
     1654          self.linkService.navigateTo(destination);
     1655        }
     1656        return false;
     1657      };
     1658      if (destination) {
     1659        link.className = 'internalLink';
     1660      }
     1661    },
     1662    _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
     1663      var self = this;
     1664      link.href = this.linkService.getAnchorUrl('');
     1665      link.onclick = function () {
     1666        self.linkService.executeNamedAction(action);
     1667        return false;
     1668      };
     1669      link.className = 'internalLink';
     1670    }
     1671  });
     1672  return LinkAnnotationElement;
     1673}();
     1674var TextAnnotationElement = function TextAnnotationElementClosure() {
     1675  function TextAnnotationElement(parameters) {
     1676    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
     1677    AnnotationElement.call(this, parameters, isRenderable);
     1678  }
     1679  Util.inherit(TextAnnotationElement, AnnotationElement, {
     1680    render: function TextAnnotationElement_render() {
     1681      this.container.className = 'textAnnotation';
     1682      var image = document.createElement('img');
     1683      image.style.height = this.container.style.height;
     1684      image.style.width = this.container.style.width;
     1685      image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
     1686      image.alt = '[{{type}} Annotation]';
     1687      image.dataset.l10nId = 'text_annotation_type';
     1688      image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
     1689      if (!this.data.hasPopup) {
     1690        this._createPopup(this.container, image, this.data);
     1691      }
     1692      this.container.appendChild(image);
     1693      return this.container;
     1694    }
     1695  });
     1696  return TextAnnotationElement;
     1697}();
     1698var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
     1699  function WidgetAnnotationElement(parameters, isRenderable) {
     1700    AnnotationElement.call(this, parameters, isRenderable);
     1701  }
     1702  Util.inherit(WidgetAnnotationElement, AnnotationElement, {
     1703    render: function WidgetAnnotationElement_render() {
     1704      return this.container;
     1705    }
     1706  });
     1707  return WidgetAnnotationElement;
     1708}();
     1709var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
     1710  var TEXT_ALIGNMENT = ['left', 'center', 'right'];
     1711  function TextWidgetAnnotationElement(parameters) {
     1712    var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
     1713    WidgetAnnotationElement.call(this, parameters, isRenderable);
     1714  }
     1715  Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
     1716    render: function TextWidgetAnnotationElement_render() {
     1717      this.container.className = 'textWidgetAnnotation';
     1718      var element = null;
     1719      if (this.renderInteractiveForms) {
     1720        if (this.data.multiLine) {
     1721          element = document.createElement('textarea');
     1722          element.textContent = this.data.fieldValue;
     1723        } else {
     1724          element = document.createElement('input');
     1725          element.type = 'text';
     1726          element.setAttribute('value', this.data.fieldValue);
     1727        }
     1728        element.disabled = this.data.readOnly;
     1729        if (this.data.maxLen !== null) {
     1730          element.maxLength = this.data.maxLen;
     1731        }
     1732        if (this.data.comb) {
     1733          var fieldWidth = this.data.rect[2] - this.data.rect[0];
     1734          var combWidth = fieldWidth / this.data.maxLen;
     1735          element.classList.add('comb');
     1736          element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
     1737        }
     1738      } else {
     1739        element = document.createElement('div');
     1740        element.textContent = this.data.fieldValue;
     1741        element.style.verticalAlign = 'middle';
     1742        element.style.display = 'table-cell';
     1743        var font = null;
     1744        if (this.data.fontRefName) {
     1745          font = this.page.commonObjs.getData(this.data.fontRefName);
     1746        }
     1747        this._setTextStyle(element, font);
     1748      }
     1749      if (this.data.textAlignment !== null) {
     1750        element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
     1751      }
     1752      this.container.appendChild(element);
     1753      return this.container;
     1754    },
     1755    _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
     1756      var style = element.style;
     1757      style.fontSize = this.data.fontSize + 'px';
     1758      style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
     1759      if (!font) {
     1760        return;
     1761      }
     1762      style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
     1763      style.fontStyle = font.italic ? 'italic' : 'normal';
     1764      var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
     1765      var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
     1766      style.fontFamily = fontFamily + fallbackName;
     1767    }
     1768  });
     1769  return TextWidgetAnnotationElement;
     1770}();
     1771var CheckboxWidgetAnnotationElement = function CheckboxWidgetAnnotationElementClosure() {
     1772  function CheckboxWidgetAnnotationElement(parameters) {
     1773    WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
     1774  }
     1775  Util.inherit(CheckboxWidgetAnnotationElement, WidgetAnnotationElement, {
     1776    render: function CheckboxWidgetAnnotationElement_render() {
     1777      this.container.className = 'buttonWidgetAnnotation checkBox';
     1778      var element = document.createElement('input');
     1779      element.disabled = this.data.readOnly;
     1780      element.type = 'checkbox';
     1781      if (this.data.fieldValue && this.data.fieldValue !== 'Off') {
     1782        element.setAttribute('checked', true);
     1783      }
     1784      this.container.appendChild(element);
     1785      return this.container;
     1786    }
     1787  });
     1788  return CheckboxWidgetAnnotationElement;
     1789}();
     1790var RadioButtonWidgetAnnotationElement = function RadioButtonWidgetAnnotationElementClosure() {
     1791  function RadioButtonWidgetAnnotationElement(parameters) {
     1792    WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
     1793  }
     1794  Util.inherit(RadioButtonWidgetAnnotationElement, WidgetAnnotationElement, {
     1795    render: function RadioButtonWidgetAnnotationElement_render() {
     1796      this.container.className = 'buttonWidgetAnnotation radioButton';
     1797      var element = document.createElement('input');
     1798      element.disabled = this.data.readOnly;
     1799      element.type = 'radio';
     1800      element.name = this.data.fieldName;
     1801      if (this.data.fieldValue === this.data.buttonValue) {
     1802        element.setAttribute('checked', true);
     1803      }
     1804      this.container.appendChild(element);
     1805      return this.container;
     1806    }
     1807  });
     1808  return RadioButtonWidgetAnnotationElement;
     1809}();
     1810var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
     1811  function ChoiceWidgetAnnotationElement(parameters) {
     1812    WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
     1813  }
     1814  Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
     1815    render: function ChoiceWidgetAnnotationElement_render() {
     1816      this.container.className = 'choiceWidgetAnnotation';
     1817      var selectElement = document.createElement('select');
     1818      selectElement.disabled = this.data.readOnly;
     1819      if (!this.data.combo) {
     1820        selectElement.size = this.data.options.length;
     1821        if (this.data.multiSelect) {
     1822          selectElement.multiple = true;
     1823        }
     1824      }
     1825      for (var i = 0, ii = this.data.options.length; i < ii; i++) {
     1826        var option = this.data.options[i];
     1827        var optionElement = document.createElement('option');
     1828        optionElement.textContent = option.displayValue;
     1829        optionElement.value = option.exportValue;
     1830        if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
     1831          optionElement.setAttribute('selected', true);
     1832        }
     1833        selectElement.appendChild(optionElement);
     1834      }
     1835      this.container.appendChild(selectElement);
     1836      return this.container;
     1837    }
     1838  });
     1839  return ChoiceWidgetAnnotationElement;
     1840}();
     1841var PopupAnnotationElement = function PopupAnnotationElementClosure() {
     1842  var IGNORE_TYPES = ['Line'];
     1843  function PopupAnnotationElement(parameters) {
     1844    var isRenderable = !!(parameters.data.title || parameters.data.contents);
     1845    AnnotationElement.call(this, parameters, isRenderable);
     1846  }
     1847  Util.inherit(PopupAnnotationElement, AnnotationElement, {
     1848    render: function PopupAnnotationElement_render() {
     1849      this.container.className = 'popupAnnotation';
     1850      if (IGNORE_TYPES.indexOf(this.data.parentType) >= 0) {
     1851        return this.container;
     1852      }
     1853      var selector = '[data-annotation-id="' + this.data.parentId + '"]';
     1854      var parentElement = this.layer.querySelector(selector);
     1855      if (!parentElement) {
     1856        return this.container;
     1857      }
     1858      var popup = new PopupElement({
     1859        container: this.container,
     1860        trigger: parentElement,
     1861        color: this.data.color,
     1862        title: this.data.title,
     1863        contents: this.data.contents
     1864      });
     1865      var parentLeft = parseFloat(parentElement.style.left);
     1866      var parentWidth = parseFloat(parentElement.style.width);
     1867      CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
     1868      this.container.style.left = parentLeft + parentWidth + 'px';
     1869      this.container.appendChild(popup.render());
     1870      return this.container;
     1871    }
     1872  });
     1873  return PopupAnnotationElement;
     1874}();
     1875var PopupElement = function PopupElementClosure() {
     1876  var BACKGROUND_ENLIGHT = 0.7;
     1877  function PopupElement(parameters) {
     1878    this.container = parameters.container;
     1879    this.trigger = parameters.trigger;
     1880    this.color = parameters.color;
     1881    this.title = parameters.title;
     1882    this.contents = parameters.contents;
     1883    this.hideWrapper = parameters.hideWrapper || false;
     1884    this.pinned = false;
     1885  }
     1886  PopupElement.prototype = {
     1887    render: function PopupElement_render() {
     1888      var wrapper = document.createElement('div');
     1889      wrapper.className = 'popupWrapper';
     1890      this.hideElement = this.hideWrapper ? wrapper : this.container;
     1891      this.hideElement.setAttribute('hidden', true);
     1892      var popup = document.createElement('div');
     1893      popup.className = 'popup';
     1894      var color = this.color;
     1895      if (color) {
     1896        var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
     1897        var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
     1898        var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
     1899        popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
     1900      }
     1901      var contents = this._formatContents(this.contents);
     1902      var title = document.createElement('h1');
     1903      title.textContent = this.title;
     1904      this.trigger.addEventListener('click', this._toggle.bind(this));
     1905      this.trigger.addEventListener('mouseover', this._show.bind(this, false));
     1906      this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
     1907      popup.addEventListener('click', this._hide.bind(this, true));
     1908      popup.appendChild(title);
     1909      popup.appendChild(contents);
     1910      wrapper.appendChild(popup);
     1911      return wrapper;
     1912    },
     1913    _formatContents: function PopupElement_formatContents(contents) {
     1914      var p = document.createElement('p');
     1915      var lines = contents.split(/(?:\r\n?|\n)/);
     1916      for (var i = 0, ii = lines.length; i < ii; ++i) {
     1917        var line = lines[i];
     1918        p.appendChild(document.createTextNode(line));
     1919        if (i < ii - 1) {
     1920          p.appendChild(document.createElement('br'));
     1921        }
     1922      }
     1923      return p;
     1924    },
     1925    _toggle: function PopupElement_toggle() {
     1926      if (this.pinned) {
     1927        this._hide(true);
     1928      } else {
     1929        this._show(true);
     1930      }
     1931    },
     1932    _show: function PopupElement_show(pin) {
     1933      if (pin) {
     1934        this.pinned = true;
     1935      }
     1936      if (this.hideElement.hasAttribute('hidden')) {
     1937        this.hideElement.removeAttribute('hidden');
     1938        this.container.style.zIndex += 1;
     1939      }
     1940    },
     1941    _hide: function PopupElement_hide(unpin) {
     1942      if (unpin) {
     1943        this.pinned = false;
     1944      }
     1945      if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
     1946        this.hideElement.setAttribute('hidden', true);
     1947        this.container.style.zIndex -= 1;
     1948      }
     1949    }
     1950  };
     1951  return PopupElement;
     1952}();
     1953var LineAnnotationElement = function LineAnnotationElementClosure() {
     1954  var SVG_NS = 'http://www.w3.org/2000/svg';
     1955  function LineAnnotationElement(parameters) {
     1956    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
     1957    AnnotationElement.call(this, parameters, isRenderable, true);
     1958  }
     1959  Util.inherit(LineAnnotationElement, AnnotationElement, {
     1960    render: function LineAnnotationElement_render() {
     1961      this.container.className = 'lineAnnotation';
     1962      var data = this.data;
     1963      var width = data.rect[2] - data.rect[0];
     1964      var height = data.rect[3] - data.rect[1];
     1965      var svg = document.createElementNS(SVG_NS, 'svg:svg');
     1966      svg.setAttributeNS(null, 'version', '1.1');
     1967      svg.setAttributeNS(null, 'width', width + 'px');
     1968      svg.setAttributeNS(null, 'height', height + 'px');
     1969      svg.setAttributeNS(null, 'preserveAspectRatio', 'none');
     1970      svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
     1971      var line = document.createElementNS(SVG_NS, 'svg:line');
     1972      line.setAttributeNS(null, 'x1', data.rect[2] - data.lineCoordinates[0]);
     1973      line.setAttributeNS(null, 'y1', data.rect[3] - data.lineCoordinates[1]);
     1974      line.setAttributeNS(null, 'x2', data.rect[2] - data.lineCoordinates[2]);
     1975      line.setAttributeNS(null, 'y2', data.rect[3] - data.lineCoordinates[3]);
     1976      line.setAttributeNS(null, 'stroke-width', data.borderStyle.width);
     1977      line.setAttributeNS(null, 'stroke', 'transparent');
     1978      svg.appendChild(line);
     1979      this.container.append(svg);
     1980      this._createPopup(this.container, line, this.data);
     1981      return this.container;
     1982    }
     1983  });
     1984  return LineAnnotationElement;
     1985}();
     1986var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
     1987  function HighlightAnnotationElement(parameters) {
     1988    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
     1989    AnnotationElement.call(this, parameters, isRenderable, true);
     1990  }
     1991  Util.inherit(HighlightAnnotationElement, AnnotationElement, {
     1992    render: function HighlightAnnotationElement_render() {
     1993      this.container.className = 'highlightAnnotation';
     1994      if (!this.data.hasPopup) {
     1995        this._createPopup(this.container, null, this.data);
     1996      }
     1997      return this.container;
     1998    }
     1999  });
     2000  return HighlightAnnotationElement;
     2001}();
     2002var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
     2003  function UnderlineAnnotationElement(parameters) {
     2004    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
     2005    AnnotationElement.call(this, parameters, isRenderable, true);
     2006  }
     2007  Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
     2008    render: function UnderlineAnnotationElement_render() {
     2009      this.container.className = 'underlineAnnotation';
     2010      if (!this.data.hasPopup) {
     2011        this._createPopup(this.container, null, this.data);
     2012      }
     2013      return this.container;
     2014    }
     2015  });
     2016  return UnderlineAnnotationElement;
     2017}();
     2018var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
     2019  function SquigglyAnnotationElement(parameters) {
     2020    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
     2021    AnnotationElement.call(this, parameters, isRenderable, true);
     2022  }
     2023  Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
     2024    render: function SquigglyAnnotationElement_render() {
     2025      this.container.className = 'squigglyAnnotation';
     2026      if (!this.data.hasPopup) {
     2027        this._createPopup(this.container, null, this.data);
     2028      }
     2029      return this.container;
     2030    }
     2031  });
     2032  return SquigglyAnnotationElement;
     2033}();
     2034var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
     2035  function StrikeOutAnnotationElement(parameters) {
     2036    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
     2037    AnnotationElement.call(this, parameters, isRenderable, true);
     2038  }
     2039  Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
     2040    render: function StrikeOutAnnotationElement_render() {
     2041      this.container.className = 'strikeoutAnnotation';
     2042      if (!this.data.hasPopup) {
     2043        this._createPopup(this.container, null, this.data);
     2044      }
     2045      return this.container;
     2046    }
     2047  });
     2048  return StrikeOutAnnotationElement;
     2049}();
     2050var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
     2051  function FileAttachmentAnnotationElement(parameters) {
     2052    AnnotationElement.call(this, parameters, true);
     2053    var file = this.data.file;
     2054    this.filename = getFilenameFromUrl(file.filename);
     2055    this.content = file.content;
     2056    this.linkService.onFileAttachmentAnnotation({
     2057      id: stringToPDFString(file.filename),
     2058      filename: file.filename,
     2059      content: file.content
     2060    });
     2061  }
     2062  Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
     2063    render: function FileAttachmentAnnotationElement_render() {
     2064      this.container.className = 'fileAttachmentAnnotation';
     2065      var trigger = document.createElement('div');
     2066      trigger.style.height = this.container.style.height;
     2067      trigger.style.width = this.container.style.width;
     2068      trigger.addEventListener('dblclick', this._download.bind(this));
     2069      if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
     2070        this._createPopup(this.container, trigger, this.data);
     2071      }
     2072      this.container.appendChild(trigger);
     2073      return this.container;
     2074    },
     2075    _download: function FileAttachmentAnnotationElement_download() {
     2076      if (!this.downloadManager) {
     2077        warn('Download cannot be started due to unavailable download manager');
     2078        return;
     2079      }
     2080      this.downloadManager.downloadData(this.content, this.filename, '');
     2081    }
     2082  });
     2083  return FileAttachmentAnnotationElement;
     2084}();
     2085var AnnotationLayer = function AnnotationLayerClosure() {
     2086  return {
     2087    render: function AnnotationLayer_render(parameters) {
     2088      var annotationElementFactory = new AnnotationElementFactory();
     2089      for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
     2090        var data = parameters.annotations[i];
     2091        if (!data) {
     2092          continue;
     2093        }
     2094        var element = annotationElementFactory.create({
     2095          data: data,
     2096          layer: parameters.div,
     2097          page: parameters.page,
     2098          viewport: parameters.viewport,
     2099          linkService: parameters.linkService,
     2100          downloadManager: parameters.downloadManager,
     2101          imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
     2102          renderInteractiveForms: parameters.renderInteractiveForms || false
     2103        });
     2104        if (element.isRenderable) {
     2105          parameters.div.appendChild(element.render());
     2106        }
     2107      }
     2108    },
     2109    update: function AnnotationLayer_update(parameters) {
     2110      for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
     2111        var data = parameters.annotations[i];
     2112        var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
     2113        if (element) {
     2114          CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
     2115        }
     2116      }
     2117      parameters.div.removeAttribute('hidden');
     2118    }
     2119  };
     2120}();
     2121exports.AnnotationLayer = AnnotationLayer;
    16512122
    1652 /**
    1653  * Disable the web worker and run all code on the main thread. This will happen
    1654  * automatically if the browser doesn't support workers or sending typed arrays
    1655  * to workers.
    1656  * @var {boolean}
    1657  */
    1658 PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
    1659                        false : PDFJS.disableWorker);
     2123/***/ }),
     2124/* 3 */
     2125/***/ (function(module, exports, __w_pdfjs_require__) {
    16602126
    1661 /**
    1662  * Path and filename of the worker file. Required when the worker is enabled in
    1663  * development mode. If unspecified in the production build, the worker will be
    1664  * loaded based on the location of the pdf.js file.
    1665  * @var {string}
    1666  */
    1667 PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
     2127"use strict";
    16682128
    1669 /**
    1670  * Disable range request loading of PDF files. When enabled and if the server
    1671  * supports partial content requests then the PDF will be fetched in chunks.
    1672  * Enabled (false) by default.
    1673  * @var {boolean}
    1674  */
    1675 PDFJS.disableRange = (PDFJS.disableRange === undefined ?
    1676                       false : PDFJS.disableRange);
    16772129
    1678 /**
    1679  * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
    1680  * in chunks. This default behavior can be disabled.
    1681  * @var {boolean}
    1682  */
    1683 PDFJS.disableStream = (PDFJS.disableStream === undefined ?
    1684                        false : PDFJS.disableStream);
    1685 
    1686 /**
    1687  * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
    1688  * will automatically keep fetching more data even if it isn't needed to display
    1689  * the current page. This default behavior can be disabled.
    1690  *
    1691  * NOTE: It is also necessary to disable streaming, see above,
    1692  *       in order for disabling of pre-fetching to work correctly.
    1693  * @var {boolean}
    1694  */
    1695 PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
    1696                           false : PDFJS.disableAutoFetch);
    1697 
    1698 /**
    1699  * Enables special hooks for debugging PDF.js.
    1700  * @var {boolean}
    1701  */
    1702 PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
    1703 
    1704 /**
    1705  * Enables transfer usage in postMessage for ArrayBuffers.
    1706  * @var {boolean}
    1707  */
    1708 PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
    1709                               true : PDFJS.postMessageTransfers);
    1710 
    1711 /**
    1712  * Disables URL.createObjectURL usage.
    1713  * @var {boolean}
    1714  */
    1715 PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
    1716                                 false : PDFJS.disableCreateObjectURL);
    1717 
    1718 /**
    1719  * Disables WebGL usage.
    1720  * @var {boolean}
    1721  */
    1722 PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
    1723                       true : PDFJS.disableWebGL);
    1724 
    1725 /**
    1726  * Disables fullscreen support, and by extension Presentation Mode,
    1727  * in browsers which support the fullscreen API.
    1728  * @var {boolean}
    1729  */
    1730 PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
    1731                            false : PDFJS.disableFullscreen);
    1732 
    1733 /**
    1734  * Enables CSS only zooming.
    1735  * @var {boolean}
    1736  */
    1737 PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
    1738                         false : PDFJS.useOnlyCssZoom);
    1739 
    1740 /**
    1741  * Controls the logging level.
    1742  * The constants from PDFJS.VERBOSITY_LEVELS should be used:
    1743  * - errors
    1744  * - warnings [default]
    1745  * - infos
    1746  * @var {number}
    1747  */
    1748 PDFJS.verbosity = (PDFJS.verbosity === undefined ?
    1749                    PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
    1750 
    1751 /**
    1752  * The maximum supported canvas size in total pixels e.g. width * height.
    1753  * The default value is 4096 * 4096. Use -1 for no limit.
    1754  * @var {number}
    1755  */
    1756 PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
    1757                          16777216 : PDFJS.maxCanvasPixels);
    1758 
    1759 /**
    1760  * Opens external links in a new window if enabled. The default behavior opens
    1761  * external links in the PDF.js window.
    1762  * @var {boolean}
    1763  */
    1764 PDFJS.openExternalLinksInNewWindow = (
    1765   PDFJS.openExternalLinksInNewWindow === undefined ?
    1766     false : PDFJS.openExternalLinksInNewWindow);
    1767 
    1768 /**
    1769  * Document initialization / loading parameters object.
    1770  *
    1771  * @typedef {Object} DocumentInitParameters
    1772  * @property {string}     url   - The URL of the PDF.
    1773  * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
    1774  *   (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
    1775  *   use atob() to convert it to a binary string first.
    1776  * @property {Object}     httpHeaders - Basic authentication headers.
    1777  * @property {boolean}    withCredentials - Indicates whether or not cross-site
    1778  *   Access-Control requests should be made using credentials such as cookies
    1779  *   or authorization headers. The default is false.
    1780  * @property {string}     password - For decrypting password-protected PDFs.
    1781  * @property {TypedArray} initialData - A typed array with the first portion or
    1782  *   all of the pdf data. Used by the extension since some data is already
    1783  *   loaded before the switch to range requests.
    1784  * @property {number}     length - The PDF file length. It's used for progress
    1785  *   reports and range requests operations.
    1786  * @property {PDFDataRangeTransport} range
    1787  */
    1788 
    1789 /**
    1790  * @typedef {Object} PDFDocumentStats
    1791  * @property {Array} streamTypes - Used stream types in the document (an item
    1792  *   is set to true if specific stream ID was used in the document).
    1793  * @property {Array} fontTypes - Used font type in the document (an item is set
    1794  *   to true if specific font ID was used in the document).
    1795  */
    1796 
    1797 /**
    1798  * This is the main entry point for loading a PDF and interacting with it.
    1799  * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
    1800  * is used, which means it must follow the same origin rules that any XHR does
    1801  * e.g. No cross domain requests without CORS.
    1802  *
    1803  * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
    1804  * Can be a url to where a PDF is located, a typed array (Uint8Array)
    1805  * already populated with data or parameter object.
    1806  *
    1807  * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
    1808  * if you want to manually serve range requests for data in the PDF.
    1809  *
    1810  * @param {function} passwordCallback (deprecated) It is used to request a
    1811  * password if wrong or no password was provided. The callback receives two
    1812  * parameters: function that needs to be called with new password and reason
    1813  * (see {PasswordResponses}).
    1814  *
    1815  * @param {function} progressCallback (deprecated) It is used to be able to
    1816  * monitor the loading progress of the PDF file (necessary to implement e.g.
    1817  * a loading bar). The callback receives an {Object} with the properties:
    1818  * {number} loaded and {number} total.
    1819  *
    1820  * @return {PDFDocumentLoadingTask}
    1821  */
    1822 PDFJS.getDocument = function getDocument(src,
    1823                                          pdfDataRangeTransport,
    1824                                          passwordCallback,
    1825                                          progressCallback) {
     2130var sharedUtil = __w_pdfjs_require__(0);
     2131var displayFontLoader = __w_pdfjs_require__(11);
     2132var displayCanvas = __w_pdfjs_require__(10);
     2133var displayMetadata = __w_pdfjs_require__(7);
     2134var displayDOMUtils = __w_pdfjs_require__(1);
     2135var amdRequire;
     2136var InvalidPDFException = sharedUtil.InvalidPDFException;
     2137var MessageHandler = sharedUtil.MessageHandler;
     2138var MissingPDFException = sharedUtil.MissingPDFException;
     2139var PageViewport = sharedUtil.PageViewport;
     2140var PasswordException = sharedUtil.PasswordException;
     2141var StatTimer = sharedUtil.StatTimer;
     2142var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
     2143var UnknownErrorException = sharedUtil.UnknownErrorException;
     2144var Util = sharedUtil.Util;
     2145var createPromiseCapability = sharedUtil.createPromiseCapability;
     2146var error = sharedUtil.error;
     2147var deprecated = sharedUtil.deprecated;
     2148var getVerbosityLevel = sharedUtil.getVerbosityLevel;
     2149var info = sharedUtil.info;
     2150var isInt = sharedUtil.isInt;
     2151var isArray = sharedUtil.isArray;
     2152var isArrayBuffer = sharedUtil.isArrayBuffer;
     2153var isSameOrigin = sharedUtil.isSameOrigin;
     2154var loadJpegStream = sharedUtil.loadJpegStream;
     2155var stringToBytes = sharedUtil.stringToBytes;
     2156var globalScope = sharedUtil.globalScope;
     2157var warn = sharedUtil.warn;
     2158var FontFaceObject = displayFontLoader.FontFaceObject;
     2159var FontLoader = displayFontLoader.FontLoader;
     2160var CanvasGraphics = displayCanvas.CanvasGraphics;
     2161var Metadata = displayMetadata.Metadata;
     2162var RenderingCancelledException = displayDOMUtils.RenderingCancelledException;
     2163var getDefaultSetting = displayDOMUtils.getDefaultSetting;
     2164var DOMCanvasFactory = displayDOMUtils.DOMCanvasFactory;
     2165var DOMCMapReaderFactory = displayDOMUtils.DOMCMapReaderFactory;
     2166var DEFAULT_RANGE_CHUNK_SIZE = 65536;
     2167var isWorkerDisabled = false;
     2168var workerSrc;
     2169var isPostMessageTransfersDisabled = false;
     2170var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
     2171var fakeWorkerFilesLoader = null;
     2172var useRequireEnsure = false;
     2173if (typeof __pdfjsdev_webpack__ === 'undefined') {
     2174  if (typeof window === 'undefined') {
     2175    isWorkerDisabled = true;
     2176    if (typeof require.ensure === 'undefined') {
     2177      require.ensure = require('node-ensure');
     2178    }
     2179    useRequireEnsure = true;
     2180  } else if (typeof require !== 'undefined' && typeof require.ensure === 'function') {
     2181    useRequireEnsure = true;
     2182  }
     2183  if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
     2184    workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
     2185  }
     2186  var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
     2187  fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
     2188    require.ensure([], function () {
     2189      var worker = require('./pdf.worker.js');
     2190      callback(worker.WorkerMessageHandler);
     2191    });
     2192  } : dynamicLoaderSupported ? function (callback) {
     2193    requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
     2194      callback(worker.WorkerMessageHandler);
     2195    });
     2196  } : null;
     2197}
     2198function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
    18262199  var task = new PDFDocumentLoadingTask();
    1827 
    1828   // Support of the obsolete arguments (for compatibility with API v1.0)
     2200  if (arguments.length > 1) {
     2201    deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
     2202  }
    18292203  if (pdfDataRangeTransport) {
    18302204    if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
    1831       // Not a PDFDataRangeTransport instance, trying to add missing properties.
    18322205      pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
    18332206      pdfDataRangeTransport.length = src.length;
    18342207      pdfDataRangeTransport.initialData = src.initialData;
     2208      if (!pdfDataRangeTransport.abort) {
     2209        pdfDataRangeTransport.abort = function () {};
     2210      }
    18352211    }
    18362212    src = Object.create(src);
     
    18392215  task.onPassword = passwordCallback || null;
    18402216  task.onProgress = progressCallback || null;
    1841 
    1842   var workerInitializedCapability, transport;
    18432217  var source;
    18442218  if (typeof src === 'string') {
     
    18502224  } else {
    18512225    if (typeof src !== 'object') {
    1852       error('Invalid parameter in getDocument, need either Uint8Array, ' +
    1853         'string or a parameter object');
     2226      error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
    18542227    }
    18552228    if (!src.url && !src.data && !src.range) {
    18562229      error('Invalid parameter object: need either .data, .range or .url');
    18572230    }
    1858 
    18592231    source = src;
    18602232  }
    1861 
    18622233  var params = {};
     2234  var rangeTransport = null;
     2235  var worker = null;
    18632236  for (var key in source) {
    18642237    if (key === 'url' && typeof window !== 'undefined') {
    1865       // The full path is required in the 'url' field.
    1866       params[key] = combineUrl(window.location.href, source[key]);
     2238      params[key] = new URL(source[key], window.location).href;
    18672239      continue;
    18682240    } else if (key === 'range') {
     2241      rangeTransport = source[key];
     2242      continue;
     2243    } else if (key === 'worker') {
     2244      worker = source[key];
    18692245      continue;
    18702246    } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
    1871       // Converting string or array-like data to Uint8Array.
    18722247      var pdfBytes = source[key];
    18732248      if (typeof pdfBytes === 'string') {
    18742249        params[key] = stringToBytes(pdfBytes);
    1875       } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
    1876                  !isNaN(pdfBytes.length)) {
     2250      } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
     2251        params[key] = new Uint8Array(pdfBytes);
     2252      } else if (isArrayBuffer(pdfBytes)) {
    18772253        params[key] = new Uint8Array(pdfBytes);
    18782254      } else {
    1879         error('Invalid PDF binary data: either typed array, string or ' +
    1880               'array-like object is expected in the data property.');
     2255        error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
    18812256      }
    18822257      continue;
     
    18842259    params[key] = source[key];
    18852260  }
    1886 
    1887   workerInitializedCapability = createPromiseCapability();
    1888   transport = new WorkerTransport(workerInitializedCapability, source.range);
    1889   workerInitializedCapability.promise.then(function transportInitialized() {
    1890     transport.fetchDocument(task, params);
     2261  params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
     2262  params.disableNativeImageDecoder = params.disableNativeImageDecoder === true;
     2263  var CMapReaderFactory = params.CMapReaderFactory || DOMCMapReaderFactory;
     2264  if (!worker) {
     2265    var workerPort = getDefaultSetting('workerPort');
     2266    worker = workerPort ? new PDFWorker(null, workerPort) : new PDFWorker();
     2267    task._worker = worker;
     2268  }
     2269  var docId = task.docId;
     2270  worker.promise.then(function () {
     2271    if (task.destroyed) {
     2272      throw new Error('Loading aborted');
     2273    }
     2274    return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
     2275      if (task.destroyed) {
     2276        throw new Error('Loading aborted');
     2277      }
     2278      var messageHandler = new MessageHandler(docId, workerId, worker.port);
     2279      var transport = new WorkerTransport(messageHandler, task, rangeTransport, CMapReaderFactory);
     2280      task._transport = transport;
     2281      messageHandler.send('Ready', null);
     2282    });
     2283  }).catch(task._capability.reject);
     2284  return task;
     2285}
     2286function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
     2287  if (worker.destroyed) {
     2288    return Promise.reject(new Error('Worker was destroyed'));
     2289  }
     2290  source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
     2291  source.disableStream = getDefaultSetting('disableStream');
     2292  source.chunkedViewerLoading = !!pdfDataRangeTransport;
     2293  if (pdfDataRangeTransport) {
     2294    source.length = pdfDataRangeTransport.length;
     2295    source.initialData = pdfDataRangeTransport.initialData;
     2296  }
     2297  return worker.messageHandler.sendWithPromise('GetDocRequest', {
     2298    docId: docId,
     2299    source: source,
     2300    disableRange: getDefaultSetting('disableRange'),
     2301    maxImageSize: getDefaultSetting('maxImageSize'),
     2302    disableFontFace: getDefaultSetting('disableFontFace'),
     2303    disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
     2304    postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled,
     2305    docBaseUrl: source.docBaseUrl,
     2306    disableNativeImageDecoder: source.disableNativeImageDecoder
     2307  }).then(function (workerId) {
     2308    if (worker.destroyed) {
     2309      throw new Error('Worker was destroyed');
     2310    }
     2311    return workerId;
    18912312  });
    1892 
    1893   return task;
    1894 };
    1895 
    1896 /**
    1897  * PDF document loading operation.
    1898  * @class
    1899  */
    1900 var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
    1901   /** @constructs PDFDocumentLoadingTask */
     2313}
     2314var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
     2315  var nextDocumentId = 0;
    19022316  function PDFDocumentLoadingTask() {
    19032317    this._capability = createPromiseCapability();
    1904 
    1905     /**
    1906      * Callback to request a password if wrong or no password was provided.
    1907      * The callback receives two parameters: function that needs to be called
    1908      * with new password and reason (see {PasswordResponses}).
    1909      */
     2318    this._transport = null;
     2319    this._worker = null;
     2320    this.docId = 'd' + nextDocumentId++;
     2321    this.destroyed = false;
    19102322    this.onPassword = null;
    1911 
    1912     /**
    1913      * Callback to be able to monitor the loading progress of the PDF file
    1914      * (necessary to implement e.g. a loading bar). The callback receives
    1915      * an {Object} with the properties: {number} loaded and {number} total.
    1916      */
    19172323    this.onProgress = null;
    1918   }
    1919 
    1920   PDFDocumentLoadingTask.prototype =
    1921       /** @lends PDFDocumentLoadingTask.prototype */ {
    1922     /**
    1923      * @return {Promise}
    1924      */
     2324    this.onUnsupportedFeature = null;
     2325  }
     2326  PDFDocumentLoadingTask.prototype = {
    19252327    get promise() {
    19262328      return this._capability.promise;
    19272329    },
    1928 
    1929     // TODO add cancel or abort method
    1930 
    1931     /**
    1932      * Registers callbacks to indicate the document loading completion.
    1933      *
    1934      * @param {function} onFulfilled The callback for the loading completion.
    1935      * @param {function} onRejected The callback for the loading failure.
    1936      * @return {Promise} A promise that is resolved after the onFulfilled or
    1937      *                   onRejected callback.
    1938      */
     2330    destroy: function () {
     2331      this.destroyed = true;
     2332      var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
     2333      return transportDestroyed.then(function () {
     2334        this._transport = null;
     2335        if (this._worker) {
     2336          this._worker.destroy();
     2337          this._worker = null;
     2338        }
     2339      }.bind(this));
     2340    },
    19392341    then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
    19402342      return this.promise.then.apply(this.promise, arguments);
    19412343    }
    19422344  };
    1943 
    19442345  return PDFDocumentLoadingTask;
    1945 })();
    1946 
    1947 /**
    1948  * Abstract class to support range requests file loading.
    1949  * @class
    1950  */
    1951 var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
    1952   /**
    1953    * @constructs PDFDataRangeTransport
    1954    * @param {number} length
    1955    * @param {Uint8Array} initialData
    1956    */
     2346}();
     2347var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
    19572348  function PDFDataRangeTransport(length, initialData) {
    19582349    this.length = length;
    19592350    this.initialData = initialData;
    1960 
    19612351    this._rangeListeners = [];
    19622352    this._progressListeners = [];
     
    19642354    this._readyCapability = createPromiseCapability();
    19652355  }
    1966   PDFDataRangeTransport.prototype =
    1967       /** @lends PDFDataRangeTransport.prototype */ {
    1968     addRangeListener:
    1969         function PDFDataRangeTransport_addRangeListener(listener) {
     2356  PDFDataRangeTransport.prototype = {
     2357    addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
    19702358      this._rangeListeners.push(listener);
    19712359    },
    1972 
    1973     addProgressListener:
    1974         function PDFDataRangeTransport_addProgressListener(listener) {
     2360    addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
    19752361      this._progressListeners.push(listener);
    19762362    },
    1977 
    1978     addProgressiveReadListener:
    1979         function PDFDataRangeTransport_addProgressiveReadListener(listener) {
     2363    addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
    19802364      this._progressiveReadListeners.push(listener);
    19812365    },
    1982 
    19832366    onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
    19842367      var listeners = this._rangeListeners;
     
    19872370      }
    19882371    },
    1989 
    19902372    onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
    19912373      this._readyCapability.promise.then(function () {
     
    19962378      }.bind(this));
    19972379    },
    1998 
    1999     onDataProgressiveRead:
    2000         function PDFDataRangeTransport_onDataProgress(chunk) {
     2380    onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
    20012381      this._readyCapability.promise.then(function () {
    20022382        var listeners = this._progressiveReadListeners;
     
    20062386      }.bind(this));
    20072387    },
    2008 
    20092388    transportReady: function PDFDataRangeTransport_transportReady() {
    20102389      this._readyCapability.resolve();
    20112390    },
    2012 
    2013     requestDataRange:
    2014         function PDFDataRangeTransport_requestDataRange(begin, end) {
     2391    requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
    20152392      throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
    2016     }
     2393    },
     2394    abort: function PDFDataRangeTransport_abort() {}
    20172395  };
    20182396  return PDFDataRangeTransport;
    2019 })();
    2020 
    2021 PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
    2022 
    2023 /**
    2024  * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
    2025  * properties that can be read synchronously.
    2026  * @class
    2027  */
    2028 var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
    2029   function PDFDocumentProxy(pdfInfo, transport) {
     2397}();
     2398var PDFDocumentProxy = function PDFDocumentProxyClosure() {
     2399  function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
    20302400    this.pdfInfo = pdfInfo;
    20312401    this.transport = transport;
    2032   }
    2033   PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
    2034     /**
    2035      * @return {number} Total number of pages the PDF contains.
    2036      */
     2402    this.loadingTask = loadingTask;
     2403  }
     2404  PDFDocumentProxy.prototype = {
    20372405    get numPages() {
    20382406      return this.pdfInfo.numPages;
    20392407    },
    2040     /**
    2041      * @return {string} A unique ID to identify a PDF. Not guaranteed to be
    2042      * unique.
    2043      */
    20442408    get fingerprint() {
    20452409      return this.pdfInfo.fingerprint;
    20462410    },
    2047     /**
    2048      * @param {number} pageNumber The page number to get. The first page is 1.
    2049      * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
    2050      * object.
    2051      */
    20522411    getPage: function PDFDocumentProxy_getPage(pageNumber) {
    20532412      return this.transport.getPage(pageNumber);
    20542413    },
    2055     /**
    2056      * @param {{num: number, gen: number}} ref The page reference. Must have
    2057      *   the 'num' and 'gen' properties.
    2058      * @return {Promise} A promise that is resolved with the page index that is
    2059      * associated with the reference.
    2060      */
    20612414    getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
    20622415      return this.transport.getPageIndex(ref);
    20632416    },
    2064     /**
    2065      * @return {Promise} A promise that is resolved with a lookup table for
    2066      * mapping named destinations to reference numbers.
    2067      *
    2068      * This can be slow for large documents: use getDestination instead
    2069      */
    20702417    getDestinations: function PDFDocumentProxy_getDestinations() {
    20712418      return this.transport.getDestinations();
    20722419    },
    2073     /**
    2074      * @param {string} id The named destination to get.
    2075      * @return {Promise} A promise that is resolved with all information
    2076      * of the given named destination.
    2077      */
    20782420    getDestination: function PDFDocumentProxy_getDestination(id) {
    20792421      return this.transport.getDestination(id);
    20802422    },
    2081     /**
    2082      * @return {Promise} A promise that is resolved with a lookup table for
    2083      * mapping named attachments to their content.
    2084      */
     2423    getPageLabels: function PDFDocumentProxy_getPageLabels() {
     2424      return this.transport.getPageLabels();
     2425    },
    20852426    getAttachments: function PDFDocumentProxy_getAttachments() {
    20862427      return this.transport.getAttachments();
    20872428    },
    2088     /**
    2089      * @return {Promise} A promise that is resolved with an array of all the
    2090      * JavaScript strings in the name tree.
    2091      */
    20922429    getJavaScript: function PDFDocumentProxy_getJavaScript() {
    20932430      return this.transport.getJavaScript();
    20942431    },
    2095     /**
    2096      * @return {Promise} A promise that is resolved with an {Array} that is a
    2097      * tree outline (if it has one) of the PDF. The tree is in the format of:
    2098      * [
    2099      *  {
    2100      *   title: string,
    2101      *   bold: boolean,
    2102      *   italic: boolean,
    2103      *   color: rgb array,
    2104      *   dest: dest obj,
    2105      *   items: array of more items like this
    2106      *  },
    2107      *  ...
    2108      * ].
    2109      */
    21102432    getOutline: function PDFDocumentProxy_getOutline() {
    21112433      return this.transport.getOutline();
    21122434    },
    2113     /**
    2114      * @return {Promise} A promise that is resolved with an {Object} that has
    2115      * info and metadata properties.  Info is an {Object} filled with anything
    2116      * available in the information dictionary and similarly metadata is a
    2117      * {Metadata} object with information from the metadata section of the PDF.
    2118      */
    21192435    getMetadata: function PDFDocumentProxy_getMetadata() {
    21202436      return this.transport.getMetadata();
    21212437    },
    2122     /**
    2123      * @return {Promise} A promise that is resolved with a TypedArray that has
    2124      * the raw data from the PDF.
    2125      */
    21262438    getData: function PDFDocumentProxy_getData() {
    21272439      return this.transport.getData();
    21282440    },
    2129     /**
    2130      * @return {Promise} A promise that is resolved when the document's data
    2131      * is loaded. It is resolved with an {Object} that contains the length
    2132      * property that indicates size of the PDF data in bytes.
    2133      */
    21342441    getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
    21352442      return this.transport.downloadInfoCapability.promise;
    21362443    },
    2137     /**
    2138      * @return {Promise} A promise this is resolved with current stats about
    2139      * document structures (see {@link PDFDocumentStats}).
    2140      */
    21412444    getStats: function PDFDocumentProxy_getStats() {
    21422445      return this.transport.getStats();
    21432446    },
    2144     /**
    2145      * Cleans up resources allocated by the document, e.g. created @font-face.
    2146      */
    21472447    cleanup: function PDFDocumentProxy_cleanup() {
    21482448      this.transport.startCleanup();
    21492449    },
    2150     /**
    2151      * Destroys current document instance and terminates worker.
    2152      */
    21532450    destroy: function PDFDocumentProxy_destroy() {
    2154       this.transport.destroy();
     2451      return this.loadingTask.destroy();
    21552452    }
    21562453  };
    21572454  return PDFDocumentProxy;
    2158 })();
    2159 
    2160 /**
    2161  * Page text content.
    2162  *
    2163  * @typedef {Object} TextContent
    2164  * @property {array} items - array of {@link TextItem}
    2165  * @property {Object} styles - {@link TextStyles} objects, indexed by font
    2166  *                    name.
    2167  */
    2168 
    2169 /**
    2170  * Page text content part.
    2171  *
    2172  * @typedef {Object} TextItem
    2173  * @property {string} str - text content.
    2174  * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
    2175  * @property {array} transform - transformation matrix.
    2176  * @property {number} width - width in device space.
    2177  * @property {number} height - height in device space.
    2178  * @property {string} fontName - font name used by pdf.js for converted font.
    2179  */
    2180 
    2181 /**
    2182  * Text style.
    2183  *
    2184  * @typedef {Object} TextStyle
    2185  * @property {number} ascent - font ascent.
    2186  * @property {number} descent - font descent.
    2187  * @property {boolean} vertical - text is in vertical mode.
    2188  * @property {string} fontFamily - possible font family
    2189  */
    2190 
    2191 /**
    2192  * Page render parameters.
    2193  *
    2194  * @typedef {Object} RenderParameters
    2195  * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
    2196  * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
    2197  *                                calling of PDFPage.getViewport method.
    2198  * @property {string} intent - Rendering intent, can be 'display' or 'print'
    2199  *                    (default value is 'display').
    2200  * @property {Object} imageLayer - (optional) An object that has beginLayout,
    2201  *                    endLayout and appendImage functions.
    2202  * @property {function} continueCallback - (deprecated) A function that will be
    2203  *                      called each time the rendering is paused.  To continue
    2204  *                      rendering call the function that is the first argument
    2205  *                      to the callback.
    2206  */
    2207 
    2208 /**
    2209  * PDF page operator list.
    2210  *
    2211  * @typedef {Object} PDFOperatorList
    2212  * @property {Array} fnArray - Array containing the operator functions.
    2213  * @property {Array} argsArray - Array containing the arguments of the
    2214  *                               functions.
    2215  */
    2216 
    2217 /**
    2218  * Proxy to a PDFPage in the worker thread.
    2219  * @class
    2220  */
    2221 var PDFPageProxy = (function PDFPageProxyClosure() {
     2455}();
     2456var PDFPageProxy = function PDFPageProxyClosure() {
    22222457  function PDFPageProxy(pageIndex, pageInfo, transport) {
    22232458    this.pageIndex = pageIndex;
     
    22252460    this.transport = transport;
    22262461    this.stats = new StatTimer();
    2227     this.stats.enabled = !!globalScope.PDFJS.enableStats;
     2462    this.stats.enabled = getDefaultSetting('enableStats');
    22282463    this.commonObjs = transport.commonObjs;
    22292464    this.objs = new PDFObjects();
    22302465    this.cleanupAfterRender = false;
    2231     this.pendingDestroy = false;
    2232     this.intentStates = {};
    2233   }
    2234   PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
    2235     /**
    2236      * @return {number} Page number of the page. First page is 1.
    2237      */
     2466    this.pendingCleanup = false;
     2467    this.intentStates = Object.create(null);
     2468    this.destroyed = false;
     2469  }
     2470  PDFPageProxy.prototype = {
    22382471    get pageNumber() {
    22392472      return this.pageIndex + 1;
    22402473    },
    2241     /**
    2242      * @return {number} The number of degrees the page is rotated clockwise.
    2243      */
    22442474    get rotate() {
    22452475      return this.pageInfo.rotate;
    22462476    },
    2247     /**
    2248      * @return {Object} The reference that points to this page. It has 'num' and
    2249      * 'gen' properties.
    2250      */
    22512477    get ref() {
    22522478      return this.pageInfo.ref;
    22532479    },
    2254     /**
    2255      * @return {Array} An array of the visible portion of the PDF page in the
    2256      * user space units - [x1, y1, x2, y2].
    2257      */
     2480    get userUnit() {
     2481      return this.pageInfo.userUnit;
     2482    },
    22582483    get view() {
    22592484      return this.pageInfo.view;
    22602485    },
    2261     /**
    2262      * @param {number} scale The desired scale of the viewport.
    2263      * @param {number} rotate Degrees to rotate the viewport. If omitted this
    2264      * defaults to the page rotation.
    2265      * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
    2266      * along with transforms required for rendering.
    2267      */
    22682486    getViewport: function PDFPageProxy_getViewport(scale, rotate) {
    22692487      if (arguments.length < 2) {
    22702488        rotate = this.rotate;
    22712489      }
    2272       return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
    2273     },
    2274     /**
    2275      * @return {Promise} A promise that is resolved with an {Array} of the
    2276      * annotation objects.
    2277      */
    2278     getAnnotations: function PDFPageProxy_getAnnotations() {
    2279       if (this.annotationsPromise) {
    2280         return this.annotationsPromise;
    2281       }
    2282 
    2283       var promise = this.transport.getAnnotations(this.pageIndex);
    2284       this.annotationsPromise = promise;
    2285       return promise;
    2286     },
    2287     /**
    2288      * Begins the process of rendering a page to the desired context.
    2289      * @param {RenderParameters} params Page render parameters.
    2290      * @return {RenderTask} An object that contains the promise, which
    2291      *                      is resolved when the page finishes rendering.
    2292      */
     2490      return new PageViewport(this.view, scale, rotate, 0, 0);
     2491    },
     2492    getAnnotations: function PDFPageProxy_getAnnotations(params) {
     2493      var intent = params && params.intent || null;
     2494      if (!this.annotationsPromise || this.annotationsIntent !== intent) {
     2495        this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
     2496        this.annotationsIntent = intent;
     2497      }
     2498      return this.annotationsPromise;
     2499    },
    22932500    render: function PDFPageProxy_render(params) {
    22942501      var stats = this.stats;
    22952502      stats.time('Overall');
    2296 
    2297       // If there was a pending destroy cancel it so no cleanup happens during
    2298       // this call to render.
    2299       this.pendingDestroy = false;
    2300 
    2301       var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
    2302 
     2503      this.pendingCleanup = false;
     2504      var renderingIntent = params.intent === 'print' ? 'print' : 'display';
     2505      var renderInteractiveForms = params.renderInteractiveForms === true ? true : false;
     2506      var canvasFactory = params.canvasFactory || new DOMCanvasFactory();
    23032507      if (!this.intentStates[renderingIntent]) {
    2304         this.intentStates[renderingIntent] = {};
     2508        this.intentStates[renderingIntent] = Object.create(null);
    23052509      }
    23062510      var intentState = this.intentStates[renderingIntent];
    2307 
    2308       // If there's no displayReadyCapability yet, then the operatorList
    2309       // was never requested before. Make the request and create the promise.
    23102511      if (!intentState.displayReadyCapability) {
    23112512        intentState.receivingOperatorList = true;
     
    23162517          lastChunk: false
    23172518        };
    2318 
    23192519        this.stats.time('Page Request');
    23202520        this.transport.messageHandler.send('RenderPageRequest', {
    23212521          pageIndex: this.pageNumber - 1,
    2322           intent: renderingIntent
     2522          intent: renderingIntent,
     2523          renderInteractiveForms: renderInteractiveForms
    23232524        });
    23242525      }
    2325 
    2326       var internalRenderTask = new InternalRenderTask(complete, params,
    2327                                                       this.objs,
    2328                                                       this.commonObjs,
    2329                                                       intentState.operatorList,
    2330                                                       this.pageNumber);
     2526      var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber, canvasFactory);
     2527      internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
    23312528      if (!intentState.renderTasks) {
    23322529        intentState.renderTasks = [];
     
    23342531      intentState.renderTasks.push(internalRenderTask);
    23352532      var renderTask = internalRenderTask.task;
    2336 
    2337       // Obsolete parameter support
    23382533      if (params.continueCallback) {
     2534        deprecated('render is used with continueCallback parameter');
    23392535        renderTask.onContinue = params.continueCallback;
    23402536      }
    2341 
    23422537      var self = this;
    2343       intentState.displayReadyCapability.promise.then(
    2344         function pageDisplayReadyPromise(transparency) {
    2345           if (self.pendingDestroy) {
    2346             complete();
    2347             return;
    2348           }
    2349           stats.time('Rendering');
    2350           internalRenderTask.initalizeGraphics(transparency);
    2351           internalRenderTask.operatorListChanged();
    2352         },
    2353         function pageDisplayReadPromiseError(reason) {
    2354           complete(reason);
    2355         }
    2356       );
    2357 
     2538      intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
     2539        if (self.pendingCleanup) {
     2540          complete();
     2541          return;
     2542        }
     2543        stats.time('Rendering');
     2544        internalRenderTask.initializeGraphics(transparency);
     2545        internalRenderTask.operatorListChanged();
     2546      }, function pageDisplayReadPromiseError(reason) {
     2547        complete(reason);
     2548      });
    23582549      function complete(error) {
    23592550        var i = intentState.renderTasks.indexOf(internalRenderTask);
     
    23612552          intentState.renderTasks.splice(i, 1);
    23622553        }
    2363 
    23642554        if (self.cleanupAfterRender) {
    2365           self.pendingDestroy = true;
    2366         }
    2367         self._tryDestroy();
    2368 
     2555          self.pendingCleanup = true;
     2556        }
     2557        self._tryCleanup();
    23692558        if (error) {
    23702559          internalRenderTask.capability.reject(error);
     
    23752564        stats.timeEnd('Overall');
    23762565      }
    2377 
    23782566      return renderTask;
    23792567    },
    2380 
    2381     /**
    2382      * @return {Promise} A promise resolved with an {@link PDFOperatorList}
    2383      * object that represents page's operator list.
    2384      */
    23852568    getOperatorList: function PDFPageProxy_getOperatorList() {
    23862569      function operatorListChanged() {
    23872570        if (intentState.operatorList.lastChunk) {
    23882571          intentState.opListReadCapability.resolve(intentState.operatorList);
    2389         }
    2390       }
    2391 
     2572          var i = intentState.renderTasks.indexOf(opListTask);
     2573          if (i >= 0) {
     2574            intentState.renderTasks.splice(i, 1);
     2575          }
     2576        }
     2577      }
    23922578      var renderingIntent = 'oplist';
    23932579      if (!this.intentStates[renderingIntent]) {
    2394         this.intentStates[renderingIntent] = {};
     2580        this.intentStates[renderingIntent] = Object.create(null);
    23952581      }
    23962582      var intentState = this.intentStates[renderingIntent];
    2397 
     2583      var opListTask;
    23982584      if (!intentState.opListReadCapability) {
    2399         var opListTask = {};
     2585        opListTask = {};
    24002586        opListTask.operatorListChanged = operatorListChanged;
    24012587        intentState.receivingOperatorList = true;
     
    24082594          lastChunk: false
    24092595        };
    2410 
    24112596        this.transport.messageHandler.send('RenderPageRequest', {
    24122597          pageIndex: this.pageIndex,
     
    24162601      return intentState.opListReadCapability.promise;
    24172602    },
    2418 
    2419     /**
    2420      * @return {Promise} That is resolved a {@link TextContent}
    2421      * object that represent the page text content.
    2422      */
    2423     getTextContent: function PDFPageProxy_getTextContent() {
     2603    getTextContent: function PDFPageProxy_getTextContent(params) {
    24242604      return this.transport.messageHandler.sendWithPromise('GetTextContent', {
    2425         pageIndex: this.pageNumber - 1
     2605        pageIndex: this.pageNumber - 1,
     2606        normalizeWhitespace: params && params.normalizeWhitespace === true ? true : false,
     2607        combineTextItems: params && params.disableCombineTextItems === true ? false : true
    24262608      });
    24272609    },
    2428     /**
    2429      * Destroys resources allocated by the page.
    2430      */
    2431     destroy: function PDFPageProxy_destroy() {
    2432       this.pendingDestroy = true;
    2433       this._tryDestroy();
    2434     },
    2435     /**
    2436      * For internal use only. Attempts to clean up if rendering is in a state
    2437      * where that's possible.
    2438      * @ignore
    2439      */
    2440     _tryDestroy: function PDFPageProxy__destroy() {
    2441       if (!this.pendingDestroy ||
    2442           Object.keys(this.intentStates).some(function(intent) {
    2443             var intentState = this.intentStates[intent];
    2444             return (intentState.renderTasks.length !== 0 ||
    2445                     intentState.receivingOperatorList);
    2446           }, this)) {
     2610    _destroy: function PDFPageProxy_destroy() {
     2611      this.destroyed = true;
     2612      this.transport.pageCache[this.pageIndex] = null;
     2613      var waitOn = [];
     2614      Object.keys(this.intentStates).forEach(function (intent) {
     2615        if (intent === 'oplist') {
     2616          return;
     2617        }
     2618        var intentState = this.intentStates[intent];
     2619        intentState.renderTasks.forEach(function (renderTask) {
     2620          var renderCompleted = renderTask.capability.promise.catch(function () {});
     2621          waitOn.push(renderCompleted);
     2622          renderTask.cancel();
     2623        });
     2624      }, this);
     2625      this.objs.clear();
     2626      this.annotationsPromise = null;
     2627      this.pendingCleanup = false;
     2628      return Promise.all(waitOn);
     2629    },
     2630    destroy: function () {
     2631      deprecated('page destroy method, use cleanup() instead');
     2632      this.cleanup();
     2633    },
     2634    cleanup: function PDFPageProxy_cleanup() {
     2635      this.pendingCleanup = true;
     2636      this._tryCleanup();
     2637    },
     2638    _tryCleanup: function PDFPageProxy_tryCleanup() {
     2639      if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
     2640        var intentState = this.intentStates[intent];
     2641        return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
     2642      }, this)) {
    24472643        return;
    24482644      }
    2449 
    2450       Object.keys(this.intentStates).forEach(function(intent) {
     2645      Object.keys(this.intentStates).forEach(function (intent) {
    24512646        delete this.intentStates[intent];
    24522647      }, this);
    24532648      this.objs.clear();
    24542649      this.annotationsPromise = null;
    2455       this.pendingDestroy = false;
    2456     },
    2457     /**
    2458      * For internal use only.
    2459      * @ignore
    2460      */
    2461     _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
    2462                                                             intent) {
     2650      this.pendingCleanup = false;
     2651    },
     2652    _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
    24632653      var intentState = this.intentStates[intent];
    2464       // TODO Refactor RenderPageRequest to separate rendering
    2465       // and operator list logic
    24662654      if (intentState.displayReadyCapability) {
    24672655        intentState.displayReadyCapability.resolve(transparency);
    24682656      }
    24692657    },
    2470     /**
    2471      * For internal use only.
    2472      * @ignore
    2473      */
    2474     _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
    2475                                                             intent) {
     2658    _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
    24762659      var intentState = this.intentStates[intent];
    24772660      var i, ii;
    2478       // Add the new chunk to the current operator list.
    24792661      for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
    24802662        intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
    2481         intentState.operatorList.argsArray.push(
    2482           operatorListChunk.argsArray[i]);
     2663        intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
    24832664      }
    24842665      intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
    2485 
    2486       // Notify all the rendering tasks there are more operators to be consumed.
    24872666      for (i = 0; i < intentState.renderTasks.length; i++) {
    24882667        intentState.renderTasks[i].operatorListChanged();
    24892668      }
    2490 
    24912669      if (operatorListChunk.lastChunk) {
    24922670        intentState.receivingOperatorList = false;
    2493         this._tryDestroy();
     2671        this._tryCleanup();
    24942672      }
    24952673    }
    24962674  };
    24972675  return PDFPageProxy;
    2498 })();
    2499 
    2500 /**
    2501  * For internal use only.
    2502  * @ignore
    2503  */
    2504 var WorkerTransport = (function WorkerTransportClosure() {
    2505   function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) {
     2676}();
     2677var PDFWorker = function PDFWorkerClosure() {
     2678  var nextFakeWorkerId = 0;
     2679  function getWorkerSrc() {
     2680    if (typeof workerSrc !== 'undefined') {
     2681      return workerSrc;
     2682    }
     2683    if (getDefaultSetting('workerSrc')) {
     2684      return getDefaultSetting('workerSrc');
     2685    }
     2686    if (pdfjsFilePath) {
     2687      return pdfjsFilePath.replace(/(\.(?:min\.)?js)$/i, '.worker$1');
     2688    }
     2689    error('No PDFJS.workerSrc specified');
     2690  }
     2691  var fakeWorkerFilesLoadedCapability;
     2692  function setupFakeWorkerGlobal() {
     2693    var WorkerMessageHandler;
     2694    if (fakeWorkerFilesLoadedCapability) {
     2695      return fakeWorkerFilesLoadedCapability.promise;
     2696    }
     2697    fakeWorkerFilesLoadedCapability = createPromiseCapability();
     2698    var loader = fakeWorkerFilesLoader || function (callback) {
     2699      Util.loadScript(getWorkerSrc(), function () {
     2700        callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
     2701      });
     2702    };
     2703    loader(fakeWorkerFilesLoadedCapability.resolve);
     2704    return fakeWorkerFilesLoadedCapability.promise;
     2705  }
     2706  function FakeWorkerPort(defer) {
     2707    this._listeners = [];
     2708    this._defer = defer;
     2709    this._deferred = Promise.resolve(undefined);
     2710  }
     2711  FakeWorkerPort.prototype = {
     2712    postMessage: function (obj, transfers) {
     2713      function cloneValue(value) {
     2714        if (typeof value !== 'object' || value === null) {
     2715          return value;
     2716        }
     2717        if (cloned.has(value)) {
     2718          return cloned.get(value);
     2719        }
     2720        var result;
     2721        var buffer;
     2722        if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
     2723          var transferable = transfers && transfers.indexOf(buffer) >= 0;
     2724          if (value === buffer) {
     2725            result = value;
     2726          } else if (transferable) {
     2727            result = new value.constructor(buffer, value.byteOffset, value.byteLength);
     2728          } else {
     2729            result = new value.constructor(value);
     2730          }
     2731          cloned.set(value, result);
     2732          return result;
     2733        }
     2734        result = isArray(value) ? [] : {};
     2735        cloned.set(value, result);
     2736        for (var i in value) {
     2737          var desc,
     2738              p = value;
     2739          while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
     2740            p = Object.getPrototypeOf(p);
     2741          }
     2742          if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
     2743            continue;
     2744          }
     2745          result[i] = cloneValue(desc.value);
     2746        }
     2747        return result;
     2748      }
     2749      if (!this._defer) {
     2750        this._listeners.forEach(function (listener) {
     2751          listener.call(this, { data: obj });
     2752        }, this);
     2753        return;
     2754      }
     2755      var cloned = new WeakMap();
     2756      var e = { data: cloneValue(obj) };
     2757      this._deferred.then(function () {
     2758        this._listeners.forEach(function (listener) {
     2759          listener.call(this, e);
     2760        }, this);
     2761      }.bind(this));
     2762    },
     2763    addEventListener: function (name, listener) {
     2764      this._listeners.push(listener);
     2765    },
     2766    removeEventListener: function (name, listener) {
     2767      var i = this._listeners.indexOf(listener);
     2768      this._listeners.splice(i, 1);
     2769    },
     2770    terminate: function () {
     2771      this._listeners = [];
     2772    }
     2773  };
     2774  function createCDNWrapper(url) {
     2775    var wrapper = 'importScripts(\'' + url + '\');';
     2776    return URL.createObjectURL(new Blob([wrapper]));
     2777  }
     2778  function PDFWorker(name, port) {
     2779    this.name = name;
     2780    this.destroyed = false;
     2781    this._readyCapability = createPromiseCapability();
     2782    this._port = null;
     2783    this._webWorker = null;
     2784    this._messageHandler = null;
     2785    if (port) {
     2786      this._initializeFromPort(port);
     2787      return;
     2788    }
     2789    this._initialize();
     2790  }
     2791  PDFWorker.prototype = {
     2792    get promise() {
     2793      return this._readyCapability.promise;
     2794    },
     2795    get port() {
     2796      return this._port;
     2797    },
     2798    get messageHandler() {
     2799      return this._messageHandler;
     2800    },
     2801    _initializeFromPort: function PDFWorker_initializeFromPort(port) {
     2802      this._port = port;
     2803      this._messageHandler = new MessageHandler('main', 'worker', port);
     2804      this._messageHandler.on('ready', function () {});
     2805      this._readyCapability.resolve();
     2806    },
     2807    _initialize: function PDFWorker_initialize() {
     2808      if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
     2809        var workerSrc = getWorkerSrc();
     2810        try {
     2811          if (!isSameOrigin(window.location.href, workerSrc)) {
     2812            workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
     2813          }
     2814          var worker = new Worker(workerSrc);
     2815          var messageHandler = new MessageHandler('main', 'worker', worker);
     2816          var terminateEarly = function () {
     2817            worker.removeEventListener('error', onWorkerError);
     2818            messageHandler.destroy();
     2819            worker.terminate();
     2820            if (this.destroyed) {
     2821              this._readyCapability.reject(new Error('Worker was destroyed'));
     2822            } else {
     2823              this._setupFakeWorker();
     2824            }
     2825          }.bind(this);
     2826          var onWorkerError = function (event) {
     2827            if (!this._webWorker) {
     2828              terminateEarly();
     2829            }
     2830          }.bind(this);
     2831          worker.addEventListener('error', onWorkerError);
     2832          messageHandler.on('test', function PDFWorker_test(data) {
     2833            worker.removeEventListener('error', onWorkerError);
     2834            if (this.destroyed) {
     2835              terminateEarly();
     2836              return;
     2837            }
     2838            var supportTypedArray = data && data.supportTypedArray;
     2839            if (supportTypedArray) {
     2840              this._messageHandler = messageHandler;
     2841              this._port = worker;
     2842              this._webWorker = worker;
     2843              if (!data.supportTransfers) {
     2844                isPostMessageTransfersDisabled = true;
     2845              }
     2846              this._readyCapability.resolve();
     2847              messageHandler.send('configure', { verbosity: getVerbosityLevel() });
     2848            } else {
     2849              this._setupFakeWorker();
     2850              messageHandler.destroy();
     2851              worker.terminate();
     2852            }
     2853          }.bind(this));
     2854          messageHandler.on('console_log', function (data) {
     2855            console.log.apply(console, data);
     2856          });
     2857          messageHandler.on('console_error', function (data) {
     2858            console.error.apply(console, data);
     2859          });
     2860          messageHandler.on('ready', function (data) {
     2861            worker.removeEventListener('error', onWorkerError);
     2862            if (this.destroyed) {
     2863              terminateEarly();
     2864              return;
     2865            }
     2866            try {
     2867              sendTest();
     2868            } catch (e) {
     2869              this._setupFakeWorker();
     2870            }
     2871          }.bind(this));
     2872          var sendTest = function () {
     2873            var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
     2874            var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
     2875            try {
     2876              messageHandler.send('test', testObj, [testObj.buffer]);
     2877            } catch (ex) {
     2878              info('Cannot use postMessage transfers');
     2879              testObj[0] = 0;
     2880              messageHandler.send('test', testObj);
     2881            }
     2882          };
     2883          sendTest();
     2884          return;
     2885        } catch (e) {
     2886          info('The worker has been disabled.');
     2887        }
     2888      }
     2889      this._setupFakeWorker();
     2890    },
     2891    _setupFakeWorker: function PDFWorker_setupFakeWorker() {
     2892      if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
     2893        warn('Setting up fake worker.');
     2894        isWorkerDisabled = true;
     2895      }
     2896      setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
     2897        if (this.destroyed) {
     2898          this._readyCapability.reject(new Error('Worker was destroyed'));
     2899          return;
     2900        }
     2901        var isTypedArraysPresent = Uint8Array !== Float32Array;
     2902        var port = new FakeWorkerPort(isTypedArraysPresent);
     2903        this._port = port;
     2904        var id = 'fake' + nextFakeWorkerId++;
     2905        var workerHandler = new MessageHandler(id + '_worker', id, port);
     2906        WorkerMessageHandler.setup(workerHandler, port);
     2907        var messageHandler = new MessageHandler(id, id + '_worker', port);
     2908        this._messageHandler = messageHandler;
     2909        this._readyCapability.resolve();
     2910      }.bind(this));
     2911    },
     2912    destroy: function PDFWorker_destroy() {
     2913      this.destroyed = true;
     2914      if (this._webWorker) {
     2915        this._webWorker.terminate();
     2916        this._webWorker = null;
     2917      }
     2918      this._port = null;
     2919      if (this._messageHandler) {
     2920        this._messageHandler.destroy();
     2921        this._messageHandler = null;
     2922      }
     2923    }
     2924  };
     2925  return PDFWorker;
     2926}();
     2927var WorkerTransport = function WorkerTransportClosure() {
     2928  function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport, CMapReaderFactory) {
     2929    this.messageHandler = messageHandler;
     2930    this.loadingTask = loadingTask;
    25062931    this.pdfDataRangeTransport = pdfDataRangeTransport;
    2507     this.workerInitializedCapability = workerInitializedCapability;
    25082932    this.commonObjs = new PDFObjects();
    2509 
    2510     this.loadingTask = null;
    2511 
     2933    this.fontLoader = new FontLoader(loadingTask.docId);
     2934    this.CMapReaderFactory = new CMapReaderFactory({
     2935      baseUrl: getDefaultSetting('cMapUrl'),
     2936      isCompressed: getDefaultSetting('cMapPacked')
     2937    });
     2938    this.destroyed = false;
     2939    this.destroyCapability = null;
     2940    this._passwordCapability = null;
    25122941    this.pageCache = [];
    25132942    this.pagePromises = [];
    25142943    this.downloadInfoCapability = createPromiseCapability();
    2515 
    2516     // If worker support isn't disabled explicit and the browser has worker
    2517     // support, create a new web worker and test if it/the browser fullfills
    2518     // all requirements to run parts of pdf.js in a web worker.
    2519     // Right now, the requirement is, that an Uint8Array is still an Uint8Array
    2520     // as it arrives on the worker. Chrome added this with version 15.
    2521     if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
    2522       var workerSrc = PDFJS.workerSrc;
    2523       if (!workerSrc) {
    2524         error('No PDFJS.workerSrc specified');
    2525       }
    2526 
    2527       try {
    2528         // Some versions of FF can't create a worker on localhost, see:
    2529         // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
    2530         var worker = new Worker(workerSrc);
    2531         var messageHandler = new MessageHandler('main', worker);
    2532         this.messageHandler = messageHandler;
    2533 
    2534         messageHandler.on('test', function transportTest(data) {
    2535           var supportTypedArray = data && data.supportTypedArray;
    2536           if (supportTypedArray) {
    2537             this.worker = worker;
    2538             if (!data.supportTransfers) {
    2539               PDFJS.postMessageTransfers = false;
    2540             }
    2541             this.setupMessageHandler(messageHandler);
    2542             workerInitializedCapability.resolve();
    2543           } else {
    2544             this.setupFakeWorker();
    2545           }
    2546         }.bind(this));
    2547 
    2548         var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
    2549         // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
    2550         // typed array. Also, checking if we can use transfers.
    2551         try {
    2552           messageHandler.send('test', testObj, [testObj.buffer]);
    2553         } catch (ex) {
    2554           info('Cannot use postMessage transfers');
    2555           testObj[0] = 0;
    2556           messageHandler.send('test', testObj);
    2557         }
    2558         return;
    2559       } catch (e) {
    2560         info('The worker has been disabled.');
    2561       }
    2562     }
    2563     // Either workers are disabled, not supported or have thrown an exception.
    2564     // Thus, we fallback to a faked worker.
    2565     this.setupFakeWorker();
     2944    this.setupMessageHandler();
    25662945  }
    25672946  WorkerTransport.prototype = {
    25682947    destroy: function WorkerTransport_destroy() {
     2948      if (this.destroyCapability) {
     2949        return this.destroyCapability.promise;
     2950      }
     2951      this.destroyed = true;
     2952      this.destroyCapability = createPromiseCapability();
     2953      if (this._passwordCapability) {
     2954        this._passwordCapability.reject(new Error('Worker was destroyed during onPassword callback'));
     2955      }
     2956      var waitOn = [];
     2957      this.pageCache.forEach(function (page) {
     2958        if (page) {
     2959          waitOn.push(page._destroy());
     2960        }
     2961      });
    25692962      this.pageCache = [];
    25702963      this.pagePromises = [];
    25712964      var self = this;
    2572       this.messageHandler.sendWithPromise('Terminate', null).then(function () {
    2573         FontLoader.clear();
    2574         if (self.worker) {
    2575           self.worker.terminate();
    2576         }
    2577       });
    2578     },
    2579 
    2580     setupFakeWorker: function WorkerTransport_setupFakeWorker() {
    2581       globalScope.PDFJS.disableWorker = true;
    2582 
    2583       if (!PDFJS.fakeWorkerFilesLoadedCapability) {
    2584         PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
    2585         // In the developer build load worker_loader which in turn loads all the
    2586         // other files and resolves the promise. In production only the
    2587         // pdf.worker.js file is needed.
    2588         Util.loadScript(PDFJS.workerSrc, function() {
    2589           PDFJS.fakeWorkerFilesLoadedCapability.resolve();
    2590         });
    2591       }
    2592       PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
    2593         warn('Setting up fake worker.');
    2594         // If we don't use a worker, just post/sendMessage to the main thread.
    2595         var fakeWorker = {
    2596           postMessage: function WorkerTransport_postMessage(obj) {
    2597             fakeWorker.onmessage({data: obj});
    2598           },
    2599           terminate: function WorkerTransport_terminate() {}
    2600         };
    2601 
    2602         var messageHandler = new MessageHandler('main', fakeWorker);
    2603         this.setupMessageHandler(messageHandler);
    2604 
    2605         // If the main thread is our worker, setup the handling for the messages
    2606         // the main thread sends to it self.
    2607         PDFJS.WorkerMessageHandler.setup(messageHandler);
    2608 
    2609         this.workerInitializedCapability.resolve();
    2610       }.bind(this));
    2611     },
    2612 
    2613     setupMessageHandler:
    2614       function WorkerTransport_setupMessageHandler(messageHandler) {
    2615       this.messageHandler = messageHandler;
    2616 
    2617       function updatePassword(password) {
    2618         messageHandler.send('UpdatePassword', password);
    2619       }
    2620 
     2965      var terminated = this.messageHandler.sendWithPromise('Terminate', null);
     2966      waitOn.push(terminated);
     2967      Promise.all(waitOn).then(function () {
     2968        self.fontLoader.clear();
     2969        if (self.pdfDataRangeTransport) {
     2970          self.pdfDataRangeTransport.abort();
     2971          self.pdfDataRangeTransport = null;
     2972        }
     2973        if (self.messageHandler) {
     2974          self.messageHandler.destroy();
     2975          self.messageHandler = null;
     2976        }
     2977        self.destroyCapability.resolve();
     2978      }, this.destroyCapability.reject);
     2979      return this.destroyCapability.promise;
     2980    },
     2981    setupMessageHandler: function WorkerTransport_setupMessageHandler() {
     2982      var messageHandler = this.messageHandler;
     2983      var loadingTask = this.loadingTask;
    26212984      var pdfDataRangeTransport = this.pdfDataRangeTransport;
    26222985      if (pdfDataRangeTransport) {
    2623         pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
     2986        pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
    26242987          messageHandler.send('OnDataRange', {
    26252988            begin: begin,
     
    26272990          });
    26282991        });
    2629 
    2630         pdfDataRangeTransport.addProgressListener(function(loaded) {
    2631           messageHandler.send('OnDataProgress', {
    2632             loaded: loaded
    2633           });
     2992        pdfDataRangeTransport.addProgressListener(function (loaded) {
     2993          messageHandler.send('OnDataProgress', { loaded: loaded });
    26342994        });
    2635 
    2636         pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
    2637           messageHandler.send('OnDataRange', {
    2638             chunk: chunk
    2639           });
     2995        pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
     2996          messageHandler.send('OnDataRange', { chunk: chunk });
    26402997        });
    2641 
    2642         messageHandler.on('RequestDataRange',
    2643           function transportDataRange(data) {
    2644             pdfDataRangeTransport.requestDataRange(data.begin, data.end);
    2645           }, this);
    2646       }
    2647 
     2998        messageHandler.on('RequestDataRange', function transportDataRange(data) {
     2999          pdfDataRangeTransport.requestDataRange(data.begin, data.end);
     3000        }, this);
     3001      }
    26483002      messageHandler.on('GetDoc', function transportDoc(data) {
    26493003        var pdfInfo = data.pdfInfo;
    26503004        this.numPages = data.pdfInfo.numPages;
    2651         var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
     3005        var loadingTask = this.loadingTask;
     3006        var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
    26523007        this.pdfDocument = pdfDocument;
    2653         this.loadingTask._capability.resolve(pdfDocument);
     3008        loadingTask._capability.resolve(pdfDocument);
    26543009      }, this);
    2655 
    2656       messageHandler.on('NeedPassword',
    2657                         function transportNeedPassword(exception) {
    2658         var loadingTask = this.loadingTask;
     3010      messageHandler.on('PasswordRequest', function transportPasswordRequest(exception) {
     3011        this._passwordCapability = createPromiseCapability();
    26593012        if (loadingTask.onPassword) {
    2660           return loadingTask.onPassword(updatePassword,
    2661                                         PasswordResponses.NEED_PASSWORD);
    2662         }
    2663         loadingTask._capability.reject(
    2664           new PasswordException(exception.message, exception.code));
     3013          var updatePassword = function (password) {
     3014            this._passwordCapability.resolve({ password: password });
     3015          }.bind(this);
     3016          loadingTask.onPassword(updatePassword, exception.code);
     3017        } else {
     3018          this._passwordCapability.reject(new PasswordException(exception.message, exception.code));
     3019        }
     3020        return this._passwordCapability.promise;
    26653021      }, this);
    2666 
    2667       messageHandler.on('IncorrectPassword',
    2668                         function transportIncorrectPassword(exception) {
    2669         var loadingTask = this.loadingTask;
    2670         if (loadingTask.onPassword) {
    2671           return loadingTask.onPassword(updatePassword,
    2672                                         PasswordResponses.INCORRECT_PASSWORD);
    2673         }
    2674         loadingTask._capability.reject(
    2675           new PasswordException(exception.message, exception.code));
     3022      messageHandler.on('PasswordException', function transportPasswordException(exception) {
     3023        loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
    26763024      }, this);
    2677 
    26783025      messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
    2679         this.loadingTask._capability.reject(
    2680           new InvalidPDFException(exception.message));
     3026        this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
    26813027      }, this);
    2682 
    26833028      messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
    2684         this.loadingTask._capability.reject(
    2685           new MissingPDFException(exception.message));
     3029        this.loadingTask._capability.reject(new MissingPDFException(exception.message));
    26863030      }, this);
    2687 
    2688       messageHandler.on('UnexpectedResponse',
    2689                         function transportUnexpectedResponse(exception) {
    2690         this.loadingTask._capability.reject(
    2691           new UnexpectedResponseException(exception.message, exception.status));
     3031      messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
     3032        this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
    26923033      }, this);
    2693 
    2694       messageHandler.on('UnknownError',
    2695                         function transportUnknownError(exception) {
    2696         this.loadingTask._capability.reject(
    2697           new UnknownErrorException(exception.message, exception.details));
     3034      messageHandler.on('UnknownError', function transportUnknownError(exception) {
     3035        this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
    26983036      }, this);
    2699 
    27003037      messageHandler.on('DataLoaded', function transportPage(data) {
    27013038        this.downloadInfoCapability.resolve(data);
    27023039      }, this);
    2703 
    27043040      messageHandler.on('PDFManagerReady', function transportPage(data) {
    27053041        if (this.pdfDataRangeTransport) {
     
    27073043        }
    27083044      }, this);
    2709 
    27103045      messageHandler.on('StartRenderPage', function transportRender(data) {
     3046        if (this.destroyed) {
     3047          return;
     3048        }
    27113049        var page = this.pageCache[data.pageIndex];
    2712 
    27133050        page.stats.timeEnd('Page Request');
    27143051        page._startRenderPage(data.transparency, data.intent);
    27153052      }, this);
    2716 
    27173053      messageHandler.on('RenderPageChunk', function transportRender(data) {
     3054        if (this.destroyed) {
     3055          return;
     3056        }
    27183057        var page = this.pageCache[data.pageIndex];
    2719 
    27203058        page._renderPageChunk(data.operatorList, data.intent);
    27213059      }, this);
    2722 
    27233060      messageHandler.on('commonobj', function transportObj(data) {
     3061        if (this.destroyed) {
     3062          return;
     3063        }
    27243064        var id = data[0];
    27253065        var type = data[1];
     
    27273067          return;
    27283068        }
    2729 
    27303069        switch (type) {
    27313070          case 'Font':
    27323071            var exportedData = data[2];
    2733 
    2734             var font;
    27353072            if ('error' in exportedData) {
    2736               var error = exportedData.error;
    2737               warn('Error during font loading: ' + error);
    2738               this.commonObjs.resolve(id, error);
     3073              var exportedError = exportedData.error;
     3074              warn('Error during font loading: ' + exportedError);
     3075              this.commonObjs.resolve(id, exportedError);
    27393076              break;
    2740             } else {
    2741               font = new FontFaceObject(exportedData);
    27423077            }
    2743 
    2744             FontLoader.bind(
    2745               [font],
    2746               function fontReady(fontObjs) {
    2747                 this.commonObjs.resolve(id, font);
    2748               }.bind(this)
    2749             );
     3078            var fontRegistry = null;
     3079            if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
     3080              fontRegistry = {
     3081                registerFont: function (font, url) {
     3082                  globalScope['FontInspector'].fontAdded(font, url);
     3083                }
     3084              };
     3085            }
     3086            var font = new FontFaceObject(exportedData, {
     3087              isEvalSuported: getDefaultSetting('isEvalSupported'),
     3088              disableFontFace: getDefaultSetting('disableFontFace'),
     3089              fontRegistry: fontRegistry
     3090            });
     3091            this.fontLoader.bind([font], function fontReady(fontObjs) {
     3092              this.commonObjs.resolve(id, font);
     3093            }.bind(this));
    27503094            break;
    27513095          case 'FontPath':
     
    27563100        }
    27573101      }, this);
    2758 
    27593102      messageHandler.on('obj', function transportObj(data) {
     3103        if (this.destroyed) {
     3104          return;
     3105        }
    27603106        var id = data[0];
    27613107        var pageIndex = data[1];
     
    27663112          return;
    27673113        }
    2768 
    27693114        switch (type) {
    27703115          case 'JpegStream':
     
    27753120            imageData = data[3];
    27763121            pageProxy.objs.resolve(id, imageData);
    2777 
    2778             // heuristics that will allow not to store large data
    27793122            var MAX_IMAGE_SIZE_TO_STORE = 8000000;
    2780             if (imageData && 'data' in imageData &&
    2781                 imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
     3123            if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
    27823124              pageProxy.cleanupAfterRender = true;
    27833125            }
     
    27873129        }
    27883130      }, this);
    2789 
    27903131      messageHandler.on('DocProgress', function transportDocProgress(data) {
     3132        if (this.destroyed) {
     3133          return;
     3134        }
    27913135        var loadingTask = this.loadingTask;
    27923136        if (loadingTask.onProgress) {
     
    27973141        }
    27983142      }, this);
    2799 
    28003143      messageHandler.on('PageError', function transportError(data) {
     3144        if (this.destroyed) {
     3145          return;
     3146        }
    28013147        var page = this.pageCache[data.pageNum - 1];
    28023148        var intentState = page.intentStates[data.intent];
     
    28063152          error(data.error);
    28073153        }
     3154        if (intentState.operatorList) {
     3155          intentState.operatorList.lastChunk = true;
     3156          for (var i = 0; i < intentState.renderTasks.length; i++) {
     3157            intentState.renderTasks[i].operatorListChanged();
     3158          }
     3159        }
    28083160      }, this);
    2809 
    2810       messageHandler.on('JpegDecode', function(data) {
     3161      messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
     3162        if (this.destroyed) {
     3163          return;
     3164        }
     3165        var featureId = data.featureId;
     3166        var loadingTask = this.loadingTask;
     3167        if (loadingTask.onUnsupportedFeature) {
     3168          loadingTask.onUnsupportedFeature(featureId);
     3169        }
     3170        _UnsupportedManager.notify(featureId);
     3171      }, this);
     3172      messageHandler.on('JpegDecode', function (data) {
     3173        if (this.destroyed) {
     3174          return Promise.reject(new Error('Worker was destroyed'));
     3175        }
     3176        if (typeof document === 'undefined') {
     3177          return Promise.reject(new Error('"document" is not defined.'));
     3178        }
    28113179        var imageUrl = data[0];
    28123180        var components = data[1];
    28133181        if (components !== 3 && components !== 1) {
    2814           return Promise.reject(
    2815             new Error('Only 3 components or 1 component can be returned'));
    2816         }
    2817 
     3182          return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
     3183        }
    28183184        return new Promise(function (resolve, reject) {
    28193185          var img = new Image();
     
    28243190            var rgbaLength = size * 4;
    28253191            var buf = new Uint8Array(size * components);
    2826             var tmpCanvas = createScratchCanvas(width, height);
     3192            var tmpCanvas = document.createElement('canvas');
     3193            tmpCanvas.width = width;
     3194            tmpCanvas.height = height;
    28273195            var tmpCtx = tmpCanvas.getContext('2d');
    28283196            tmpCtx.drawImage(img, 0, 0);
    28293197            var data = tmpCtx.getImageData(0, 0, width, height).data;
    28303198            var i, j;
    2831 
    28323199            if (components === 3) {
    28333200              for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
     
    28413208              }
    28423209            }
    2843             resolve({ data: buf, width: width, height: height});
     3210            resolve({
     3211              data: buf,
     3212              width: width,
     3213              height: height
     3214            });
    28443215          };
    28453216          img.onerror = function () {
     
    28483219          img.src = imageUrl;
    28493220        });
    2850       });
    2851     },
    2852 
    2853     fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) {
    2854       this.loadingTask = loadingTask;
    2855 
    2856       source.disableAutoFetch = PDFJS.disableAutoFetch;
    2857       source.disableStream = PDFJS.disableStream;
    2858       source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
    2859       if (this.pdfDataRangeTransport) {
    2860         source.length = this.pdfDataRangeTransport.length;
    2861         source.initialData = this.pdfDataRangeTransport.initialData;
    2862       }
    2863       this.messageHandler.send('GetDocRequest', {
    2864         source: source,
    2865         disableRange: PDFJS.disableRange,
    2866         maxImageSize: PDFJS.maxImageSize,
    2867         cMapUrl: PDFJS.cMapUrl,
    2868         cMapPacked: PDFJS.cMapPacked,
    2869         disableFontFace: PDFJS.disableFontFace,
    2870         disableCreateObjectURL: PDFJS.disableCreateObjectURL,
    2871         verbosity: PDFJS.verbosity
    2872       });
    2873     },
    2874 
     3221      }, this);
     3222      messageHandler.on('FetchBuiltInCMap', function (data) {
     3223        if (this.destroyed) {
     3224          return Promise.reject(new Error('Worker was destroyed'));
     3225        }
     3226        return this.CMapReaderFactory.fetch({ name: data.name });
     3227      }, this);
     3228    },
    28753229    getData: function WorkerTransport_getData() {
    28763230      return this.messageHandler.sendWithPromise('GetData', null);
    28773231    },
    2878 
    28793232    getPage: function WorkerTransport_getPage(pageNumber, capability) {
    2880       if (pageNumber <= 0 || pageNumber > this.numPages ||
    2881           (pageNumber|0) !== pageNumber) {
     3233      if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
    28823234        return Promise.reject(new Error('Invalid page request'));
    28833235      }
    2884 
    28853236      var pageIndex = pageNumber - 1;
    28863237      if (pageIndex in this.pagePromises) {
    28873238        return this.pagePromises[pageIndex];
    28883239      }
    2889       var promise = this.messageHandler.sendWithPromise('GetPage', {
    2890         pageIndex: pageIndex
    2891       }).then(function (pageInfo) {
     3240      var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
     3241        if (this.destroyed) {
     3242          throw new Error('Transport destroyed');
     3243        }
    28923244        var page = new PDFPageProxy(pageIndex, pageInfo, this);
    28933245        this.pageCache[pageIndex] = page;
     
    28973249      return promise;
    28983250    },
    2899 
    29003251    getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
    2901       return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
    2902     },
    2903 
    2904     getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
    2905       return this.messageHandler.sendWithPromise('GetAnnotations',
    2906         { pageIndex: pageIndex });
    2907     },
    2908 
     3252      return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
     3253        return Promise.reject(new Error(reason));
     3254      });
     3255    },
     3256    getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
     3257      return this.messageHandler.sendWithPromise('GetAnnotations', {
     3258        pageIndex: pageIndex,
     3259        intent: intent
     3260      });
     3261    },
    29093262    getDestinations: function WorkerTransport_getDestinations() {
    29103263      return this.messageHandler.sendWithPromise('GetDestinations', null);
    29113264    },
    2912 
    29133265    getDestination: function WorkerTransport_getDestination(id) {
    2914       return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
    2915     },
    2916 
     3266      return this.messageHandler.sendWithPromise('GetDestination', { id: id });
     3267    },
     3268    getPageLabels: function WorkerTransport_getPageLabels() {
     3269      return this.messageHandler.sendWithPromise('GetPageLabels', null);
     3270    },
    29173271    getAttachments: function WorkerTransport_getAttachments() {
    29183272      return this.messageHandler.sendWithPromise('GetAttachments', null);
    29193273    },
    2920 
    29213274    getJavaScript: function WorkerTransport_getJavaScript() {
    29223275      return this.messageHandler.sendWithPromise('GetJavaScript', null);
    29233276    },
    2924 
    29253277    getOutline: function WorkerTransport_getOutline() {
    29263278      return this.messageHandler.sendWithPromise('GetOutline', null);
    29273279    },
    2928 
    29293280    getMetadata: function WorkerTransport_getMetadata() {
    2930       return this.messageHandler.sendWithPromise('GetMetadata', null).
    2931         then(function transportMetadata(results) {
     3281      return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
    29323282        return {
    29333283          info: results[0],
    2934           metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
     3284          metadata: results[1] ? new Metadata(results[1]) : null
    29353285        };
    29363286      });
    29373287    },
    2938 
    29393288    getStats: function WorkerTransport_getStats() {
    29403289      return this.messageHandler.sendWithPromise('GetStats', null);
    29413290    },
    2942 
    29433291    startCleanup: function WorkerTransport_startCleanup() {
    2944       this.messageHandler.sendWithPromise('Cleanup', null).
    2945         then(function endCleanup() {
     3292      this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
    29463293        for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
    29473294          var page = this.pageCache[i];
    29483295          if (page) {
    2949             page.destroy();
     3296            page.cleanup();
    29503297          }
    29513298        }
    29523299        this.commonObjs.clear();
    2953         FontLoader.clear();
     3300        this.fontLoader.clear();
    29543301      }.bind(this));
    29553302    }
    29563303  };
    29573304  return WorkerTransport;
    2958 
    2959 })();
    2960 
    2961 /**
    2962  * A PDF document and page is built of many objects. E.g. there are objects
    2963  * for fonts, images, rendering code and such. These objects might get processed
    2964  * inside of a worker. The `PDFObjects` implements some basic functions to
    2965  * manage these objects.
    2966  * @ignore
    2967  */
    2968 var PDFObjects = (function PDFObjectsClosure() {
     3305}();
     3306var PDFObjects = function PDFObjectsClosure() {
    29693307  function PDFObjects() {
    2970     this.objs = {};
    2971   }
    2972 
     3308    this.objs = Object.create(null);
     3309  }
    29733310  PDFObjects.prototype = {
    2974     /**
    2975      * Internal function.
    2976      * Ensures there is an object defined for `objId`.
    2977      */
    29783311    ensureObj: function PDFObjects_ensureObj(objId) {
    29793312      if (this.objs[objId]) {
    29803313        return this.objs[objId];
    29813314      }
    2982 
    29833315      var obj = {
    29843316        capability: createPromiseCapability(),
     
    29873319      };
    29883320      this.objs[objId] = obj;
    2989 
    29903321      return obj;
    29913322    },
    2992 
    2993     /**
    2994      * If called *without* callback, this returns the data of `objId` but the
    2995      * object needs to be resolved. If it isn't, this function throws.
    2996      *
    2997      * If called *with* a callback, the callback is called with the data of the
    2998      * object once the object is resolved. That means, if you call this
    2999      * function and the object is already resolved, the callback gets called
    3000      * right away.
    3001      */
    30023323    get: function PDFObjects_get(objId, callback) {
    3003       // If there is a callback, then the get can be async and the object is
    3004       // not required to be resolved right now
    30053324      if (callback) {
    30063325        this.ensureObj(objId).capability.promise.then(callback);
    30073326        return null;
    30083327      }
    3009 
    3010       // If there isn't a callback, the user expects to get the resolved data
    3011       // directly.
    30123328      var obj = this.objs[objId];
    3013 
    3014       // If there isn't an object yet or the object isn't resolved, then the
    3015       // data isn't ready yet!
    30163329      if (!obj || !obj.resolved) {
    30173330        error('Requesting object that isn\'t resolved yet ' + objId);
    30183331      }
    3019 
    30203332      return obj.data;
    30213333    },
    3022 
    3023     /**
    3024      * Resolves the object `objId` with optional `data`.
    3025      */
    30263334    resolve: function PDFObjects_resolve(objId, data) {
    30273335      var obj = this.ensureObj(objId);
    3028 
    30293336      obj.resolved = true;
    30303337      obj.data = data;
    30313338      obj.capability.resolve(data);
    30323339    },
    3033 
    30343340    isResolved: function PDFObjects_isResolved(objId) {
    30353341      var objs = this.objs;
    3036 
    30373342      if (!objs[objId]) {
    30383343        return false;
    3039       } else {
    3040         return objs[objId].resolved;
    3041       }
    3042     },
    3043 
     3344      }
     3345      return objs[objId].resolved;
     3346    },
    30443347    hasData: function PDFObjects_hasData(objId) {
    30453348      return this.isResolved(objId);
    30463349    },
    3047 
    3048     /**
    3049      * Returns the data of `objId` if object exists, null otherwise.
    3050      */
    30513350    getData: function PDFObjects_getData(objId) {
    30523351      var objs = this.objs;
    30533352      if (!objs[objId] || !objs[objId].resolved) {
    30543353        return null;
    3055       } else {
    3056         return objs[objId].data;
    3057       }
    3058     },
    3059 
     3354      }
     3355      return objs[objId].data;
     3356    },
    30603357    clear: function PDFObjects_clear() {
    3061       this.objs = {};
     3358      this.objs = Object.create(null);
    30623359    }
    30633360  };
    30643361  return PDFObjects;
    3065 })();
    3066 
    3067 /**
    3068  * Allows controlling of the rendering tasks.
    3069  * @class
    3070  */
    3071 var RenderTask = (function RenderTaskClosure() {
     3362}();
     3363var RenderTask = function RenderTaskClosure() {
    30723364  function RenderTask(internalRenderTask) {
    30733365    this._internalRenderTask = internalRenderTask;
    3074 
    3075     /**
    3076      * Callback for incremental rendering -- a function that will be called
    3077      * each time the rendering is paused.  To continue rendering call the
    3078      * function that is the first argument to the callback.
    3079      * @type {function}
    3080      */
    30813366    this.onContinue = null;
    30823367  }
    3083 
    3084   RenderTask.prototype = /** @lends RenderTask.prototype */ {
    3085     /**
    3086      * Promise for rendering task completion.
    3087      * @return {Promise}
    3088      */
     3368  RenderTask.prototype = {
    30893369    get promise() {
    30903370      return this._internalRenderTask.capability.promise;
    30913371    },
    3092 
    3093     /**
    3094      * Cancels the rendering task. If the task is currently rendering it will
    3095      * not be cancelled until graphics pauses with a timeout. The promise that
    3096      * this object extends will resolved when cancelled.
    3097      */
    30983372    cancel: function RenderTask_cancel() {
    30993373      this._internalRenderTask.cancel();
    31003374    },
    3101 
    3102     /**
    3103      * Registers callbacks to indicate the rendering task completion.
    3104      *
    3105      * @param {function} onFulfilled The callback for the rendering completion.
    3106      * @param {function} onRejected The callback for the rendering failure.
    3107      * @return {Promise} A promise that is resolved after the onFulfilled or
    3108      *                   onRejected callback.
    3109      */
    31103375    then: function RenderTask_then(onFulfilled, onRejected) {
    31113376      return this.promise.then.apply(this.promise, arguments);
    31123377    }
    31133378  };
    3114 
    31153379  return RenderTask;
    3116 })();
    3117 
    3118 /**
    3119  * For internal use only.
    3120  * @ignore
    3121  */
    3122 var InternalRenderTask = (function InternalRenderTaskClosure() {
    3123 
    3124   function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
    3125                               pageNumber) {
     3380}();
     3381var InternalRenderTask = function InternalRenderTaskClosure() {
     3382  function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber, canvasFactory) {
    31263383    this.callback = callback;
    31273384    this.params = params;
     
    31313388    this.operatorList = operatorList;
    31323389    this.pageNumber = pageNumber;
     3390    this.canvasFactory = canvasFactory;
    31333391    this.running = false;
    31343392    this.graphicsReadyCallback = null;
    31353393    this.graphicsReady = false;
     3394    this.useRequestAnimationFrame = false;
    31363395    this.cancelled = false;
    31373396    this.capability = createPromiseCapability();
    31383397    this.task = new RenderTask(this);
    3139     // caching this-bound methods
    31403398    this._continueBound = this._continue.bind(this);
    31413399    this._scheduleNextBound = this._scheduleNext.bind(this);
    31423400    this._nextBound = this._next.bind(this);
    31433401  }
    3144 
    31453402  InternalRenderTask.prototype = {
    3146 
    3147     initalizeGraphics:
    3148         function InternalRenderTask_initalizeGraphics(transparency) {
    3149 
     3403    initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
    31503404      if (this.cancelled) {
    31513405        return;
    31523406      }
    3153       if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
    3154           globalScope.StepperManager.enabled) {
     3407      if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
    31553408        this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
    31563409        this.stepper.init(this.operatorList);
    31573410        this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
    31583411      }
    3159 
    31603412      var params = this.params;
    3161       this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
    3162                                     this.objs, params.imageLayer);
    3163 
    3164       this.gfx.beginDrawing(params.viewport, transparency);
     3413      this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, this.canvasFactory, params.imageLayer);
     3414      this.gfx.beginDrawing(params.transform, params.viewport, transparency);
    31653415      this.operatorListIdx = 0;
    31663416      this.graphicsReady = true;
     
    31693419      }
    31703420    },
    3171 
    31723421    cancel: function InternalRenderTask_cancel() {
    31733422      this.running = false;
    31743423      this.cancelled = true;
    3175       this.callback('cancelled');
    3176     },
    3177 
     3424      if (getDefaultSetting('pdfjsNext')) {
     3425        this.callback(new RenderingCancelledException('Rendering cancelled, page ' + this.pageNumber, 'canvas'));
     3426      } else {
     3427        this.callback('cancelled');
     3428      }
     3429    },
    31783430    operatorListChanged: function InternalRenderTask_operatorListChanged() {
    31793431      if (!this.graphicsReady) {
     
    31833435        return;
    31843436      }
    3185 
    31863437      if (this.stepper) {
    31873438        this.stepper.updateOperatorList(this.operatorList);
    31883439      }
    3189 
    31903440      if (this.running) {
    31913441        return;
     
    31933443      this._continue();
    31943444    },
    3195 
    31963445    _continue: function InternalRenderTask__continue() {
    31973446      this.running = true;
     
    32003449      }
    32013450      if (this.task.onContinue) {
    3202         this.task.onContinue.call(this.task, this._scheduleNextBound);
     3451        this.task.onContinue(this._scheduleNextBound);
    32033452      } else {
    32043453        this._scheduleNext();
    32053454      }
    32063455    },
    3207 
    32083456    _scheduleNext: function InternalRenderTask__scheduleNext() {
    3209       window.requestAnimationFrame(this._nextBound);
    3210     },
    3211 
     3457      if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
     3458        window.requestAnimationFrame(this._nextBound);
     3459      } else {
     3460        Promise.resolve(undefined).then(this._nextBound);
     3461      }
     3462    },
    32123463    _next: function InternalRenderTask__next() {
    32133464      if (this.cancelled) {
    32143465        return;
    32153466      }
    3216       this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
    3217                                         this.operatorListIdx,
    3218                                         this._continueBound,
    3219                                         this.stepper);
     3467      this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
    32203468      if (this.operatorListIdx === this.operatorList.argsArray.length) {
    32213469        this.running = false;
     
    32263474      }
    32273475    }
     3476  };
     3477  return InternalRenderTask;
     3478}();
     3479var _UnsupportedManager = function UnsupportedManagerClosure() {
     3480  var listeners = [];
     3481  return {
     3482    listen: function (cb) {
     3483      deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
     3484      listeners.push(cb);
     3485    },
     3486    notify: function (featureId) {
     3487      for (var i = 0, ii = listeners.length; i < ii; i++) {
     3488        listeners[i](featureId);
     3489      }
     3490    }
     3491  };
     3492}();
     3493exports.version = '1.8.188';
     3494exports.build = 'ad1023ff';
     3495exports.getDocument = getDocument;
     3496exports.PDFDataRangeTransport = PDFDataRangeTransport;
     3497exports.PDFWorker = PDFWorker;
     3498exports.PDFDocumentProxy = PDFDocumentProxy;
     3499exports.PDFPageProxy = PDFPageProxy;
     3500exports._UnsupportedManager = _UnsupportedManager;
    32283501
    3229   };
     3502/***/ }),
     3503/* 4 */
     3504/***/ (function(module, exports, __w_pdfjs_require__) {
    32303505
    3231   return InternalRenderTask;
    3232 })();
     3506"use strict";
    32333507
    32343508
    3235 var Metadata = PDFJS.Metadata = (function MetadataClosure() {
    3236   function fixMetadata(meta) {
    3237     return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
    3238       var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
    3239                                 function(code, d1, d2, d3) {
    3240         return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
    3241       });
    3242       var chars = '';
    3243       for (var i = 0; i < bytes.length; i += 2) {
    3244         var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
    3245         chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
    3246           code !== 38 && false ? String.fromCharCode(code) :
    3247           '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
    3248       }
    3249       return '>' + chars;
    3250     });
    3251   }
    3252 
    3253   function Metadata(meta) {
    3254     if (typeof meta === 'string') {
    3255       // Ghostscript produces invalid metadata
    3256       meta = fixMetadata(meta);
    3257 
    3258       var parser = new DOMParser();
    3259       meta = parser.parseFromString(meta, 'application/xml');
    3260     } else if (!(meta instanceof Document)) {
    3261       error('Metadata: Invalid metadata object');
    3262     }
    3263 
    3264     this.metaDocument = meta;
    3265     this.metadata = {};
    3266     this.parse();
    3267   }
    3268 
    3269   Metadata.prototype = {
    3270     parse: function Metadata_parse() {
    3271       var doc = this.metaDocument;
    3272       var rdf = doc.documentElement;
    3273 
    3274       if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
    3275         rdf = rdf.firstChild;
    3276         while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
    3277           rdf = rdf.nextSibling;
    3278         }
    3279       }
    3280 
    3281       var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
    3282       if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
    3283         return;
    3284       }
    3285 
    3286       var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
    3287       for (i = 0, length = children.length; i < length; i++) {
    3288         desc = children[i];
    3289         if (desc.nodeName.toLowerCase() !== 'rdf:description') {
    3290           continue;
    3291         }
    3292 
    3293         for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
    3294           if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
    3295             entry = desc.childNodes[ii];
    3296             name = entry.nodeName.toLowerCase();
    3297             this.metadata[name] = entry.textContent.trim();
    3298           }
    3299         }
    3300       }
    3301     },
    3302 
    3303     get: function Metadata_get(name) {
    3304       return this.metadata[name] || null;
    3305     },
    3306 
    3307     has: function Metadata_has(name) {
    3308       return typeof this.metadata[name] !== 'undefined';
    3309     }
     3509var sharedUtil = __w_pdfjs_require__(0);
     3510var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
     3511var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
     3512var ImageKind = sharedUtil.ImageKind;
     3513var OPS = sharedUtil.OPS;
     3514var Util = sharedUtil.Util;
     3515var isNum = sharedUtil.isNum;
     3516var isArray = sharedUtil.isArray;
     3517var warn = sharedUtil.warn;
     3518var createObjectURL = sharedUtil.createObjectURL;
     3519var SVG_DEFAULTS = {
     3520  fontStyle: 'normal',
     3521  fontWeight: 'normal',
     3522  fillColor: '#000000'
     3523};
     3524var convertImgDataToPng = function convertImgDataToPngClosure() {
     3525  var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
     3526  var CHUNK_WRAPPER_SIZE = 12;
     3527  var crcTable = new Int32Array(256);
     3528  for (var i = 0; i < 256; i++) {
     3529    var c = i;
     3530    for (var h = 0; h < 8; h++) {
     3531      if (c & 1) {
     3532        c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
     3533      } else {
     3534        c = c >> 1 & 0x7fffffff;
     3535      }
     3536    }
     3537    crcTable[i] = c;
     3538  }
     3539  function crc32(data, start, end) {
     3540    var crc = -1;
     3541    for (var i = start; i < end; i++) {
     3542      var a = (crc ^ data[i]) & 0xff;
     3543      var b = crcTable[a];
     3544      crc = crc >>> 8 ^ b;
     3545    }
     3546    return crc ^ -1;
     3547  }
     3548  function writePngChunk(type, body, data, offset) {
     3549    var p = offset;
     3550    var len = body.length;
     3551    data[p] = len >> 24 & 0xff;
     3552    data[p + 1] = len >> 16 & 0xff;
     3553    data[p + 2] = len >> 8 & 0xff;
     3554    data[p + 3] = len & 0xff;
     3555    p += 4;
     3556    data[p] = type.charCodeAt(0) & 0xff;
     3557    data[p + 1] = type.charCodeAt(1) & 0xff;
     3558    data[p + 2] = type.charCodeAt(2) & 0xff;
     3559    data[p + 3] = type.charCodeAt(3) & 0xff;
     3560    p += 4;
     3561    data.set(body, p);
     3562    p += body.length;
     3563    var crc = crc32(data, offset + 4, p);
     3564    data[p] = crc >> 24 & 0xff;
     3565    data[p + 1] = crc >> 16 & 0xff;
     3566    data[p + 2] = crc >> 8 & 0xff;
     3567    data[p + 3] = crc & 0xff;
     3568  }
     3569  function adler32(data, start, end) {
     3570    var a = 1;
     3571    var b = 0;
     3572    for (var i = start; i < end; ++i) {
     3573      a = (a + (data[i] & 0xff)) % 65521;
     3574      b = (b + a) % 65521;
     3575    }
     3576    return b << 16 | a;
     3577  }
     3578  function encode(imgData, kind, forceDataSchema) {
     3579    var width = imgData.width;
     3580    var height = imgData.height;
     3581    var bitDepth, colorType, lineSize;
     3582    var bytes = imgData.data;
     3583    switch (kind) {
     3584      case ImageKind.GRAYSCALE_1BPP:
     3585        colorType = 0;
     3586        bitDepth = 1;
     3587        lineSize = width + 7 >> 3;
     3588        break;
     3589      case ImageKind.RGB_24BPP:
     3590        colorType = 2;
     3591        bitDepth = 8;
     3592        lineSize = width * 3;
     3593        break;
     3594      case ImageKind.RGBA_32BPP:
     3595        colorType = 6;
     3596        bitDepth = 8;
     3597        lineSize = width * 4;
     3598        break;
     3599      default:
     3600        throw new Error('invalid format');
     3601    }
     3602    var literals = new Uint8Array((1 + lineSize) * height);
     3603    var offsetLiterals = 0,
     3604        offsetBytes = 0;
     3605    var y, i;
     3606    for (y = 0; y < height; ++y) {
     3607      literals[offsetLiterals++] = 0;
     3608      literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
     3609      offsetBytes += lineSize;
     3610      offsetLiterals += lineSize;
     3611    }
     3612    if (kind === ImageKind.GRAYSCALE_1BPP) {
     3613      offsetLiterals = 0;
     3614      for (y = 0; y < height; y++) {
     3615        offsetLiterals++;
     3616        for (i = 0; i < lineSize; i++) {
     3617          literals[offsetLiterals++] ^= 0xFF;
     3618        }
     3619      }
     3620    }
     3621    var ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]);
     3622    var len = literals.length;
     3623    var maxBlockLength = 0xFFFF;
     3624    var deflateBlocks = Math.ceil(len / maxBlockLength);
     3625    var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
     3626    var pi = 0;
     3627    idat[pi++] = 0x78;
     3628    idat[pi++] = 0x9c;
     3629    var pos = 0;
     3630    while (len > maxBlockLength) {
     3631      idat[pi++] = 0x00;
     3632      idat[pi++] = 0xff;
     3633      idat[pi++] = 0xff;
     3634      idat[pi++] = 0x00;
     3635      idat[pi++] = 0x00;
     3636      idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
     3637      pi += maxBlockLength;
     3638      pos += maxBlockLength;
     3639      len -= maxBlockLength;
     3640    }
     3641    idat[pi++] = 0x01;
     3642    idat[pi++] = len & 0xff;
     3643    idat[pi++] = len >> 8 & 0xff;
     3644    idat[pi++] = ~len & 0xffff & 0xff;
     3645    idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
     3646    idat.set(literals.subarray(pos), pi);
     3647    pi += literals.length - pos;
     3648    var adler = adler32(literals, 0, literals.length);
     3649    idat[pi++] = adler >> 24 & 0xff;
     3650    idat[pi++] = adler >> 16 & 0xff;
     3651    idat[pi++] = adler >> 8 & 0xff;
     3652    idat[pi++] = adler & 0xff;
     3653    var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
     3654    var data = new Uint8Array(pngLength);
     3655    var offset = 0;
     3656    data.set(PNG_HEADER, offset);
     3657    offset += PNG_HEADER.length;
     3658    writePngChunk('IHDR', ihdr, data, offset);
     3659    offset += CHUNK_WRAPPER_SIZE + ihdr.length;
     3660    writePngChunk('IDATA', idat, data, offset);
     3661    offset += CHUNK_WRAPPER_SIZE + idat.length;
     3662    writePngChunk('IEND', new Uint8Array(0), data, offset);
     3663    return createObjectURL(data, 'image/png', forceDataSchema);
     3664  }
     3665  return function convertImgDataToPng(imgData, forceDataSchema) {
     3666    var kind = imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind;
     3667    return encode(imgData, kind, forceDataSchema);
    33103668  };
    3311 
    3312   return Metadata;
    3313 })();
    3314 
    3315 
    3316 // <canvas> contexts store most of the state we need natively.
    3317 // However, PDF needs a bit more state, which we store here.
    3318 
    3319 // Minimal font size that would be used during canvas fillText operations.
    3320 var MIN_FONT_SIZE = 16;
    3321 // Maximum font size that would be used during canvas fillText operations.
    3322 var MAX_FONT_SIZE = 100;
    3323 var MAX_GROUP_SIZE = 4096;
    3324 
    3325 // Heuristic value used when enforcing minimum line widths.
    3326 var MIN_WIDTH_FACTOR = 0.65;
    3327 
    3328 var COMPILE_TYPE3_GLYPHS = true;
    3329 var MAX_SIZE_TO_COMPILE = 1000;
    3330 
    3331 var FULL_CHUNK_HEIGHT = 16;
    3332 
    3333 function createScratchCanvas(width, height) {
    3334   var canvas = document.createElement('canvas');
    3335   canvas.width = width;
    3336   canvas.height = height;
    3337   return canvas;
    3338 }
    3339 
    3340 function addContextCurrentTransform(ctx) {
    3341   // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
    3342   if (!ctx.mozCurrentTransform) {
    3343     // Store the original context
    3344     ctx._scaleX = ctx._scaleX || 1.0;
    3345     ctx._scaleY = ctx._scaleY || 1.0;
    3346     ctx._originalSave = ctx.save;
    3347     ctx._originalRestore = ctx.restore;
    3348     ctx._originalRotate = ctx.rotate;
    3349     ctx._originalScale = ctx.scale;
    3350     ctx._originalTranslate = ctx.translate;
    3351     ctx._originalTransform = ctx.transform;
    3352     ctx._originalSetTransform = ctx.setTransform;
    3353 
    3354     ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
    3355     ctx._transformStack = [];
    3356 
    3357     Object.defineProperty(ctx, 'mozCurrentTransform', {
    3358       get: function getCurrentTransform() {
    3359         return this._transformMatrix;
    3360       }
    3361     });
    3362 
    3363     Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
    3364       get: function getCurrentTransformInverse() {
    3365         // Calculation done using WolframAlpha:
    3366         // http://www.wolframalpha.com/input/?
    3367         //   i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
    3368 
    3369         var m = this._transformMatrix;
    3370         var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
    3371 
    3372         var ad_bc = a * d - b * c;
    3373         var bc_ad = b * c - a * d;
    3374 
    3375         return [
    3376           d / ad_bc,
    3377           b / bc_ad,
    3378           c / bc_ad,
    3379           a / ad_bc,
    3380           (d * e - c * f) / bc_ad,
    3381           (b * e - a * f) / ad_bc
    3382         ];
    3383       }
    3384     });
    3385 
    3386     ctx.save = function ctxSave() {
    3387       var old = this._transformMatrix;
    3388       this._transformStack.push(old);
    3389       this._transformMatrix = old.slice(0, 6);
    3390 
    3391       this._originalSave();
    3392     };
    3393 
    3394     ctx.restore = function ctxRestore() {
    3395       var prev = this._transformStack.pop();
    3396       if (prev) {
    3397         this._transformMatrix = prev;
    3398         this._originalRestore();
    3399       }
    3400     };
    3401 
    3402     ctx.translate = function ctxTranslate(x, y) {
    3403       var m = this._transformMatrix;
    3404       m[4] = m[0] * x + m[2] * y + m[4];
    340