Changeset 104953 in spip-zone
- Timestamp:
- Jun 23, 2017, 5:05:40 PM (2 years ago)
- 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 4 2 * 5 3 * Licensed under the Apache License, Version 2.0 (the "License"); … … 15 13 * limitations under the License. 16 14 */ 17 /*jshint globalstrict: false */18 /* globals PDFJS */19 15 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() { 26 return /******/ (function(modules) { // webpackBootstrap 27 /******/ // The module cache 28 /******/ var installedModules = {}; 24 29 25 PDFJS.version = '1.1.3'; 26 PDFJS.build = '05991e9'; 30 /******/ // The require function 31 /******/ function __w_pdfjs_require__(moduleId) { 27 32 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; 31 36 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 /******/ }; 50 43 51 'use strict'; 44 /******/ // Execute the module function 45 /******/ modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__); 52 46 53 var globalScope = (typeof window === 'undefined') ? this : window; 47 /******/ // Flag the module as loaded 48 /******/ module.l = true; 54 49 55 var isWorker = (typeof window === 'undefined'); 50 /******/ // Return the exports of the module 51 /******/ return module.exports; 52 /******/ } 56 53 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 101 var compatibility = __w_pdfjs_require__(13); 102 var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : undefined; 57 103 var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; 58 59 104 var TextRenderingMode = { 60 105 FILL: 0, … … 69 114 ADD_TO_PATH_FLAG: 4 70 115 }; 71 72 116 var ImageKind = { 73 117 GRAYSCALE_1BPP: 1, … … 75 119 RGBA_32BPP: 3 76 120 }; 77 78 121 var 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 82 148 }; 83 149 var 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 }; 161 var 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 }; 182 var AnnotationBorderStyleType = { 183 SOLID: 1, 184 DASHED: 2, 185 BEVELED: 3, 186 INSET: 4, 187 UNDERLINE: 5 188 }; 84 189 var StreamType = { 85 190 UNKNOWN: 0, … … 94 199 RL: 9 95 200 }; 96 97 201 var FontType = { 98 202 UNKNOWN: 0, … … 108 212 MMTYPE1: 10 109 213 }; 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 = { 214 var VERBOSITY_LEVELS = { 121 215 errors: 0, 122 216 warnings: 1, 123 217 infos: 5 124 218 }; 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. 219 var CMapCompressionType = { 220 NONE: 0, 221 BINARY: 1, 222 STREAM: 2 223 }; 224 var OPS = { 130 225 dependency: 1, 131 226 setLineWidth: 2, … … 220 315 constructPath: 91 221 316 }; 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. 317 var verbosity = VERBOSITY_LEVELS.warnings; 318 function setVerbosityLevel(level) { 319 verbosity = level; 320 } 321 function getVerbosityLevel() { 322 return verbosity; 323 } 226 324 function info(msg) { 227 if ( PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {325 if (verbosity >= VERBOSITY_LEVELS.infos) { 228 326 console.log('Info: ' + msg); 229 327 } 230 328 } 231 232 // Non-fatal warnings.233 329 function warn(msg) { 234 if ( PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {330 if (verbosity >= VERBOSITY_LEVELS.warnings) { 235 331 console.log('Warning: ' + msg); 236 332 } 237 333 } 238 239 // Fatal errors that should trigger the fallback UI and halt execution by 240 // throwing an exception. 334 function deprecated(details) { 335 console.log('Deprecated API usage: ' + details); 336 } 241 337 function 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) { 250 339 console.log('Error: ' + msg); 251 } 252 console.log(backtrace()); 253 UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); 340 console.log(backtrace()); 341 } 254 342 throw new Error(msg); 255 343 } 256 257 344 function backtrace() { 258 345 try { … … 262 349 } 263 350 } 264 265 351 function assert(cond, msg) { 266 352 if (!cond) { … … 268 354 } 269 355 } 270 271 var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { 356 var UNSUPPORTED_FEATURES = { 272 357 unknown: 'unknown', 273 358 forms: 'forms', … … 277 362 font: 'font' 278 363 }; 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 } 364 function 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; 325 375 } 326 327 // Validates if URL is safe and allowed, e.g. to avoid XSS. 328 function isValidUrl(url, allowRelative) { 376 function isValidProtocol(url) { 329 377 if (!url) { 330 378 return false; 331 379 } 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:': 345 386 return true; 346 387 default: … … 348 389 } 349 390 } 350 PDFJS.isValidUrl = isValidUrl; 351 391 function 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 } 352 403 function 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 }); 357 410 return value; 358 411 } 359 PDFJS.shadow = shadow; 360 361 var PasswordResponses = PDFJS.PasswordResponses = { 412 function 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 } 423 var PasswordResponses = { 362 424 NEED_PASSWORD: 1, 363 425 INCORRECT_PASSWORD: 2 364 426 }; 365 366 var PasswordException = (function PasswordExceptionClosure() { 427 var PasswordException = function PasswordExceptionClosure() { 367 428 function PasswordException(msg, code) { 368 429 this.name = 'PasswordException'; … … 370 431 this.code = code; 371 432 } 372 373 433 PasswordException.prototype = new Error(); 374 434 PasswordException.constructor = PasswordException; 375 376 435 return PasswordException; 377 })(); 378 PDFJS.PasswordException = PasswordException; 379 380 var UnknownErrorException = (function UnknownErrorExceptionClosure() { 436 }(); 437 var UnknownErrorException = function UnknownErrorExceptionClosure() { 381 438 function UnknownErrorException(msg, details) { 382 439 this.name = 'UnknownErrorException'; … … 384 441 this.details = details; 385 442 } 386 387 443 UnknownErrorException.prototype = new Error(); 388 444 UnknownErrorException.constructor = UnknownErrorException; 389 390 445 return UnknownErrorException; 391 })(); 392 PDFJS.UnknownErrorException = UnknownErrorException; 393 394 var InvalidPDFException = (function InvalidPDFExceptionClosure() { 446 }(); 447 var InvalidPDFException = function InvalidPDFExceptionClosure() { 395 448 function InvalidPDFException(msg) { 396 449 this.name = 'InvalidPDFException'; 397 450 this.message = msg; 398 451 } 399 400 452 InvalidPDFException.prototype = new Error(); 401 453 InvalidPDFException.constructor = InvalidPDFException; 402 403 454 return InvalidPDFException; 404 })(); 405 PDFJS.InvalidPDFException = InvalidPDFException; 406 407 var MissingPDFException = (function MissingPDFExceptionClosure() { 455 }(); 456 var MissingPDFException = function MissingPDFExceptionClosure() { 408 457 function MissingPDFException(msg) { 409 458 this.name = 'MissingPDFException'; 410 459 this.message = msg; 411 460 } 412 413 461 MissingPDFException.prototype = new Error(); 414 462 MissingPDFException.constructor = MissingPDFException; 415 416 463 return MissingPDFException; 417 })(); 418 PDFJS.MissingPDFException = MissingPDFException; 419 420 var UnexpectedResponseException = 421 (function UnexpectedResponseExceptionClosure() { 464 }(); 465 var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() { 422 466 function UnexpectedResponseException(msg, status) { 423 467 this.name = 'UnexpectedResponseException'; … … 425 469 this.status = status; 426 470 } 427 428 471 UnexpectedResponseException.prototype = new Error(); 429 472 UnexpectedResponseException.constructor = UnexpectedResponseException; 430 431 473 return UnexpectedResponseException; 432 })(); 433 PDFJS.UnexpectedResponseException = UnexpectedResponseException; 434 435 var NotImplementedException = (function NotImplementedExceptionClosure() { 474 }(); 475 var NotImplementedException = function NotImplementedExceptionClosure() { 436 476 function NotImplementedException(msg) { 437 477 this.message = msg; 438 478 } 439 440 479 NotImplementedException.prototype = new Error(); 441 480 NotImplementedException.prototype.name = 'NotImplementedException'; 442 481 NotImplementedException.constructor = NotImplementedException; 443 444 482 return NotImplementedException; 445 })(); 446 447 var MissingDataException = (function MissingDataExceptionClosure() { 483 }(); 484 var MissingDataException = function MissingDataExceptionClosure() { 448 485 function MissingDataException(begin, end) { 449 486 this.begin = begin; … … 451 488 this.message = 'Missing data [' + begin + ', ' + end + ')'; 452 489 } 453 454 490 MissingDataException.prototype = new Error(); 455 491 MissingDataException.prototype.name = 'MissingDataException'; 456 492 MissingDataException.constructor = MissingDataException; 457 458 493 return MissingDataException; 459 })(); 460 461 var XRefParseException = (function XRefParseExceptionClosure() { 494 }(); 495 var XRefParseException = function XRefParseExceptionClosure() { 462 496 function XRefParseException(msg) { 463 497 this.message = msg; 464 498 } 465 466 499 XRefParseException.prototype = new Error(); 467 500 XRefParseException.prototype.name = 'XRefParseException'; 468 501 XRefParseException.constructor = XRefParseException; 469 470 502 return XRefParseException; 471 })(); 472 473 503 }(); 504 var NullCharactersRegExp = /\x00/g; 505 function 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 } 474 512 function 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'); 477 514 var length = bytes.length; 478 515 var MAX_ARGUMENT_COUNT = 8192; … … 488 525 return strBuf.join(''); 489 526 } 490 491 527 function stringToBytes(str) { 492 528 assert(typeof str === 'string', 'Invalid argument for stringToBytes'); … … 498 534 return bytes; 499 535 } 500 536 function arrayByteLength(arr) { 537 if (arr.length !== undefined) { 538 return arr.length; 539 } 540 assert(arr.byteLength !== undefined); 541 return arr.byteLength; 542 } 543 function 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 } 501 573 function 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); 504 575 } 505 506 576 function log2(x) { 507 var n = 1, i = 0; 577 var n = 1, 578 i = 0; 508 579 while (x > n) { 509 580 n <<= 1; … … 512 583 return i; 513 584 } 514 515 585 function readInt8(data, start) { 516 return (data[start] << 24)>> 24;586 return data[start] << 24 >> 24; 517 587 } 518 519 588 function readUint16(data, offset) { 520 return (data[offset] << 8)| data[offset + 1];589 return data[offset] << 8 | data[offset + 1]; 521 590 } 522 523 591 function 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; 526 593 } 527 528 // Lazy test the endianness of the platform529 // NOTE: This will be 'true' for simulated TypedArrays530 594 function isLittleEndian() { 531 595 var buffer8 = new Uint8Array(2); 532 596 buffer8[0] = 1; 533 597 var buffer16 = new Uint16Array(buffer8.buffer); 534 return (buffer16[0] === 1);598 return buffer16[0] === 1; 535 599 } 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'); 600 function isEvalSupported() { 601 try { 602 new Function(''); 603 return true; 604 } catch (e) { 605 return false; 606 } 551 607 } 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 608 var Uint32ArrayView = function Uint32ArrayViewClosure() { 562 609 function Uint32ArrayView(buffer, length) { 563 610 this.buffer = buffer; 564 611 this.byteLength = buffer.length; 565 this.length = length === undefined ? (this.byteLength >> 2): length;612 this.length = length === undefined ? this.byteLength >> 2 : length; 566 613 ensureUint32ArrayViewProps(this.length); 567 614 } 568 615 Uint32ArrayView.prototype = Object.create(null); 569 570 616 var uint32ArrayViewSetters = 0; 571 617 function createUint32ArrayProp(index) { 572 618 return { 573 619 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; 577 623 }, 578 624 set: function (value) { 579 var buffer = this.buffer, offset = index << 2; 625 var buffer = this.buffer, 626 offset = index << 2; 580 627 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; 584 631 } 585 632 }; 586 633 } 587 588 634 function ensureUint32ArrayViewProps(length) { 589 635 while (uint32ArrayViewSetters < length) { 590 Object.defineProperty(Uint32ArrayView.prototype, 591 uint32ArrayViewSetters, 592 createUint32ArrayProp(uint32ArrayViewSetters)); 636 Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); 593 637 uint32ArrayViewSetters++; 594 638 } 595 639 } 596 597 640 return Uint32ArrayView; 598 } )();599 641 }(); 642 exports.Uint32ArrayView = Uint32ArrayView; 600 643 var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; 601 602 var Util = PDFJS.Util = (function UtilClosure() { 644 var Util = function UtilClosure() { 603 645 function Util() {} 604 605 646 var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; 606 607 // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids608 // creating many intermediate strings.609 647 Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { 610 648 rgbBuf[1] = r; … … 613 651 return rgbBuf.join(''); 614 652 }; 615 616 // Concatenates two transformation matrices together and returns the result.617 653 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]]; 626 655 }; 627 628 // For 2d affine transforms629 656 Util.applyTransform = function Util_applyTransform(p, m) { 630 657 var xt = p[0] * m[0] + p[1] * m[2] + m[4]; … … 632 659 return [xt, yt]; 633 660 }; 634 635 661 Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { 636 662 var d = m[0] * m[3] - m[1] * m[2]; … … 639 665 return [xt, yt]; 640 666 }; 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) { 647 668 var p1 = Util.applyTransform(r, m); 648 669 var p2 = Util.applyTransform(r.slice(2, 4), m); 649 670 var p3 = Util.applyTransform([r[0], r[3]], m); 650 671 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])]; 657 673 }; 658 659 674 Util.inverseTransform = function Util_inverseTransform(m) { 660 675 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]; 663 677 }; 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]671 678 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]]; 677 680 }; 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) { 685 682 var transpose = [m[0], m[2], m[1], m[3]]; 686 687 // Multiply matrix m with its transpose.688 683 var a = m[0] * transpose[0] + m[1] * transpose[2]; 689 684 var b = m[0] * transpose[1] + m[1] * transpose[3]; 690 685 var c = m[2] * transpose[0] + m[3] * transpose[2]; 691 686 var d = m[2] * transpose[1] + m[3] * transpose[3]; 692 693 // Solve the second degree polynomial to get roots.694 687 var first = (a + d) / 2; 695 688 var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; 696 689 var sx = first + second || 1; 697 690 var sy = first - second || 1; 698 699 // Scale values are the square roots of the eigenvalues.700 691 return [Math.sqrt(sx), Math.sqrt(sy)]; 701 692 }; 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, this705 // means normalization to (BL,TR) ordering. For systems with origin in the706 // top-left, this means (TL,BR) ordering.707 693 Util.normalizeRect = function Util_normalizeRect(rect) { 708 var r = rect.slice(0); // clone rect694 var r = rect.slice(0); 709 695 if (rect[0] > rect[2]) { 710 696 r[0] = rect[2]; … … 717 703 return r; 718 704 }; 719 720 // Returns a rectangle [x1, y1, x2, y2] corresponding to the721 // intersection of rect1 and rect2. If no intersection, returns 'false'722 // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]723 705 Util.intersect = function Util_intersect(rect1, rect2) { 724 706 function compare(a, b) { 725 707 return a - b; 726 708 } 727 728 // Order points along the axes729 709 var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), 730 710 orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), 731 711 result = []; 732 733 712 rect1 = Util.normalizeRect(rect1); 734 713 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]) { 740 715 result[0] = orderedX[1]; 741 716 result[2] = orderedX[2]; … … 743 718 return false; 744 719 } 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]) { 750 721 result[1] = orderedY[1]; 751 722 result[3] = orderedY[2]; … … 753 724 return false; 754 725 } 755 756 726 return result; 757 727 }; 758 759 728 Util.sign = function Util_sign(num) { 760 729 return num < 0 ? -1 : 1; 761 730 }; 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 }; 763 750 Util.appendToArray = function Util_appendToArray(arr1, arr2) { 764 751 Array.prototype.push.apply(arr1, arr2); 765 752 }; 766 767 753 Util.prependToArray = function Util_prependToArray(arr1, arr2) { 768 754 Array.prototype.unshift.apply(arr1, arr2); 769 755 }; 770 771 756 Util.extendObj = function extendObj(obj1, obj2) { 772 757 for (var key in obj2) { … … 774 759 } 775 760 }; 776 777 Util.getInheritableProperty = function Util_getInheritableProperty(dict, 778 name) { 761 Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) { 779 762 while (dict && !dict.has(name)) { 780 763 dict = dict.get('Parent'); … … 783 766 return null; 784 767 } 785 return dict.get(name);768 return getArray ? dict.getArray(name) : dict.get(name); 786 769 }; 787 788 770 Util.inherit = function Util_inherit(sub, base, prototype) { 789 771 sub.prototype = Object.create(base.prototype); … … 793 775 } 794 776 }; 795 796 777 Util.loadScript = function Util_loadScript(src, callback) { 797 778 var script = document.createElement('script'); … … 799 780 script.setAttribute('src', src); 800 781 if (callback) { 801 script.onload = function () {782 script.onload = function () { 802 783 if (!loaded) { 803 784 callback(); … … 808 789 document.getElementsByTagName('head')[0].appendChild(script); 809 790 }; 810 811 791 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 }(); 793 var PageViewport = function PageViewportClosure() { 830 794 function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { 831 795 this.viewBox = viewBox; … … 834 798 this.offsetX = offsetX; 835 799 this.offsetY = offsetY; 836 837 // creating transform to convert pdf coordinate system to the normal838 // canvas like coordinates taking in account scale and rotation839 800 var centerX = (viewBox[2] + viewBox[0]) / 2; 840 801 var centerY = (viewBox[3] + viewBox[1]) / 2; … … 844 805 switch (rotation) { 845 806 case 180: 846 rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; 807 rotateA = -1; 808 rotateB = 0; 809 rotateC = 0; 810 rotateD = 1; 847 811 break; 848 812 case 90: 849 rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; 813 rotateA = 0; 814 rotateB = 1; 815 rotateC = 1; 816 rotateD = 0; 850 817 break; 851 818 case 270: 852 rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; 819 rotateA = 0; 820 rotateB = -1; 821 rotateC = -1; 822 rotateD = 0; 853 823 break; 854 //case 0:855 824 default: 856 rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; 825 rotateA = 1; 826 rotateB = 0; 827 rotateC = 0; 828 rotateD = -1; 857 829 break; 858 830 } 859 860 831 if (dontFlip) { 861 rotateC = -rotateC; rotateD = -rotateD;862 }863 832 rotateC = -rotateC; 833 rotateD = -rotateD; 834 } 864 835 var offsetCanvasX, offsetCanvasY; 865 836 var width, height; … … 875 846 height = Math.abs(viewBox[3] - viewBox[1]) * scale; 876 847 } 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]; 889 849 this.width = width; 890 850 this.height = height; 891 851 this.fontScale = scale; 892 852 } 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 = { 901 854 clone: function PageViewPort_clone(args) { 902 855 args = args || {}; 903 856 var scale = 'scale' in args ? args.scale : this.scale; 904 857 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 }, 918 860 convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { 919 861 return Util.applyTransform([x, y], this.transform); 920 862 }, 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) { 930 864 var tl = Util.applyTransform([rect[0], rect[1]], this.transform); 931 865 var br = Util.applyTransform([rect[2], rect[3]], this.transform); 932 866 return [tl[0], tl[1], br[0], br[1]]; 933 867 }, 934 /**935 * Converts viewport coordinates to the PDF location. For examples, useful936 * 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 the940 * point in the PDF coordinate space.941 * @see {@link convertToViewportPoint}942 */943 868 convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { 944 869 return Util.applyInverseTransform([x, y], this.transform); … … 946 871 }; 947 872 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 }(); 874 var 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]; 962 875 function stringToPDFString(str) { 963 var i, n = str.length, strBuf = []; 876 var i, 877 n = str.length, 878 strBuf = []; 964 879 if (str[0] === '\xFE' && str[1] === '\xFF') { 965 // UTF16BE BOM966 880 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))); 969 882 } 970 883 } else { … … 976 889 return strBuf.join(''); 977 890 } 978 979 891 function stringToUTF8String(str) { 980 892 return decodeURIComponent(escape(str)); 981 893 } 982 894 function utf8StringToString(str) { 895 return unescape(encodeURIComponent(str)); 896 } 983 897 function isEmptyObj(obj) { 984 898 for (var key in obj) { … … 987 901 return true; 988 902 } 989 990 903 function isBool(v) { 991 904 return typeof v === 'boolean'; 992 905 } 993 994 906 function isInt(v) { 995 return typeof v === 'number' && ( (v | 0) === v);907 return typeof v === 'number' && (v | 0) === v; 996 908 } 997 998 909 function isNum(v) { 999 910 return typeof v === 'number'; 1000 911 } 1001 1002 912 function isString(v) { 1003 913 return typeof v === 'string'; 1004 914 } 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 1025 915 function isArray(v) { 1026 916 return v instanceof Array; 1027 917 } 1028 1029 function isStream(v) {1030 return typeof v === 'object' && v !== null && v.getBytes !== undefined;1031 }1032 1033 918 function isArrayBuffer(v) { 1034 919 return typeof v === 'object' && v !== null && v.byteLength !== undefined; 1035 920 } 1036 1037 function isRef(v) { 1038 return v instanceof Ref; 921 function isSpace(ch) { 922 return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A; 1039 923 } 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 */ 924 function isNodeJS() { 925 if (typeof __pdfjsdev_webpack__ === 'undefined') { 926 return typeof process === 'object' && process + '' === '[object process]'; 927 } 928 return false; 929 } 1057 930 function createPromiseCapability() { 1058 931 var capability = {}; … … 1063 936 return capability; 1064 937 } 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() { 938 var StatTimer = function StatTimerClosure() { 1385 939 function rpad(str, pad, length) { 1386 940 while (str.length < length) { … … 1390 944 } 1391 945 function StatTimer() { 1392 this.started = {};946 this.started = Object.create(null); 1393 947 this.times = []; 1394 948 this.enabled = true; … … 1416 970 'end': Date.now() 1417 971 }); 1418 // Remove timer from started so it can be called again.1419 972 delete this.started[name]; 1420 973 }, … … 1423 976 var times = this.times; 1424 977 var out = ''; 1425 // Find the longest name for padding purposes.1426 978 var longest = 0; 1427 979 for (i = 0, ii = times.length; i < ii; ++i) { … … 1440 992 }; 1441 993 return StatTimer; 1442 })(); 1443 1444 PDFJS.createBlob = function createBlob(data, contentType) { 994 }(); 995 var createBlob = function createBlob(data, contentType) { 1445 996 if (typeof Blob !== 'undefined') { 1446 997 return new Blob([data], { type: contentType }); 1447 998 } 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.'); 1452 1000 }; 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); 1001 var 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); 1463 1006 return URL.createObjectURL(blob); 1464 1007 } 1465 1466 1008 var buffer = 'data:' + contentType + ';base64,'; 1467 1009 for (var i = 0, ii = data.length; i < ii; i += 3) { … … 1469 1011 var b2 = data[i + 1] & 0xFF; 1470 1012 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; 1474 1017 buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; 1475 1018 } 1476 1019 return buffer; 1477 1020 }; 1478 } )();1479 1480 function MessageHandler(name, comObj) { 1481 this. name = name;1021 }(); 1022 function MessageHandler(sourceName, targetName, comObj) { 1023 this.sourceName = sourceName; 1024 this.targetName = targetName; 1482 1025 this.comObj = comObj; 1483 1026 this.callbackIndex = 1; 1484 1027 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) { 1499 1031 var data = event.data; 1032 if (data.targetName !== this.sourceName) { 1033 return; 1034 } 1500 1035 if (data.isReply) { 1501 1036 var callbackId = data.callbackId; … … 1514 1049 var action = ah[data.action]; 1515 1050 if (data.callbackId) { 1051 var sourceName = this.sourceName; 1052 var targetName = data.sourceName; 1516 1053 Promise.resolve().then(function () { 1517 1054 return action[0].call(action[1], data.data); 1518 1055 }).then(function (result) { 1519 1056 comObj.postMessage({ 1057 sourceName: sourceName, 1058 targetName: targetName, 1520 1059 isReply: true, 1521 1060 callbackId: data.callbackId, … … 1523 1062 }); 1524 1063 }, function (reason) { 1064 if (reason instanceof Error) { 1065 reason = reason + ''; 1066 } 1525 1067 comObj.postMessage({ 1068 sourceName: sourceName, 1069 targetName: targetName, 1526 1070 isReply: true, 1527 1071 callbackId: data.callbackId, … … 1535 1079 error('Unknown action from worker: ' + data.action); 1536 1080 } 1537 }; 1081 }.bind(this); 1082 comObj.addEventListener('message', this._onComObjOnMessage); 1538 1083 } 1539 1540 1084 MessageHandler.prototype = { 1541 1085 on: function messageHandlerOn(actionName, handler, scope) { … … 1546 1090 ah[actionName] = [handler, scope]; 1547 1091 }, 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/ArrayBuffers1553 */1554 1092 send: function messageHandlerSend(actionName, data, transfers) { 1555 1093 var message = { 1094 sourceName: this.sourceName, 1095 targetName: this.targetName, 1556 1096 action: actionName, 1557 1097 data: data … … 1559 1099 this.postMessage(message, transfers); 1560 1100 }, 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) { 1571 1102 var callbackId = this.callbackIndex++; 1572 1103 var message = { 1104 sourceName: this.sourceName, 1105 targetName: this.targetName, 1573 1106 action: actionName, 1574 1107 data: data, … … 1584 1117 return capability.promise; 1585 1118 }, 1586 /**1587 * Sends raw message to the comObj.1588 * @private1589 * @param message {Object} Raw message.1590 * @param transfers List of transfers/ArrayBuffers, or undefined.1591 */1592 1119 postMessage: function (message, transfers) { 1593 1120 if (transfers && this.postMessageTransfers) { … … 1596 1123 this.comObj.postMessage(message); 1597 1124 } 1125 }, 1126 destroy: function () { 1127 this.comObj.removeEventListener('message', this._onComObjOnMessage); 1598 1128 } 1599 1129 }; 1600 1601 1130 function loadJpegStream(id, imageUrl, objs) { 1602 1131 var img = new Image(); 1603 img.onload = (function loadJpegStream_onloadClosure() {1132 img.onload = function loadJpegStream_onloadClosure() { 1604 1133 objs.resolve(id, img); 1605 } );1606 img.onerror = (function loadJpegStream_onerrorClosure() {1134 }; 1135 img.onerror = function loadJpegStream_onerrorClosure() { 1607 1136 objs.resolve(id, null); 1608 1137 warn('Error during JPEG image loading'); 1609 } );1138 }; 1610 1139 img.src = imageUrl; 1611 1140 } 1141 exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; 1142 exports.IDENTITY_MATRIX = IDENTITY_MATRIX; 1143 exports.OPS = OPS; 1144 exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS; 1145 exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; 1146 exports.AnnotationBorderStyleType = AnnotationBorderStyleType; 1147 exports.AnnotationFieldFlag = AnnotationFieldFlag; 1148 exports.AnnotationFlag = AnnotationFlag; 1149 exports.AnnotationType = AnnotationType; 1150 exports.FontType = FontType; 1151 exports.ImageKind = ImageKind; 1152 exports.CMapCompressionType = CMapCompressionType; 1153 exports.InvalidPDFException = InvalidPDFException; 1154 exports.MessageHandler = MessageHandler; 1155 exports.MissingDataException = MissingDataException; 1156 exports.MissingPDFException = MissingPDFException; 1157 exports.NotImplementedException = NotImplementedException; 1158 exports.PageViewport = PageViewport; 1159 exports.PasswordException = PasswordException; 1160 exports.PasswordResponses = PasswordResponses; 1161 exports.StatTimer = StatTimer; 1162 exports.StreamType = StreamType; 1163 exports.TextRenderingMode = TextRenderingMode; 1164 exports.UnexpectedResponseException = UnexpectedResponseException; 1165 exports.UnknownErrorException = UnknownErrorException; 1166 exports.Util = Util; 1167 exports.XRefParseException = XRefParseException; 1168 exports.arrayByteLength = arrayByteLength; 1169 exports.arraysToBytes = arraysToBytes; 1170 exports.assert = assert; 1171 exports.bytesToString = bytesToString; 1172 exports.createBlob = createBlob; 1173 exports.createPromiseCapability = createPromiseCapability; 1174 exports.createObjectURL = createObjectURL; 1175 exports.deprecated = deprecated; 1176 exports.error = error; 1177 exports.getLookupTableFactory = getLookupTableFactory; 1178 exports.getVerbosityLevel = getVerbosityLevel; 1179 exports.globalScope = globalScope; 1180 exports.info = info; 1181 exports.isArray = isArray; 1182 exports.isArrayBuffer = isArrayBuffer; 1183 exports.isBool = isBool; 1184 exports.isEmptyObj = isEmptyObj; 1185 exports.isInt = isInt; 1186 exports.isNum = isNum; 1187 exports.isString = isString; 1188 exports.isSpace = isSpace; 1189 exports.isNodeJS = isNodeJS; 1190 exports.isSameOrigin = isSameOrigin; 1191 exports.createValidAbsoluteUrl = createValidAbsoluteUrl; 1192 exports.isLittleEndian = isLittleEndian; 1193 exports.isEvalSupported = isEvalSupported; 1194 exports.loadJpegStream = loadJpegStream; 1195 exports.log2 = log2; 1196 exports.readInt8 = readInt8; 1197 exports.readUint16 = readUint16; 1198 exports.readUint32 = readUint32; 1199 exports.removeNullCharacters = removeNullCharacters; 1200 exports.setVerbosityLevel = setVerbosityLevel; 1201 exports.shadow = shadow; 1202 exports.string32 = string32; 1203 exports.stringToBytes = stringToBytes; 1204 exports.stringToPDFString = stringToPDFString; 1205 exports.stringToUTF8String = stringToUTF8String; 1206 exports.utf8StringToString = utf8StringToString; 1207 exports.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"; 1612 1215 1613 1216 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); 1217 var sharedUtil = __w_pdfjs_require__(0); 1218 var assert = sharedUtil.assert; 1219 var removeNullCharacters = sharedUtil.removeNullCharacters; 1220 var warn = sharedUtil.warn; 1221 var deprecated = sharedUtil.deprecated; 1222 var createValidAbsoluteUrl = sharedUtil.createValidAbsoluteUrl; 1223 var stringToBytes = sharedUtil.stringToBytes; 1224 var CMapCompressionType = sharedUtil.CMapCompressionType; 1225 var DEFAULT_LINK_REL = 'noopener noreferrer nofollow'; 1226 function DOMCanvasFactory() {} 1227 DOMCanvasFactory.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 }; 1253 var 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 }(); 1298 var 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 }(); 1330 var 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 }(); 1340 var hasCanvasTypedArrays; 1341 hasCanvasTypedArrays = 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 }; 1348 var LinkTarget = { 1349 NONE: 0, 1350 SELF: 1, 1351 BLANK: 2, 1352 PARENT: 3, 1353 TOP: 4 1354 }; 1355 var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top']; 1356 function 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 } 1372 function 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 } 1378 function 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 } 1438 function 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 } 1450 function 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 } 1455 exports.CustomStyle = CustomStyle; 1456 exports.addLinkAttributes = addLinkAttributes; 1457 exports.isExternalLinkTargetSet = isExternalLinkTargetSet; 1458 exports.isValidUrl = isValidUrl; 1459 exports.getFilenameFromUrl = getFilenameFromUrl; 1460 exports.LinkTarget = LinkTarget; 1461 exports.RenderingCancelledException = RenderingCancelledException; 1462 exports.hasCanvasTypedArrays = hasCanvasTypedArrays; 1463 exports.getDefaultSetting = getDefaultSetting; 1464 exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL; 1465 exports.DOMCanvasFactory = DOMCanvasFactory; 1466 exports.DOMCMapReaderFactory = DOMCMapReaderFactory; 1621 1467 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__) { 1628 1471 1629 /** 1630 * Specifies if CMaps are binary packed. 1631 * @var {boolean} 1632 */ 1633 PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; 1472 "use strict"; 1634 1473 1635 /**1636 * By default fonts are converted to OpenType fonts and loaded via font face1637 * rules. If disabled, the font will be rendered using a built in font renderer1638 * that constructs the glyphs with primitive path commands.1639 * @var {boolean}1640 */1641 PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?1642 false : PDFJS.disableFontFace);1643 1474 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); 1475 var sharedUtil = __w_pdfjs_require__(0); 1476 var displayDOMUtils = __w_pdfjs_require__(1); 1477 var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; 1478 var AnnotationType = sharedUtil.AnnotationType; 1479 var stringToPDFString = sharedUtil.stringToPDFString; 1480 var Util = sharedUtil.Util; 1481 var addLinkAttributes = displayDOMUtils.addLinkAttributes; 1482 var LinkTarget = displayDOMUtils.LinkTarget; 1483 var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl; 1484 var warn = sharedUtil.warn; 1485 var CustomStyle = displayDOMUtils.CustomStyle; 1486 var getDefaultSetting = displayDOMUtils.getDefaultSetting; 1487 function AnnotationElementFactory() {} 1488 AnnotationElementFactory.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 }; 1532 var 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 }(); 1627 var 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 }(); 1674 var 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 }(); 1698 var 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 }(); 1709 var 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 }(); 1771 var 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 }(); 1790 var 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 }(); 1810 var 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 }(); 1841 var 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 }(); 1875 var 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 }(); 1953 var 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 }(); 1986 var 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 }(); 2002 var 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 }(); 2018 var 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 }(); 2034 var 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 }(); 2050 var 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 }(); 2085 var 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 }(); 2121 exports.AnnotationLayer = AnnotationLayer; 1651 2122 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__) { 1660 2126 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"; 1668 2128 1669 /**1670 * Disable range request loading of PDF files. When enabled and if the server1671 * 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);1677 2129 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) { 2130 var sharedUtil = __w_pdfjs_require__(0); 2131 var displayFontLoader = __w_pdfjs_require__(11); 2132 var displayCanvas = __w_pdfjs_require__(10); 2133 var displayMetadata = __w_pdfjs_require__(7); 2134 var displayDOMUtils = __w_pdfjs_require__(1); 2135 var amdRequire; 2136 var InvalidPDFException = sharedUtil.InvalidPDFException; 2137 var MessageHandler = sharedUtil.MessageHandler; 2138 var MissingPDFException = sharedUtil.MissingPDFException; 2139 var PageViewport = sharedUtil.PageViewport; 2140 var PasswordException = sharedUtil.PasswordException; 2141 var StatTimer = sharedUtil.StatTimer; 2142 var UnexpectedResponseException = sharedUtil.UnexpectedResponseException; 2143 var UnknownErrorException = sharedUtil.UnknownErrorException; 2144 var Util = sharedUtil.Util; 2145 var createPromiseCapability = sharedUtil.createPromiseCapability; 2146 var error = sharedUtil.error; 2147 var deprecated = sharedUtil.deprecated; 2148 var getVerbosityLevel = sharedUtil.getVerbosityLevel; 2149 var info = sharedUtil.info; 2150 var isInt = sharedUtil.isInt; 2151 var isArray = sharedUtil.isArray; 2152 var isArrayBuffer = sharedUtil.isArrayBuffer; 2153 var isSameOrigin = sharedUtil.isSameOrigin; 2154 var loadJpegStream = sharedUtil.loadJpegStream; 2155 var stringToBytes = sharedUtil.stringToBytes; 2156 var globalScope = sharedUtil.globalScope; 2157 var warn = sharedUtil.warn; 2158 var FontFaceObject = displayFontLoader.FontFaceObject; 2159 var FontLoader = displayFontLoader.FontLoader; 2160 var CanvasGraphics = displayCanvas.CanvasGraphics; 2161 var Metadata = displayMetadata.Metadata; 2162 var RenderingCancelledException = displayDOMUtils.RenderingCancelledException; 2163 var getDefaultSetting = displayDOMUtils.getDefaultSetting; 2164 var DOMCanvasFactory = displayDOMUtils.DOMCanvasFactory; 2165 var DOMCMapReaderFactory = displayDOMUtils.DOMCMapReaderFactory; 2166 var DEFAULT_RANGE_CHUNK_SIZE = 65536; 2167 var isWorkerDisabled = false; 2168 var workerSrc; 2169 var isPostMessageTransfersDisabled = false; 2170 var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; 2171 var fakeWorkerFilesLoader = null; 2172 var useRequireEnsure = false; 2173 if (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 } 2198 function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { 1826 2199 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 } 1829 2203 if (pdfDataRangeTransport) { 1830 2204 if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { 1831 // Not a PDFDataRangeTransport instance, trying to add missing properties.1832 2205 pdfDataRangeTransport = Object.create(pdfDataRangeTransport); 1833 2206 pdfDataRangeTransport.length = src.length; 1834 2207 pdfDataRangeTransport.initialData = src.initialData; 2208 if (!pdfDataRangeTransport.abort) { 2209 pdfDataRangeTransport.abort = function () {}; 2210 } 1835 2211 } 1836 2212 src = Object.create(src); … … 1839 2215 task.onPassword = passwordCallback || null; 1840 2216 task.onProgress = progressCallback || null; 1841 1842 var workerInitializedCapability, transport;1843 2217 var source; 1844 2218 if (typeof src === 'string') { … … 1850 2224 } else { 1851 2225 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'); 1854 2227 } 1855 2228 if (!src.url && !src.data && !src.range) { 1856 2229 error('Invalid parameter object: need either .data, .range or .url'); 1857 2230 } 1858 1859 2231 source = src; 1860 2232 } 1861 1862 2233 var params = {}; 2234 var rangeTransport = null; 2235 var worker = null; 1863 2236 for (var key in source) { 1864 2237 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; 1867 2239 continue; 1868 2240 } else if (key === 'range') { 2241 rangeTransport = source[key]; 2242 continue; 2243 } else if (key === 'worker') { 2244 worker = source[key]; 1869 2245 continue; 1870 2246 } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { 1871 // Converting string or array-like data to Uint8Array.1872 2247 var pdfBytes = source[key]; 1873 2248 if (typeof pdfBytes === 'string') { 1874 2249 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)) { 1877 2253 params[key] = new Uint8Array(pdfBytes); 1878 2254 } 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.'); 1881 2256 } 1882 2257 continue; … … 1884 2259 params[key] = source[key]; 1885 2260 } 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 } 2286 function _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; 1891 2312 }); 1892 1893 return task; 1894 }; 1895 1896 /** 1897 * PDF document loading operation. 1898 * @class 1899 */ 1900 var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { 1901 /** @constructs PDFDocumentLoadingTask */ 2313 } 2314 var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() { 2315 var nextDocumentId = 0; 1902 2316 function PDFDocumentLoadingTask() { 1903 2317 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; 1910 2322 this.onPassword = null; 1911 1912 /**1913 * Callback to be able to monitor the loading progress of the PDF file1914 * (necessary to implement e.g. a loading bar). The callback receives1915 * an {Object} with the properties: {number} loaded and {number} total.1916 */1917 2323 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 = { 1925 2327 get promise() { 1926 2328 return this._capability.promise; 1927 2329 }, 1928 1929 // TODO add cancel or abort method1930 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 or1937 * 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 }, 1939 2341 then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { 1940 2342 return this.promise.then.apply(this.promise, arguments); 1941 2343 } 1942 2344 }; 1943 1944 2345 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 }(); 2347 var PDFDataRangeTransport = function pdfDataRangeTransportClosure() { 1957 2348 function PDFDataRangeTransport(length, initialData) { 1958 2349 this.length = length; 1959 2350 this.initialData = initialData; 1960 1961 2351 this._rangeListeners = []; 1962 2352 this._progressListeners = []; … … 1964 2354 this._readyCapability = createPromiseCapability(); 1965 2355 } 1966 PDFDataRangeTransport.prototype = 1967 /** @lends PDFDataRangeTransport.prototype */ { 1968 addRangeListener: 1969 function PDFDataRangeTransport_addRangeListener(listener) { 2356 PDFDataRangeTransport.prototype = { 2357 addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { 1970 2358 this._rangeListeners.push(listener); 1971 2359 }, 1972 1973 addProgressListener: 1974 function PDFDataRangeTransport_addProgressListener(listener) { 2360 addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { 1975 2361 this._progressListeners.push(listener); 1976 2362 }, 1977 1978 addProgressiveReadListener: 1979 function PDFDataRangeTransport_addProgressiveReadListener(listener) { 2363 addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { 1980 2364 this._progressiveReadListeners.push(listener); 1981 2365 }, 1982 1983 2366 onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { 1984 2367 var listeners = this._rangeListeners; … … 1987 2370 } 1988 2371 }, 1989 1990 2372 onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { 1991 2373 this._readyCapability.promise.then(function () { … … 1996 2378 }.bind(this)); 1997 2379 }, 1998 1999 onDataProgressiveRead: 2000 function PDFDataRangeTransport_onDataProgress(chunk) { 2380 onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { 2001 2381 this._readyCapability.promise.then(function () { 2002 2382 var listeners = this._progressiveReadListeners; … … 2006 2386 }.bind(this)); 2007 2387 }, 2008 2009 2388 transportReady: function PDFDataRangeTransport_transportReady() { 2010 2389 this._readyCapability.resolve(); 2011 2390 }, 2012 2013 requestDataRange: 2014 function PDFDataRangeTransport_requestDataRange(begin, end) { 2391 requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { 2015 2392 throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); 2016 } 2393 }, 2394 abort: function PDFDataRangeTransport_abort() {} 2017 2395 }; 2018 2396 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 }(); 2398 var PDFDocumentProxy = function PDFDocumentProxyClosure() { 2399 function PDFDocumentProxy(pdfInfo, transport, loadingTask) { 2030 2400 this.pdfInfo = pdfInfo; 2031 2401 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 = { 2037 2405 get numPages() { 2038 2406 return this.pdfInfo.numPages; 2039 2407 }, 2040 /**2041 * @return {string} A unique ID to identify a PDF. Not guaranteed to be2042 * unique.2043 */2044 2408 get fingerprint() { 2045 2409 return this.pdfInfo.fingerprint; 2046 2410 }, 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 */2052 2411 getPage: function PDFDocumentProxy_getPage(pageNumber) { 2053 2412 return this.transport.getPage(pageNumber); 2054 2413 }, 2055 /**2056 * @param {{num: number, gen: number}} ref The page reference. Must have2057 * the 'num' and 'gen' properties.2058 * @return {Promise} A promise that is resolved with the page index that is2059 * associated with the reference.2060 */2061 2414 getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { 2062 2415 return this.transport.getPageIndex(ref); 2063 2416 }, 2064 /**2065 * @return {Promise} A promise that is resolved with a lookup table for2066 * mapping named destinations to reference numbers.2067 *2068 * This can be slow for large documents: use getDestination instead2069 */2070 2417 getDestinations: function PDFDocumentProxy_getDestinations() { 2071 2418 return this.transport.getDestinations(); 2072 2419 }, 2073 /**2074 * @param {string} id The named destination to get.2075 * @return {Promise} A promise that is resolved with all information2076 * of the given named destination.2077 */2078 2420 getDestination: function PDFDocumentProxy_getDestination(id) { 2079 2421 return this.transport.getDestination(id); 2080 2422 }, 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 }, 2085 2426 getAttachments: function PDFDocumentProxy_getAttachments() { 2086 2427 return this.transport.getAttachments(); 2087 2428 }, 2088 /**2089 * @return {Promise} A promise that is resolved with an array of all the2090 * JavaScript strings in the name tree.2091 */2092 2429 getJavaScript: function PDFDocumentProxy_getJavaScript() { 2093 2430 return this.transport.getJavaScript(); 2094 2431 }, 2095 /**2096 * @return {Promise} A promise that is resolved with an {Array} that is a2097 * 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 this2106 * },2107 * ...2108 * ].2109 */2110 2432 getOutline: function PDFDocumentProxy_getOutline() { 2111 2433 return this.transport.getOutline(); 2112 2434 }, 2113 /**2114 * @return {Promise} A promise that is resolved with an {Object} that has2115 * info and metadata properties. Info is an {Object} filled with anything2116 * available in the information dictionary and similarly metadata is a2117 * {Metadata} object with information from the metadata section of the PDF.2118 */2119 2435 getMetadata: function PDFDocumentProxy_getMetadata() { 2120 2436 return this.transport.getMetadata(); 2121 2437 }, 2122 /**2123 * @return {Promise} A promise that is resolved with a TypedArray that has2124 * the raw data from the PDF.2125 */2126 2438 getData: function PDFDocumentProxy_getData() { 2127 2439 return this.transport.getData(); 2128 2440 }, 2129 /**2130 * @return {Promise} A promise that is resolved when the document's data2131 * is loaded. It is resolved with an {Object} that contains the length2132 * property that indicates size of the PDF data in bytes.2133 */2134 2441 getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { 2135 2442 return this.transport.downloadInfoCapability.promise; 2136 2443 }, 2137 /**2138 * @return {Promise} A promise this is resolved with current stats about2139 * document structures (see {@link PDFDocumentStats}).2140 */2141 2444 getStats: function PDFDocumentProxy_getStats() { 2142 2445 return this.transport.getStats(); 2143 2446 }, 2144 /**2145 * Cleans up resources allocated by the document, e.g. created @font-face.2146 */2147 2447 cleanup: function PDFDocumentProxy_cleanup() { 2148 2448 this.transport.startCleanup(); 2149 2449 }, 2150 /**2151 * Destroys current document instance and terminates worker.2152 */2153 2450 destroy: function PDFDocumentProxy_destroy() { 2154 this.transport.destroy();2451 return this.loadingTask.destroy(); 2155 2452 } 2156 2453 }; 2157 2454 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 }(); 2456 var PDFPageProxy = function PDFPageProxyClosure() { 2222 2457 function PDFPageProxy(pageIndex, pageInfo, transport) { 2223 2458 this.pageIndex = pageIndex; … … 2225 2460 this.transport = transport; 2226 2461 this.stats = new StatTimer(); 2227 this.stats.enabled = !!globalScope.PDFJS.enableStats;2462 this.stats.enabled = getDefaultSetting('enableStats'); 2228 2463 this.commonObjs = transport.commonObjs; 2229 2464 this.objs = new PDFObjects(); 2230 2465 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 = { 2238 2471 get pageNumber() { 2239 2472 return this.pageIndex + 1; 2240 2473 }, 2241 /**2242 * @return {number} The number of degrees the page is rotated clockwise.2243 */2244 2474 get rotate() { 2245 2475 return this.pageInfo.rotate; 2246 2476 }, 2247 /**2248 * @return {Object} The reference that points to this page. It has 'num' and2249 * 'gen' properties.2250 */2251 2477 get ref() { 2252 2478 return this.pageInfo.ref; 2253 2479 }, 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 }, 2258 2483 get view() { 2259 2484 return this.pageInfo.view; 2260 2485 }, 2261 /**2262 * @param {number} scale The desired scale of the viewport.2263 * @param {number} rotate Degrees to rotate the viewport. If omitted this2264 * defaults to the page rotation.2265 * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties2266 * along with transforms required for rendering.2267 */2268 2486 getViewport: function PDFPageProxy_getViewport(scale, rotate) { 2269 2487 if (arguments.length < 2) { 2270 2488 rotate = this.rotate; 2271 2489 } 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 }, 2293 2500 render: function PDFPageProxy_render(params) { 2294 2501 var stats = this.stats; 2295 2502 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(); 2303 2507 if (!this.intentStates[renderingIntent]) { 2304 this.intentStates[renderingIntent] = {};2508 this.intentStates[renderingIntent] = Object.create(null); 2305 2509 } 2306 2510 var intentState = this.intentStates[renderingIntent]; 2307 2308 // If there's no displayReadyCapability yet, then the operatorList2309 // was never requested before. Make the request and create the promise.2310 2511 if (!intentState.displayReadyCapability) { 2311 2512 intentState.receivingOperatorList = true; … … 2316 2517 lastChunk: false 2317 2518 }; 2318 2319 2519 this.stats.time('Page Request'); 2320 2520 this.transport.messageHandler.send('RenderPageRequest', { 2321 2521 pageIndex: this.pageNumber - 1, 2322 intent: renderingIntent 2522 intent: renderingIntent, 2523 renderInteractiveForms: renderInteractiveForms 2323 2524 }); 2324 2525 } 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'; 2331 2528 if (!intentState.renderTasks) { 2332 2529 intentState.renderTasks = []; … … 2334 2531 intentState.renderTasks.push(internalRenderTask); 2335 2532 var renderTask = internalRenderTask.task; 2336 2337 // Obsolete parameter support2338 2533 if (params.continueCallback) { 2534 deprecated('render is used with continueCallback parameter'); 2339 2535 renderTask.onContinue = params.continueCallback; 2340 2536 } 2341 2342 2537 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 }); 2358 2549 function complete(error) { 2359 2550 var i = intentState.renderTasks.indexOf(internalRenderTask); … … 2361 2552 intentState.renderTasks.splice(i, 1); 2362 2553 } 2363 2364 2554 if (self.cleanupAfterRender) { 2365 self.pendingDestroy = true; 2366 } 2367 self._tryDestroy(); 2368 2555 self.pendingCleanup = true; 2556 } 2557 self._tryCleanup(); 2369 2558 if (error) { 2370 2559 internalRenderTask.capability.reject(error); … … 2375 2564 stats.timeEnd('Overall'); 2376 2565 } 2377 2378 2566 return renderTask; 2379 2567 }, 2380 2381 /**2382 * @return {Promise} A promise resolved with an {@link PDFOperatorList}2383 * object that represents page's operator list.2384 */2385 2568 getOperatorList: function PDFPageProxy_getOperatorList() { 2386 2569 function operatorListChanged() { 2387 2570 if (intentState.operatorList.lastChunk) { 2388 2571 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 } 2392 2578 var renderingIntent = 'oplist'; 2393 2579 if (!this.intentStates[renderingIntent]) { 2394 this.intentStates[renderingIntent] = {};2580 this.intentStates[renderingIntent] = Object.create(null); 2395 2581 } 2396 2582 var intentState = this.intentStates[renderingIntent]; 2397 2583 var opListTask; 2398 2584 if (!intentState.opListReadCapability) { 2399 varopListTask = {};2585 opListTask = {}; 2400 2586 opListTask.operatorListChanged = operatorListChanged; 2401 2587 intentState.receivingOperatorList = true; … … 2408 2594 lastChunk: false 2409 2595 }; 2410 2411 2596 this.transport.messageHandler.send('RenderPageRequest', { 2412 2597 pageIndex: this.pageIndex, … … 2416 2601 return intentState.opListReadCapability.promise; 2417 2602 }, 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) { 2424 2604 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 2426 2608 }); 2427 2609 }, 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)) { 2447 2643 return; 2448 2644 } 2449 2450 Object.keys(this.intentStates).forEach(function(intent) { 2645 Object.keys(this.intentStates).forEach(function (intent) { 2451 2646 delete this.intentStates[intent]; 2452 2647 }, this); 2453 2648 this.objs.clear(); 2454 2649 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) { 2463 2653 var intentState = this.intentStates[intent]; 2464 // TODO Refactor RenderPageRequest to separate rendering2465 // and operator list logic2466 2654 if (intentState.displayReadyCapability) { 2467 2655 intentState.displayReadyCapability.resolve(transparency); 2468 2656 } 2469 2657 }, 2470 /** 2471 * For internal use only. 2472 * @ignore 2473 */ 2474 _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, 2475 intent) { 2658 _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { 2476 2659 var intentState = this.intentStates[intent]; 2477 2660 var i, ii; 2478 // Add the new chunk to the current operator list.2479 2661 for (i = 0, ii = operatorListChunk.length; i < ii; i++) { 2480 2662 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); 2481 intentState.operatorList.argsArray.push( 2482 operatorListChunk.argsArray[i]); 2663 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); 2483 2664 } 2484 2665 intentState.operatorList.lastChunk = operatorListChunk.lastChunk; 2485 2486 // Notify all the rendering tasks there are more operators to be consumed.2487 2666 for (i = 0; i < intentState.renderTasks.length; i++) { 2488 2667 intentState.renderTasks[i].operatorListChanged(); 2489 2668 } 2490 2491 2669 if (operatorListChunk.lastChunk) { 2492 2670 intentState.receivingOperatorList = false; 2493 this._try Destroy();2671 this._tryCleanup(); 2494 2672 } 2495 2673 } 2496 2674 }; 2497 2675 return PDFPageProxy; 2498 })(); 2499 2500 /** 2501 * For internal use only. 2502 * @ignore 2503 */ 2504 var WorkerTransport = (function WorkerTransportClosure() { 2505 function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) { 2676 }(); 2677 var 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 }(); 2927 var WorkerTransport = function WorkerTransportClosure() { 2928 function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport, CMapReaderFactory) { 2929 this.messageHandler = messageHandler; 2930 this.loadingTask = loadingTask; 2506 2931 this.pdfDataRangeTransport = pdfDataRangeTransport; 2507 this.workerInitializedCapability = workerInitializedCapability;2508 2932 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; 2512 2941 this.pageCache = []; 2513 2942 this.pagePromises = []; 2514 2943 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(); 2566 2945 } 2567 2946 WorkerTransport.prototype = { 2568 2947 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 }); 2569 2962 this.pageCache = []; 2570 2963 this.pagePromises = []; 2571 2964 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; 2621 2984 var pdfDataRangeTransport = this.pdfDataRangeTransport; 2622 2985 if (pdfDataRangeTransport) { 2623 pdfDataRangeTransport.addRangeListener(function (begin, chunk) {2986 pdfDataRangeTransport.addRangeListener(function (begin, chunk) { 2624 2987 messageHandler.send('OnDataRange', { 2625 2988 begin: begin, … … 2627 2990 }); 2628 2991 }); 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 }); 2634 2994 }); 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 }); 2640 2997 }); 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 } 2648 3002 messageHandler.on('GetDoc', function transportDoc(data) { 2649 3003 var pdfInfo = data.pdfInfo; 2650 3004 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); 2652 3007 this.pdfDocument = pdfDocument; 2653 this.loadingTask._capability.resolve(pdfDocument);3008 loadingTask._capability.resolve(pdfDocument); 2654 3009 }, 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(); 2659 3012 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; 2665 3021 }, 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)); 2676 3024 }, this); 2677 2678 3025 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)); 2681 3027 }, this); 2682 2683 3028 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)); 2686 3030 }, 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)); 2692 3033 }, 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)); 2698 3036 }, this); 2699 2700 3037 messageHandler.on('DataLoaded', function transportPage(data) { 2701 3038 this.downloadInfoCapability.resolve(data); 2702 3039 }, this); 2703 2704 3040 messageHandler.on('PDFManagerReady', function transportPage(data) { 2705 3041 if (this.pdfDataRangeTransport) { … … 2707 3043 } 2708 3044 }, this); 2709 2710 3045 messageHandler.on('StartRenderPage', function transportRender(data) { 3046 if (this.destroyed) { 3047 return; 3048 } 2711 3049 var page = this.pageCache[data.pageIndex]; 2712 2713 3050 page.stats.timeEnd('Page Request'); 2714 3051 page._startRenderPage(data.transparency, data.intent); 2715 3052 }, this); 2716 2717 3053 messageHandler.on('RenderPageChunk', function transportRender(data) { 3054 if (this.destroyed) { 3055 return; 3056 } 2718 3057 var page = this.pageCache[data.pageIndex]; 2719 2720 3058 page._renderPageChunk(data.operatorList, data.intent); 2721 3059 }, this); 2722 2723 3060 messageHandler.on('commonobj', function transportObj(data) { 3061 if (this.destroyed) { 3062 return; 3063 } 2724 3064 var id = data[0]; 2725 3065 var type = data[1]; … … 2727 3067 return; 2728 3068 } 2729 2730 3069 switch (type) { 2731 3070 case 'Font': 2732 3071 var exportedData = data[2]; 2733 2734 var font;2735 3072 if ('error' in exportedData) { 2736 var e rror = exportedData.error;2737 warn('Error during font loading: ' + e rror);2738 this.commonObjs.resolve(id, e rror);3073 var exportedError = exportedData.error; 3074 warn('Error during font loading: ' + exportedError); 3075 this.commonObjs.resolve(id, exportedError); 2739 3076 break; 2740 } else {2741 font = new FontFaceObject(exportedData);2742 3077 } 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)); 2750 3094 break; 2751 3095 case 'FontPath': … … 2756 3100 } 2757 3101 }, this); 2758 2759 3102 messageHandler.on('obj', function transportObj(data) { 3103 if (this.destroyed) { 3104 return; 3105 } 2760 3106 var id = data[0]; 2761 3107 var pageIndex = data[1]; … … 2766 3112 return; 2767 3113 } 2768 2769 3114 switch (type) { 2770 3115 case 'JpegStream': … … 2775 3120 imageData = data[3]; 2776 3121 pageProxy.objs.resolve(id, imageData); 2777 2778 // heuristics that will allow not to store large data2779 3122 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) { 2782 3124 pageProxy.cleanupAfterRender = true; 2783 3125 } … … 2787 3129 } 2788 3130 }, this); 2789 2790 3131 messageHandler.on('DocProgress', function transportDocProgress(data) { 3132 if (this.destroyed) { 3133 return; 3134 } 2791 3135 var loadingTask = this.loadingTask; 2792 3136 if (loadingTask.onProgress) { … … 2797 3141 } 2798 3142 }, this); 2799 2800 3143 messageHandler.on('PageError', function transportError(data) { 3144 if (this.destroyed) { 3145 return; 3146 } 2801 3147 var page = this.pageCache[data.pageNum - 1]; 2802 3148 var intentState = page.intentStates[data.intent]; … … 2806 3152 error(data.error); 2807 3153 } 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 } 2808 3160 }, 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 } 2811 3179 var imageUrl = data[0]; 2812 3180 var components = data[1]; 2813 3181 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 } 2818 3184 return new Promise(function (resolve, reject) { 2819 3185 var img = new Image(); … … 2824 3190 var rgbaLength = size * 4; 2825 3191 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; 2827 3195 var tmpCtx = tmpCanvas.getContext('2d'); 2828 3196 tmpCtx.drawImage(img, 0, 0); 2829 3197 var data = tmpCtx.getImageData(0, 0, width, height).data; 2830 3198 var i, j; 2831 2832 3199 if (components === 3) { 2833 3200 for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { … … 2841 3208 } 2842 3209 } 2843 resolve({ data: buf, width: width, height: height}); 3210 resolve({ 3211 data: buf, 3212 width: width, 3213 height: height 3214 }); 2844 3215 }; 2845 3216 img.onerror = function () { … … 2848 3219 img.src = imageUrl; 2849 3220 }); 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 }, 2875 3229 getData: function WorkerTransport_getData() { 2876 3230 return this.messageHandler.sendWithPromise('GetData', null); 2877 3231 }, 2878 2879 3232 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) { 2882 3234 return Promise.reject(new Error('Invalid page request')); 2883 3235 } 2884 2885 3236 var pageIndex = pageNumber - 1; 2886 3237 if (pageIndex in this.pagePromises) { 2887 3238 return this.pagePromises[pageIndex]; 2888 3239 } 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 } 2892 3244 var page = new PDFPageProxy(pageIndex, pageInfo, this); 2893 3245 this.pageCache[pageIndex] = page; … … 2897 3249 return promise; 2898 3250 }, 2899 2900 3251 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 }, 2909 3262 getDestinations: function WorkerTransport_getDestinations() { 2910 3263 return this.messageHandler.sendWithPromise('GetDestinations', null); 2911 3264 }, 2912 2913 3265 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 }, 2917 3271 getAttachments: function WorkerTransport_getAttachments() { 2918 3272 return this.messageHandler.sendWithPromise('GetAttachments', null); 2919 3273 }, 2920 2921 3274 getJavaScript: function WorkerTransport_getJavaScript() { 2922 3275 return this.messageHandler.sendWithPromise('GetJavaScript', null); 2923 3276 }, 2924 2925 3277 getOutline: function WorkerTransport_getOutline() { 2926 3278 return this.messageHandler.sendWithPromise('GetOutline', null); 2927 3279 }, 2928 2929 3280 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) { 2932 3282 return { 2933 3283 info: results[0], 2934 metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)3284 metadata: results[1] ? new Metadata(results[1]) : null 2935 3285 }; 2936 3286 }); 2937 3287 }, 2938 2939 3288 getStats: function WorkerTransport_getStats() { 2940 3289 return this.messageHandler.sendWithPromise('GetStats', null); 2941 3290 }, 2942 2943 3291 startCleanup: function WorkerTransport_startCleanup() { 2944 this.messageHandler.sendWithPromise('Cleanup', null). 2945 then(function endCleanup() { 3292 this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() { 2946 3293 for (var i = 0, ii = this.pageCache.length; i < ii; i++) { 2947 3294 var page = this.pageCache[i]; 2948 3295 if (page) { 2949 page. destroy();3296 page.cleanup(); 2950 3297 } 2951 3298 } 2952 3299 this.commonObjs.clear(); 2953 FontLoader.clear();3300 this.fontLoader.clear(); 2954 3301 }.bind(this)); 2955 3302 } 2956 3303 }; 2957 3304 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 }(); 3306 var PDFObjects = function PDFObjectsClosure() { 2969 3307 function PDFObjects() { 2970 this.objs = {}; 2971 } 2972 3308 this.objs = Object.create(null); 3309 } 2973 3310 PDFObjects.prototype = { 2974 /**2975 * Internal function.2976 * Ensures there is an object defined for `objId`.2977 */2978 3311 ensureObj: function PDFObjects_ensureObj(objId) { 2979 3312 if (this.objs[objId]) { 2980 3313 return this.objs[objId]; 2981 3314 } 2982 2983 3315 var obj = { 2984 3316 capability: createPromiseCapability(), … … 2987 3319 }; 2988 3320 this.objs[objId] = obj; 2989 2990 3321 return obj; 2991 3322 }, 2992 2993 /**2994 * If called *without* callback, this returns the data of `objId` but the2995 * 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 the2998 * object once the object is resolved. That means, if you call this2999 * function and the object is already resolved, the callback gets called3000 * right away.3001 */3002 3323 get: function PDFObjects_get(objId, callback) { 3003 // If there is a callback, then the get can be async and the object is3004 // not required to be resolved right now3005 3324 if (callback) { 3006 3325 this.ensureObj(objId).capability.promise.then(callback); 3007 3326 return null; 3008 3327 } 3009 3010 // If there isn't a callback, the user expects to get the resolved data3011 // directly.3012 3328 var obj = this.objs[objId]; 3013 3014 // If there isn't an object yet or the object isn't resolved, then the3015 // data isn't ready yet!3016 3329 if (!obj || !obj.resolved) { 3017 3330 error('Requesting object that isn\'t resolved yet ' + objId); 3018 3331 } 3019 3020 3332 return obj.data; 3021 3333 }, 3022 3023 /**3024 * Resolves the object `objId` with optional `data`.3025 */3026 3334 resolve: function PDFObjects_resolve(objId, data) { 3027 3335 var obj = this.ensureObj(objId); 3028 3029 3336 obj.resolved = true; 3030 3337 obj.data = data; 3031 3338 obj.capability.resolve(data); 3032 3339 }, 3033 3034 3340 isResolved: function PDFObjects_isResolved(objId) { 3035 3341 var objs = this.objs; 3036 3037 3342 if (!objs[objId]) { 3038 3343 return false; 3039 } else { 3040 return objs[objId].resolved; 3041 } 3042 }, 3043 3344 } 3345 return objs[objId].resolved; 3346 }, 3044 3347 hasData: function PDFObjects_hasData(objId) { 3045 3348 return this.isResolved(objId); 3046 3349 }, 3047 3048 /**3049 * Returns the data of `objId` if object exists, null otherwise.3050 */3051 3350 getData: function PDFObjects_getData(objId) { 3052 3351 var objs = this.objs; 3053 3352 if (!objs[objId] || !objs[objId].resolved) { 3054 3353 return null; 3055 } else { 3056 return objs[objId].data; 3057 } 3058 }, 3059 3354 } 3355 return objs[objId].data; 3356 }, 3060 3357 clear: function PDFObjects_clear() { 3061 this.objs = {};3358 this.objs = Object.create(null); 3062 3359 } 3063 3360 }; 3064 3361 return PDFObjects; 3065 })(); 3066 3067 /** 3068 * Allows controlling of the rendering tasks. 3069 * @class 3070 */ 3071 var RenderTask = (function RenderTaskClosure() { 3362 }(); 3363 var RenderTask = function RenderTaskClosure() { 3072 3364 function RenderTask(internalRenderTask) { 3073 3365 this._internalRenderTask = internalRenderTask; 3074 3075 /**3076 * Callback for incremental rendering -- a function that will be called3077 * each time the rendering is paused. To continue rendering call the3078 * function that is the first argument to the callback.3079 * @type {function}3080 */3081 3366 this.onContinue = null; 3082 3367 } 3083 3084 RenderTask.prototype = /** @lends RenderTask.prototype */ { 3085 /** 3086 * Promise for rendering task completion. 3087 * @return {Promise} 3088 */ 3368 RenderTask.prototype = { 3089 3369 get promise() { 3090 3370 return this._internalRenderTask.capability.promise; 3091 3371 }, 3092 3093 /**3094 * Cancels the rendering task. If the task is currently rendering it will3095 * not be cancelled until graphics pauses with a timeout. The promise that3096 * this object extends will resolved when cancelled.3097 */3098 3372 cancel: function RenderTask_cancel() { 3099 3373 this._internalRenderTask.cancel(); 3100 3374 }, 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 or3108 * onRejected callback.3109 */3110 3375 then: function RenderTask_then(onFulfilled, onRejected) { 3111 3376 return this.promise.then.apply(this.promise, arguments); 3112 3377 } 3113 3378 }; 3114 3115 3379 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 }(); 3381 var InternalRenderTask = function InternalRenderTaskClosure() { 3382 function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber, canvasFactory) { 3126 3383 this.callback = callback; 3127 3384 this.params = params; … … 3131 3388 this.operatorList = operatorList; 3132 3389 this.pageNumber = pageNumber; 3390 this.canvasFactory = canvasFactory; 3133 3391 this.running = false; 3134 3392 this.graphicsReadyCallback = null; 3135 3393 this.graphicsReady = false; 3394 this.useRequestAnimationFrame = false; 3136 3395 this.cancelled = false; 3137 3396 this.capability = createPromiseCapability(); 3138 3397 this.task = new RenderTask(this); 3139 // caching this-bound methods3140 3398 this._continueBound = this._continue.bind(this); 3141 3399 this._scheduleNextBound = this._scheduleNext.bind(this); 3142 3400 this._nextBound = this._next.bind(this); 3143 3401 } 3144 3145 3402 InternalRenderTask.prototype = { 3146 3147 initalizeGraphics: 3148 function InternalRenderTask_initalizeGraphics(transparency) { 3149 3403 initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) { 3150 3404 if (this.cancelled) { 3151 3405 return; 3152 3406 } 3153 if (PDFJS.pdfBug && 'StepperManager' in globalScope && 3154 globalScope.StepperManager.enabled) { 3407 if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) { 3155 3408 this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); 3156 3409 this.stepper.init(this.operatorList); 3157 3410 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); 3158 3411 } 3159 3160 3412 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); 3165 3415 this.operatorListIdx = 0; 3166 3416 this.graphicsReady = true; … … 3169 3419 } 3170 3420 }, 3171 3172 3421 cancel: function InternalRenderTask_cancel() { 3173 3422 this.running = false; 3174 3423 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 }, 3178 3430 operatorListChanged: function InternalRenderTask_operatorListChanged() { 3179 3431 if (!this.graphicsReady) { … … 3183 3435 return; 3184 3436 } 3185 3186 3437 if (this.stepper) { 3187 3438 this.stepper.updateOperatorList(this.operatorList); 3188 3439 } 3189 3190 3440 if (this.running) { 3191 3441 return; … … 3193 3443 this._continue(); 3194 3444 }, 3195 3196 3445 _continue: function InternalRenderTask__continue() { 3197 3446 this.running = true; … … 3200 3449 } 3201 3450 if (this.task.onContinue) { 3202 this.task.onContinue .call(this.task,this._scheduleNextBound);3451 this.task.onContinue(this._scheduleNextBound); 3203 3452 } else { 3204 3453 this._scheduleNext(); 3205 3454 } 3206 3455 }, 3207 3208 3456 _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 }, 3212 3463 _next: function InternalRenderTask__next() { 3213 3464 if (this.cancelled) { 3214 3465 return; 3215 3466 } 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); 3220 3468 if (this.operatorListIdx === this.operatorList.argsArray.length) { 3221 3469 this.running = false; … … 3226 3474 } 3227 3475 } 3476 }; 3477 return InternalRenderTask; 3478 }(); 3479 var _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 }(); 3493 exports.version = '1.8.188'; 3494 exports.build = 'ad1023ff'; 3495 exports.getDocument = getDocument; 3496 exports.PDFDataRangeTransport = PDFDataRangeTransport; 3497 exports.PDFWorker = PDFWorker; 3498 exports.PDFDocumentProxy = PDFDocumentProxy; 3499 exports.PDFPageProxy = PDFPageProxy; 3500 exports._UnsupportedManager = _UnsupportedManager; 3228 3501 3229 }; 3502 /***/ }), 3503 /* 4 */ 3504 /***/ (function(module, exports, __w_pdfjs_require__) { 3230 3505 3231 return InternalRenderTask; 3232 })(); 3506 "use strict"; 3233 3507 3234 3508 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 } 3509 var sharedUtil = __w_pdfjs_require__(0); 3510 var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; 3511 var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; 3512 var ImageKind = sharedUtil.ImageKind; 3513 var OPS = sharedUtil.OPS; 3514 var Util = sharedUtil.Util; 3515 var isNum = sharedUtil.isNum; 3516 var isArray = sharedUtil.isArray; 3517 var warn = sharedUtil.warn; 3518 var createObjectURL = sharedUtil.createObjectURL; 3519 var SVG_DEFAULTS = { 3520 fontStyle: 'normal', 3521 fontWeight: 'normal', 3522 fillColor: '#000000' 3523 }; 3524 var 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); 3310 3668 }; 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]; 3405 m[5] = m[1] * x + m[3] * y + m[5]; 3406 <