1/** 2 * @licstart The following is the entire license notice for the 3 * Javascript code in this page 4 * 5 * Copyright 2021 Mozilla Foundation 6 * 7 * Licensed under the Apache License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. 9 * You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software 14 * distributed under the License is distributed on an "AS IS" BASIS, 15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 * See the License for the specific language governing permissions and 17 * limitations under the License. 18 * 19 * @licend The above is the entire license notice for the 20 * Javascript code in this page 21 */ 22 23(function webpackUniversalModuleDefinition(root, factory) { 24 if(typeof exports === 'object' && typeof module === 'object') 25 module.exports = factory(); 26 else if(typeof define === 'function' && define.amd) 27 define("pdfjs-dist/build/pdf", [], factory); 28 else if(typeof exports === 'object') 29 exports["pdfjs-dist/build/pdf"] = factory(); 30 else 31 root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory(); 32})(this, function() { 33return /******/ (() => { // webpackBootstrap 34/******/ "use strict"; 35/******/ var __webpack_modules__ = ([ 36/* 0 */, 37/* 1 */ 38/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 39 40 41 42Object.defineProperty(exports, "__esModule", ({ 43 value: true 44})); 45exports.addLinkAttributes = addLinkAttributes; 46exports.deprecated = deprecated; 47exports.getFilenameFromUrl = getFilenameFromUrl; 48exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl; 49exports.getXfaPageViewport = getXfaPageViewport; 50exports.isDataScheme = isDataScheme; 51exports.isPdfFile = isPdfFile; 52exports.isValidFetchUrl = isValidFetchUrl; 53exports.loadScript = loadScript; 54exports.StatTimer = exports.RenderingCancelledException = exports.PDFDateString = exports.PageViewport = exports.LinkTarget = exports.DOMSVGFactory = exports.DOMStandardFontDataFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = void 0; 55 56var _util = __w_pdfjs_require__(2); 57 58var _base_factory = __w_pdfjs_require__(5); 59 60const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; 61exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL; 62const SVG_NS = "http://www.w3.org/2000/svg"; 63 64class DOMCanvasFactory extends _base_factory.BaseCanvasFactory { 65 constructor({ 66 ownerDocument = globalThis.document 67 } = {}) { 68 super(); 69 this._document = ownerDocument; 70 } 71 72 _createCanvas(width, height) { 73 const canvas = this._document.createElement("canvas"); 74 75 canvas.width = width; 76 canvas.height = height; 77 return canvas; 78 } 79 80} 81 82exports.DOMCanvasFactory = DOMCanvasFactory; 83 84async function fetchData(url, asTypedArray = false) { 85 if (isValidFetchUrl(url, document.baseURI)) { 86 const response = await fetch(url); 87 88 if (!response.ok) { 89 throw new Error(response.statusText); 90 } 91 92 return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text()); 93 } 94 95 return new Promise((resolve, reject) => { 96 const request = new XMLHttpRequest(); 97 request.open("GET", url, true); 98 99 if (asTypedArray) { 100 request.responseType = "arraybuffer"; 101 } 102 103 request.onreadystatechange = () => { 104 if (request.readyState !== XMLHttpRequest.DONE) { 105 return; 106 } 107 108 if (request.status === 200 || request.status === 0) { 109 let data; 110 111 if (asTypedArray && request.response) { 112 data = new Uint8Array(request.response); 113 } else if (!asTypedArray && request.responseText) { 114 data = (0, _util.stringToBytes)(request.responseText); 115 } 116 117 if (data) { 118 resolve(data); 119 return; 120 } 121 } 122 123 reject(new Error(request.statusText)); 124 }; 125 126 request.send(null); 127 }); 128} 129 130class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory { 131 _fetchData(url, compressionType) { 132 return fetchData(url, this.isCompressed).then(data => { 133 return { 134 cMapData: data, 135 compressionType 136 }; 137 }); 138 } 139 140} 141 142exports.DOMCMapReaderFactory = DOMCMapReaderFactory; 143 144class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory { 145 _fetchData(url) { 146 return fetchData(url, true); 147 } 148 149} 150 151exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory; 152 153class DOMSVGFactory extends _base_factory.BaseSVGFactory { 154 _createSVG(type) { 155 return document.createElementNS(SVG_NS, type); 156 } 157 158} 159 160exports.DOMSVGFactory = DOMSVGFactory; 161 162class PageViewport { 163 constructor({
164 viewBox, 165 scale, 166 rotation, 167 offsetX = 0, 168 offsetY = 0, 169 dontFlip = false 170 }) { 171 this.viewBox = viewBox; 172 this.scale = scale; 173 this.rotation = rotation; 174 this.offsetX = offsetX; 175 this.offsetY = offsetY; 176 const centerX = (viewBox[2] + viewBox[0]) / 2; 177 const centerY = (viewBox[3] + viewBox[1]) / 2; 178 let rotateA, rotateB, rotateC, rotateD; 179 rotation %= 360; 180 181 if (rotation < 0) { 182 rotation += 360; 183 } 184 185 switch (rotation) { 186 case 180: 187 rotateA = -1; 188 rotateB = 0; 189 rotateC = 0; 190 rotateD = 1; 191 break; 192 193 case 90: 194 rotateA = 0; 195 rotateB = 1; 196 rotateC = 1; 197 rotateD = 0; 198 break; 199 200 case 270: 201 rotateA = 0; 202 rotateB = -1; 203 rotateC = -1; 204 rotateD = 0; 205 break; 206 207 case 0: 208 rotateA = 1; 209 rotateB = 0; 210 rotateC = 0; 211 rotateD = -1; 212 break; 213 214 default: 215 throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); 216 } 217 218 if (dontFlip) { 219 rotateC = -rotateC; 220 rotateD = -rotateD; 221 } 222 223 let offsetCanvasX, offsetCanvasY; 224 let width, height; 225 226 if (rotateA === 0) { 227 offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; 228 offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; 229 width = Math.abs(viewBox[3] - viewBox[1]) * scale; 230 height = Math.abs(viewBox[2] - viewBox[0]) * scale; 231 } else { 232 offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; 233 offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; 234 width = Math.abs(viewBox[2] - viewBox[0]) * scale; 235 height = Math.abs(viewBox[3] - viewBox[1]) * scale; 236 } 237 238 this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; 239 this.width = width; 240 this.height = height; 241 } 242 243 clone({ 244 scale = this.scale, 245 rotation = this.rotation, 246 offsetX = this.offsetX, 247 offsetY = this.offsetY, 248 dontFlip = false 249 } = {}) { 250 return new PageViewport({ 251 viewBox: this.viewBox.slice(), 252 scale, 253 rotation, 254 offsetX, 255 offsetY, 256 dontFlip 257 }); 258 } 259 260 convertToViewportPoint(x, y) { 261 return _util.Util.applyTransform([x, y], this.transform); 262 } 263 264 convertToViewportRectangle(rect) { 265 const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform); 266 267 const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform); 268 269 return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; 270 } 271 272 convertToPdfPoint(x, y) { 273 return _util.Util.applyInverseTransform([x, y], this.transform); 274 } 275 276} 277 278exports.PageViewport = PageViewport; 279 280class RenderingCancelledException extends _util.BaseException { 281 constructor(msg, type) { 282 super(msg); 283 this.type = type; 284 } 285 286} 287 288exports.RenderingCancelledException = RenderingCancelledException; 289const LinkTarget = { 290 NONE: 0, 291 SELF: 1, 292 BLANK: 2, 293 PARENT: 3, 294 TOP: 4 295}; 296exports.LinkTarget = LinkTarget; 297 298function addLinkAttributes(link, { 299 url, 300 target, 301 rel, 302 enabled = true 303} = {}) { 304 (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.'); 305 const urlNullRemoved = (0, _util.removeNullCharacters)(url); 306 307 if (enabled) { 308 link.href = link.title = urlNullRemoved; 309 } else { 310 link.href = ""; 311 link.title = `Disabled: ${urlNullRemoved}`; 312 313 link.onclick = () => { 314 return false; 315 }; 316 } 317 318 let targetStr = ""; 319 320 switch (target) { 321 case LinkTarget.NONE: 322 break; 323 324 case LinkTarget.SELF: 325 targetStr = "_self"; 326 break; 327 328 case LinkTarget.BLANK: 329 targetStr = "_blank"; 330 break; 331 332 case LinkTarget.PARENT: 333 targetStr = "_parent"; 334 break; 335 336 case LinkTarget.TOP: 337 targetStr = "_top"; 338 break; 339 } 340 341 link.target = targetStr; 342 link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; 343} 344 345function isDataScheme(url) { 346 const ii = url.length; 347 let i = 0; 348 349 while (i < ii && url[i].trim() === "") { 350 i++; 351 } 352 353 return url.substring(i, i + 5).toLowerCase() === "data:"; 354} 355 356function isPdfFile(filename) { 357 return typeof filename === "string" && /\.pdf$/i.test(filename); 358} 359 360function getFilenameFromUrl(url) { 361 const anchor = url.indexOf("#"); 362 const query = url.indexOf("?"); 363 const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length); 364 return url.substring(url.lastIndexOf("/", end) + 1, end); 365} 366 367function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { 368 if (typeof url !== "string") { 369 return defaultFilename; 370 } 371 372 if (isDataScheme(url)) { 373 (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); 374 return defaultFilename; 375 } 376 377 const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; 378 const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; 379 const splitURI = reURI.exec(url); 380 let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); 381 382 if (suggestedFilename) { 383 suggestedFilename = suggestedFilename[0]; 384 385 if (suggestedFilename.includes("%")) {
386 try { 387 suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0]; 388 } catch (ex) {} 389 } 390 } 391 392 return suggestedFilename || defaultFilename; 393} 394 395class StatTimer { 396 constructor() { 397 this.started = Object.create(null); 398 this.times = []; 399 } 400 401 time(name) { 402 if (name in this.started) { 403 (0, _util.warn)(`Timer is already running for ${name}`); 404 } 405 406 this.started[name] = Date.now(); 407 } 408 409 timeEnd(name) { 410 if (!(name in this.started)) { 411 (0, _util.warn)(`Timer has not been started for ${name}`); 412 } 413 414 this.times.push({ 415 name, 416 start: this.started[name], 417 end: Date.now() 418 }); 419 delete this.started[name]; 420 } 421 422 toString() { 423 const outBuf = []; 424 let longest = 0; 425 426 for (const time of this.times) { 427 const name = time.name; 428 429 if (name.length > longest) { 430 longest = name.length; 431 } 432 } 433 434 for (const time of this.times) { 435 const duration = time.end - time.start; 436 outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`); 437 } 438 439 return outBuf.join(""); 440 } 441 442} 443 444exports.StatTimer = StatTimer; 445 446function isValidFetchUrl(url, baseUrl) { 447 try { 448 const { 449 protocol 450 } = baseUrl ? new URL(url, baseUrl) : new URL(url); 451 return protocol === "http:" || protocol === "https:"; 452 } catch (ex) { 453 return false; 454 } 455} 456 457function loadScript(src, removeScriptElement = false) { 458 return new Promise((resolve, reject) => { 459 const script = document.createElement("script"); 460 script.src = src; 461 462 script.onload = function (evt) { 463 if (removeScriptElement) { 464 script.remove(); 465 } 466 467 resolve(evt); 468 }; 469 470 script.onerror = function () { 471 reject(new Error(`Cannot load script at: ${script.src}`)); 472 }; 473 474 (document.head || document.documentElement).appendChild(script); 475 }); 476} 477 478function deprecated(details) { 479 console.log("Deprecated API usage: " + details); 480} 481 482let pdfDateStringRegex; 483 484class PDFDateString { 485 static toDateObject(input) { 486 if (!input || !(0, _util.isString)(input)) { 487 return null; 488 } 489 490 if (!pdfDateStringRegex) { 491 pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?"); 492 } 493 494 const matches = pdfDateStringRegex.exec(input); 495 496 if (!matches) { 497 return null; 498 } 499 500 const year = parseInt(matches[1], 10); 501 let month = parseInt(matches[2], 10);
502 month = month >= 1 && month <= 12 ? month - 1 : 0; 503 let day = parseInt(matches[3], 10); 504 day = day >= 1 && day <= 31 ? day : 1; 505 let hour = parseInt(matches[4], 10); 506 hour = hour >= 0 && hour <= 23 ? hour : 0; 507 let minute = parseInt(matches[5], 10); 508 minute = minute >= 0 && minute <= 59 ? minute : 0; 509 let second = parseInt(matches[6], 10); 510 second = second >= 0 && second <= 59 ? second : 0; 511 const universalTimeRelation = matches[7] || "Z"; 512 let offsetHour = parseInt(matches[8], 10); 513 offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; 514 let offsetMinute = parseInt(matches[9], 10) || 0; 515 offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; 516 517 if (universalTimeRelation === "-") { 518 hour += offsetHour; 519 minute += offsetMinute; 520 } else if (universalTimeRelation === "+") { 521 hour -= offsetHour; 522 minute -= offsetMinute; 523 } 524 525 return new Date(Date.UTC(year, month, day, hour, minute, second)); 526 } 527 528} 529 530exports.PDFDateString = PDFDateString; 531 532function getXfaPageViewport(xfaPage, { 533 scale = 1, 534 rotation = 0 535}) { 536 const { 537 width, 538 height 539 } = xfaPage.attributes.style; 540 const viewBox = [0, 0, parseInt(width), parseInt(height)]; 541 return new PageViewport({ 542 viewBox, 543 scale, 544 rotation 545 }); 546} 547 548/***/ }), 549/* 2 */ 550/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 551 552 553 554Object.defineProperty(exports, "__esModule", ({ 555 value: true 556})); 557exports.arrayByteLength = arrayByteLength; 558exports.arraysToBytes = arraysToBytes; 559exports.assert = assert; 560exports.bytesToString = bytesToString; 561exports.createObjectURL = createObjectURL; 562exports.createPromiseCapability = createPromiseCapability; 563exports.createValidAbsoluteUrl = createValidAbsoluteUrl; 564exports.escapeString = escapeString; 565exports.getModificationDate = getModificationDate; 566exports.getVerbosityLevel = getVerbosityLevel; 567exports.info = info; 568exports.isArrayBuffer = isArrayBuffer; 569exports.isArrayEqual = isArrayEqual; 570exports.isAscii = isAscii; 571exports.isBool = isBool; 572exports.isNum = isNum; 573exports.isSameOrigin = isSameOrigin; 574exports.isString = isString; 575exports.objectFromMap = objectFromMap; 576exports.objectSize = objectSize; 577exports.removeNullCharacters = removeNullCharacters; 578exports.setVerbosityLevel = setVerbosityLevel; 579exports.shadow = shadow; 580exports.string32 = string32; 581exports.stringToBytes = stringToBytes; 582exports.stringToPDFString = stringToPDFString; 583exports.stringToUTF16BEString = stringToUTF16BEString; 584exports.stringToUTF8String = stringToUTF8String; 585exports.unreachable = unreachable; 586exports.utf8StringToString = utf8StringToString; 587exports.warn = warn; 588exports.VerbosityLevel = exports.Util = exports.UNSUPPORTED_FEATURES = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.IsLittleEndianCached = exports.IsEvalSupportedCached = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0; 589 590__w_pdfjs_require__(3); 591 592const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; 593exports.IDENTITY_MATRIX = IDENTITY_MATRIX; 594const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; 595exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; 596const PermissionFlag = { 597 PRINT: 0x04, 598 MODIFY_CONTENTS: 0x08, 599 COPY: 0x10, 600 MODIFY_ANNOTATIONS: 0x20, 601 FILL_INTERACTIVE_FORMS: 0x100, 602 COPY_FOR_ACCESSIBILITY: 0x200, 603 ASSEMBLE: 0x400, 604 PRINT_HIGH_QUALITY: 0x800 605}; 606exports.PermissionFlag = PermissionFlag; 607const TextRenderingMode = { 608 FILL: 0, 609 STROKE: 1, 610 FILL_STROKE: 2, 611 INVISIBLE: 3, 612 FILL_ADD_TO_PATH: 4, 613 STROKE_ADD_TO_PATH: 5, 614 FILL_STROKE_ADD_TO_PATH: 6, 615 ADD_TO_PATH: 7, 616 FILL_STROKE_MASK: 3, 617 ADD_TO_PATH_FLAG: 4 618}; 619exports.TextRenderingMode = TextRenderingMode; 620const ImageKind = { 621 GRAYSCALE_1BPP: 1, 622 RGB_24BPP: 2, 623 RGBA_32BPP: 3 624}; 625exports.ImageKind = ImageKind; 626const AnnotationType = { 627 TEXT: 1, 628 LINK: 2, 629 FREETEXT: 3, 630 LINE: 4, 631 SQUARE: 5, 632 CIRCLE: 6, 633 POLYGON: 7, 634 POLYLINE: 8, 635 HIGHLIGHT: 9, 636 UNDERLINE: 10, 637 SQUIGGLY: 11, 638 STRIKEOUT: 12, 639 STAMP: 13, 640 CARET: 14, 641 INK: 15, 642 POPUP: 16, 643 FILEATTACHMENT: 17, 644 SOUND: 18, 645 MOVIE: 19, 646 WIDGET: 20, 647 SCREEN: 21, 648 PRINTERMARK: 22, 649 TRAPNET: 23, 650 WATERMARK: 24, 651 THREED: 25, 652 REDACT: 26 653}; 654exports.AnnotationType = AnnotationType; 655const AnnotationStateModelType = { 656 MARKED: "Marked", 657 REVIEW: "Review" 658}; 659exports.AnnotationStateModelType = AnnotationStateModelType; 660const AnnotationMarkedState = { 661 MARKED: "Marked", 662 UNMARKED: "Unmarked" 663}; 664exports.AnnotationMarkedState = AnnotationMarkedState; 665const AnnotationReviewState = { 666 ACCEPTED: "Accepted", 667 REJECTED: "Rejected", 668 CANCELLED: "Cancelled", 669 COMPLETED: "Completed", 670 NONE: "None" 671}; 672exports.AnnotationReviewState = AnnotationReviewState; 673const AnnotationReplyType = { 674 GROUP: "Group", 675 REPLY: "R" 676}; 677exports.AnnotationReplyType = AnnotationReplyType; 678const AnnotationFlag = { 679 INVISIBLE: 0x01, 680 HIDDEN: 0x02, 681 PRINT: 0x04, 682 NOZOOM: 0x08,
683 NOROTATE: 0x10, 684 NOVIEW: 0x20, 685 READONLY: 0x40, 686 LOCKED: 0x80, 687 TOGGLENOVIEW: 0x100, 688 LOCKEDCONTENTS: 0x200 689}; 690exports.AnnotationFlag = AnnotationFlag; 691const AnnotationFieldFlag = { 692 READONLY: 0x0000001, 693 REQUIRED: 0x0000002, 694 NOEXPORT: 0x0000004, 695 MULTILINE: 0x0001000, 696 PASSWORD: 0x0002000, 697 NOTOGGLETOOFF: 0x0004000, 698 RADIO: 0x0008000, 699 PUSHBUTTON: 0x0010000, 700 COMBO: 0x0020000, 701 EDIT: 0x0040000, 702 SORT: 0x0080000, 703 FILESELECT: 0x0100000, 704 MULTISELECT: 0x0200000, 705 DONOTSPELLCHECK: 0x0400000, 706 DONOTSCROLL: 0x0800000, 707 COMB: 0x1000000, 708 RICHTEXT: 0x2000000, 709 RADIOSINUNISON: 0x2000000, 710 COMMITONSELCHANGE: 0x4000000 711}; 712exports.AnnotationFieldFlag = AnnotationFieldFlag; 713const AnnotationBorderStyleType = { 714 SOLID: 1, 715 DASHED: 2, 716 BEVELED: 3, 717 INSET: 4, 718 UNDERLINE: 5 719}; 720exports.AnnotationBorderStyleType = AnnotationBorderStyleType; 721const AnnotationActionEventType = { 722 E: "Mouse Enter", 723 X: "Mouse Exit", 724 D: "Mouse Down", 725 U: "Mouse Up", 726 Fo: "Focus", 727 Bl: "Blur", 728 PO: "PageOpen", 729 PC: "PageClose", 730 PV: "PageVisible", 731 PI: "PageInvisible", 732 K: "Keystroke", 733 F: "Format", 734 V: "Validate", 735 C: "Calculate" 736}; 737exports.AnnotationActionEventType = AnnotationActionEventType; 738const DocumentActionEventType = { 739 WC: "WillClose", 740 WS: "WillSave", 741 DS: "DidSave", 742 WP: "WillPrint", 743 DP: "DidPrint" 744}; 745exports.DocumentActionEventType = DocumentActionEventType; 746const PageActionEventType = { 747 O: "PageOpen", 748 C: "PageClose" 749}; 750exports.PageActionEventType = PageActionEventType; 751const StreamType = { 752 UNKNOWN: "UNKNOWN", 753 FLATE: "FLATE", 754 LZW: "LZW", 755 DCT: "DCT", 756 JPX: "JPX", 757 JBIG: "JBIG", 758 A85: "A85", 759 AHX: "AHX", 760 CCF: "CCF", 761 RLX: "RLX" 762}; 763exports.StreamType = StreamType; 764const FontType = { 765 UNKNOWN: "UNKNOWN", 766 TYPE1: "TYPE1", 767 TYPE1STANDARD: "TYPE1STANDARD", 768 TYPE1C: "TYPE1C", 769 CIDFONTTYPE0: "CIDFONTTYPE0", 770 CIDFONTTYPE0C: "CIDFONTTYPE0C", 771 TRUETYPE: "TRUETYPE", 772 CIDFONTTYPE2: "CIDFONTTYPE2", 773 TYPE3: "TYPE3", 774 OPENTYPE: "OPENTYPE", 775 TYPE0: "TYPE0", 776 MMTYPE1: "MMTYPE1" 777}; 778exports.FontType = FontType; 779const VerbosityLevel = { 780 ERRORS: 0, 781 WARNINGS: 1, 782 INFOS: 5 783}; 784exports.VerbosityLevel = VerbosityLevel; 785const CMapCompressionType = { 786 NONE: 0, 787 BINARY: 1, 788 STREAM: 2 789}; 790exports.CMapCompressionType = CMapCompressionType; 791const OPS = { 792 dependency: 1, 793 setLineWidth: 2, 794 setLineCap: 3, 795 setLineJoin: 4, 796 setMiterLimit: 5, 797 setDash: 6, 798 setRenderingIntent: 7, 799 setFlatness: 8, 800 setGState: 9, 801 save: 10, 802 restore: 11, 803 transform: 12, 804 moveTo: 13, 805 lineTo: 14, 806 curveTo: 15, 807 curveTo2: 16,
808 curveTo3: 17, 809 closePath: 18, 810 rectangle: 19, 811 stroke: 20, 812 closeStroke: 21, 813 fill: 22, 814 eoFill: 23, 815 fillStroke: 24, 816 eoFillStroke: 25, 817 closeFillStroke: 26, 818 closeEOFillStroke: 27, 819 endPath: 28, 820 clip: 29, 821 eoClip: 30, 822 beginText: 31, 823 endText: 32, 824 setCharSpacing: 33, 825 setWordSpacing: 34, 826 setHScale: 35, 827 setLeading: 36, 828 setFont: 37, 829 setTextRenderingMode: 38, 830 setTextRise: 39, 831 moveText: 40, 832 setLeadingMoveText: 41, 833 setTextMatrix: 42, 834 nextLine: 43, 835 showText: 44, 836 showSpacedText: 45, 837 nextLineShowText: 46, 838 nextLineSetSpacingShowText: 47, 839 setCharWidth: 48, 840 setCharWidthAndBounds: 49, 841 setStrokeColorSpace: 50, 842 setFillColorSpace: 51, 843 setStrokeColor: 52, 844 setStrokeColorN: 53, 845 setFillColor: 54, 846 setFillColorN: 55, 847 setStrokeGray: 56, 848 setFillGray: 57, 849 setStrokeRGBColor: 58, 850 setFillRGBColor: 59, 851 setStrokeCMYKColor: 60, 852 setFillCMYKColor: 61, 853 shadingFill: 62, 854 beginInlineImage: 63, 855 beginImageData: 64, 856 endInlineImage: 65, 857 paintXObject: 66, 858 markPoint: 67, 859 markPointProps: 68, 860 beginMarkedContent: 69, 861 beginMarkedContentProps: 70, 862 endMarkedContent: 71, 863 beginCompat: 72, 864 endCompat: 73, 865 paintFormXObjectBegin: 74, 866 paintFormXObjectEnd: 75, 867 beginGroup: 76, 868 endGroup: 77, 869 beginAnnotations: 78, 870 endAnnotations: 79, 871 beginAnnotation: 80, 872 endAnnotation: 81, 873 paintJpegXObject: 82, 874 paintImageMaskXObject: 83, 875 paintImageMaskXObjectGroup: 84, 876 paintImageXObject: 85, 877 paintInlineImageXObject: 86, 878 paintInlineImageXObjectGroup: 87, 879 paintImageXObjectRepeat: 88, 880 paintImageMaskXObjectRepeat: 89, 881 paintSolidColorImageMask: 90, 882 constructPath: 91 883}; 884exports.OPS = OPS; 885const UNSUPPORTED_FEATURES = { 886 unknown: "unknown", 887 forms: "forms", 888 javaScript: "javaScript", 889 signatures: "signatures", 890 smask: "smask", 891 shadingPattern: "shadingPattern", 892 font: "font", 893 errorTilingPattern: "errorTilingPattern", 894 errorExtGState: "errorExtGState", 895 errorXObject: "errorXObject", 896 errorFontLoadType3: "errorFontLoadType3", 897 errorFontState: "errorFontState", 898 errorFontMissing: "errorFontMissing", 899 errorFontTranslate: "errorFontTranslate", 900 errorColorSpace: "errorColorSpace", 901 errorOperatorList: "errorOperatorList", 902 errorFontToUnicode: "errorFontToUnicode", 903 errorFontLoadNative: "errorFontLoadNative", 904 errorFontBuildPath: "errorFontBuildPath", 905 errorFontGetPath: "errorFontGetPath", 906 errorMarkedContent: "errorMarkedContent" 907}; 908exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; 909const PasswordResponses = { 910 NEED_PASSWORD: 1, 911 INCORRECT_PASSWORD: 2 912}; 913exports.PasswordResponses = PasswordResponses; 914let verbosity = VerbosityLevel.WARNINGS; 915 916function setVerbosityLevel(level) { 917 if (Number.isInteger(level)) { 918 verbosity = level; 919 } 920} 921 922function getVerbosityLevel() { 923 return verbosity; 924} 925 926function info(msg) { 927 if (verbosity >= VerbosityLevel.INFOS) { 928 console.log(`Info: ${msg}`); 929 } 930} 931 932function warn(msg) { 933 if (verbosity >= VerbosityLevel.WARNINGS) { 934 console.log(`Warning: ${msg}`); 935 } 936} 937 938function unreachable(msg) { 939 throw new Error(msg); 940} 941 942function assert(cond, msg) { 943 if (!cond) { 944 unreachable(msg); 945 } 946} 947 948function isSameOrigin(baseUrl, otherUrl) { 949 let base; 950 951 try { 952 base = new URL(baseUrl); 953 954 if (!base.origin || base.origin === "null") { 955 return false; 956 } 957 } catch (e) { 958 return false; 959 } 960 961 const other = new URL(otherUrl, base); 962 return base.origin === other.origin; 963} 964 965function _isValidProtocol(url) { 966 if (!url) { 967 return false; 968 } 969 970 switch (url.protocol) { 971 case "http:": 972 case "https:": 973 case "ftp:": 974 case "mailto:": 975 case "tel:": 976 return true; 977 978 default: 979 return false; 980 } 981} 982 983function createValidAbsoluteUrl(url, baseUrl) { 984 if (!url) { 985 return null; 986 } 987 988 try { 989 const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url); 990 991 if (_isValidProtocol(absoluteUrl)) { 992 return absoluteUrl; 993 } 994 } catch (ex) {} 995 996 return null; 997} 998 999function shadow(obj, prop, value) { 1000 Object.defineProperty(obj, prop, { 1001 value, 1002 enumerable: true, 1003 configurable: true, 1004 writable: false 1005 }); 1006 return value; 1007} 1008 1009const BaseException = function BaseExceptionClosure() { 1010 function BaseException(message) { 1011 if (this.constructor === BaseException) { 1012 unreachable("Cannot initialize BaseException."); 1013 } 1014 1015 this.message = message; 1016 this.name = this.constructor.name; 1017 } 1018 1019 BaseException.prototype = new Error(); 1020 BaseException.constructor = BaseException; 1021 return BaseException; 1022}(); 1023 1024exports.BaseException = BaseException; 1025 1026class PasswordException extends BaseException { 1027 constructor(msg, code) { 1028 super(msg); 1029 this.code = code; 1030 } 1031 1032} 1033 1034exports.PasswordException = PasswordException; 1035 1036class UnknownErrorException extends BaseException { 1037 constructor(msg, details) { 1038 super(msg); 1039 this.details = details; 1040 } 1041 1042} 1043 1044exports.UnknownErrorException = UnknownErrorException; 1045 1046class InvalidPDFException extends BaseException {} 1047 1048exports.InvalidPDFException = InvalidPDFException; 1049 1050class MissingPDFException extends BaseException {} 1051 1052exports.MissingPDFException = MissingPDFException; 1053 1054class UnexpectedResponseException extends BaseException { 1055 constructor(msg, status) { 1056 super(msg); 1057 this.status = status; 1058 } 1059 1060} 1061 1062exports.UnexpectedResponseException = UnexpectedResponseException; 1063 1064class FormatError extends BaseException {} 1065 1066exports.FormatError = FormatError; 1067 1068class AbortException extends BaseException {} 1069 1070exports.AbortException = AbortException; 1071const NullCharactersRegExp = /\x00/g; 1072 1073function removeNullCharacters(str) { 1074 if (typeof str !== "string") { 1075 warn("The argument for removeNullCharacters must be a string."); 1076 return str; 1077 } 1078 1079 return str.replace(NullCharactersRegExp, ""); 1080} 1081 1082function bytesToString(bytes) { 1083 assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString"); 1084 const length = bytes.length; 1085 const MAX_ARGUMENT_COUNT = 8192; 1086 1087 if (length < MAX_ARGUMENT_COUNT) { 1088 return String.fromCharCode.apply(null, bytes); 1089 } 1090 1091 const strBuf = []; 1092 1093 for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) { 1094 const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); 1095 const chunk = bytes.subarray(i, chunkEnd); 1096 strBuf.push(String.fromCharCode.apply(null, chunk)); 1097 } 1098 1099 return strBuf.join(""); 1100} 1101 1102function stringToBytes(str) { 1103 assert(typeof str === "string", "Invalid argument for stringToBytes"); 1104 const length = str.length; 1105 const bytes = new Uint8Array(length); 1106 1107 for (let i = 0; i < length; ++i) { 1108 bytes[i] = str.charCodeAt(i) & 0xff;
vendor: 4,446 bytes, lines 1109-1282
1109 } 1110 1111 return bytes; 1112} 1113 1114function arrayByteLength(arr) { 1115 if (arr.length !== undefined) { 1116 return arr.length; 1117 } 1118 1119 assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument."); 1120 return arr.byteLength; 1121} 1122 1123function arraysToBytes(arr) { 1124 const length = arr.length; 1125 1126 if (length === 1 && arr[0] instanceof Uint8Array) { 1127 return arr[0]; 1128 } 1129 1130 let resultLength = 0; 1131 1132 for (let i = 0; i < length; i++) { 1133 resultLength += arrayByteLength(arr[i]); 1134 } 1135 1136 let pos = 0; 1137 const data = new Uint8Array(resultLength); 1138 1139 for (let i = 0; i < length; i++) { 1140 let item = arr[i]; 1141 1142 if (!(item instanceof Uint8Array)) { 1143 if (typeof item === "string") { 1144 item = stringToBytes(item); 1145 } else { 1146 item = new Uint8Array(item); 1147 } 1148 } 1149 1150 const itemLength = item.byteLength; 1151 data.set(item, pos); 1152 pos += itemLength; 1153 } 1154 1155 return data; 1156} 1157 1158function string32(value) { 1159 return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff); 1160} 1161 1162function objectSize(obj) { 1163 return Object.keys(obj).length; 1164} 1165 1166function objectFromMap(map) { 1167 const obj = Object.create(null); 1168 1169 for (const [key, value] of map) { 1170 obj[key] = value; 1171 } 1172 1173 return obj; 1174} 1175 1176function isLittleEndian() { 1177 const buffer8 = new Uint8Array(4); 1178 buffer8[0] = 1; 1179 const view32 = new Uint32Array(buffer8.buffer, 0, 1); 1180 return view32[0] === 1; 1181} 1182 1183const IsLittleEndianCached = { 1184 get value() { 1185 return shadow(this, "value", isLittleEndian()); 1186 } 1187 1188}; 1189exports.IsLittleEndianCached = IsLittleEndianCached; 1190 1191function isEvalSupported() { 1192 try { 1193 new Function(""); 1194 return true; 1195 } catch (e) { 1196 return false; 1197 } 1198} 1199 1200const IsEvalSupportedCached = { 1201 get value() { 1202 return shadow(this, "value", isEvalSupported()); 1203 } 1204 1205}; 1206exports.IsEvalSupportedCached = IsEvalSupportedCached; 1207const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0")); 1208 1209class Util { 1210 static makeHexColor(r, g, b) { 1211 return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`; 1212 } 1213 1214 static transform(m1, m2) { 1215 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]]; 1216 } 1217 1218 static applyTransform(p, m) { 1219 const xt = p[0] * m[0] + p[1] * m[2] + m[4]; 1220 const yt = p[0] * m[1] + p[1] * m[3] + m[5]; 1221 return [xt, yt]; 1222 } 1223 1224 static applyInverseTransform(p, m) { 1225 const d = m[0] * m[3] - m[1] * m[2]; 1226 const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; 1227 const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; 1228 return [xt, yt]; 1229 } 1230 1231 static getAxialAlignedBoundingBox(r, m) { 1232 const p1 = Util.applyTransform(r, m); 1233 const p2 = Util.applyTransform(r.slice(2, 4), m); 1234 const p3 = Util.applyTransform([r[0], r[3]], m); 1235 const p4 = Util.applyTransform([r[2], r[1]], m); 1236 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])]; 1237 } 1238 1239 static inverseTransform(m) { 1240 const d = m[0] * m[3] - m[1] * m[2]; 1241 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]; 1242 } 1243 1244 static apply3dTransform(m, v) { 1245 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]]; 1246 } 1247 1248 static singularValueDecompose2dScale(m) { 1249 const transpose = [m[0], m[2], m[1], m[3]]; 1250 const a = m[0] * transpose[0] + m[1] * transpose[2]; 1251 const b = m[0] * transpose[1] + m[1] * transpose[3]; 1252 const c = m[2] * transpose[0] + m[3] * transpose[2]; 1253 const d = m[2] * transpose[1] + m[3] * transpose[3]; 1254 const first = (a + d) / 2; 1255 const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2; 1256 const sx = first + second || 1; 1257 const sy = first - second || 1; 1258 return [Math.sqrt(sx), Math.sqrt(sy)]; 1259 } 1260 1261 static normalizeRect(rect) { 1262 const r = rect.slice(0); 1263 1264 if (rect[0] > rect[2]) { 1265 r[0] = rect[2]; 1266 r[2] = rect[0]; 1267 } 1268 1269 if (rect[1] > rect[3]) { 1270 r[1] = rect[3]; 1271 r[3] = rect[1]; 1272 } 1273 1274 return r; 1275 } 1276 1277 static intersect(rect1, rect2) { 1278 function compare(a, b) { 1279 return a - b; 1280 } 1281 1282 const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
1283 const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare); 1284 const result = []; 1285 rect1 = Util.normalizeRect(rect1); 1286 rect2 = Util.normalizeRect(rect2); 1287 1288 if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) { 1289 result[0] = orderedX[1]; 1290 result[2] = orderedX[2]; 1291 } else { 1292 return null; 1293 } 1294 1295 if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) { 1296 result[1] = orderedY[1]; 1297 result[3] = orderedY[2]; 1298 } else { 1299 return null; 1300 } 1301 1302 return result; 1303 } 1304 1305} 1306 1307exports.Util = Util; 1308const 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]; 1309 1310function stringToPDFString(str) { 1311 const length = str.length, 1312 strBuf = []; 1313 1314 if (str[0] === "\xFE" && str[1] === "\xFF") { 1315 for (let i = 2; i < length; i += 2) { 1316 strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1))); 1317 } 1318 } else if (str[0] === "\xFF" && str[1] === "\xFE") { 1319 for (let i = 2; i < length; i += 2) { 1320 strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i))); 1321 } 1322 } else { 1323 for (let i = 0; i < length; ++i) { 1324 const code = PDFStringTranslateTable[str.charCodeAt(i)]; 1325 strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); 1326 } 1327 } 1328 1329 return strBuf.join(""); 1330} 1331 1332function escapeString(str) { 1333 return str.replace(/([()\\\n\r])/g, match => { 1334 if (match === "\n") { 1335 return "\\n"; 1336 } else if (match === "\r") { 1337 return "\\r"; 1338 } 1339 1340 return `\\${match}`; 1341 }); 1342} 1343 1344function isAscii(str) { 1345 return /^[\x00-\x7F]*$/.test(str); 1346} 1347 1348function stringToUTF16BEString(str) { 1349 const buf = ["\xFE\xFF"]; 1350 1351 for (let i = 0, ii = str.length; i < ii; i++) { 1352 const char = str.charCodeAt(i); 1353 buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff)); 1354 } 1355 1356 return buf.join(""); 1357} 1358 1359function stringToUTF8String(str) { 1360 return decodeURIComponent(escape(str)); 1361} 1362 1363function utf8StringToString(str) { 1364 return unescape(encodeURIComponent(str)); 1365} 1366 1367function isBool(v) { 1368 return typeof v === "boolean"; 1369} 1370 1371function isNum(v) { 1372 return typeof v === "number"; 1373} 1374 1375function isString(v) { 1376 return typeof v === "string"; 1377} 1378 1379function isArrayBuffer(v) { 1380 return typeof v === "object" && v !== null && v.byteLength !== undefined; 1381} 1382 1383function isArrayEqual(arr1, arr2) { 1384 if (arr1.length !== arr2.length) { 1385 return false; 1386 } 1387 1388 for (let i = 0, ii = arr1.length; i < ii; i++) { 1389 if (arr1[i] !== arr2[i]) { 1390 return false; 1391 } 1392 } 1393 1394 return true; 1395} 1396 1397function getModificationDate(date = new Date()) { 1398 const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")]; 1399 return buffer.join(""); 1400} 1401 1402function createPromiseCapability() { 1403 const capability = Object.create(null); 1404 let isSettled = false; 1405 Object.defineProperty(capability, "settled", { 1406 get() { 1407 return isSettled; 1408 } 1409 1410 }); 1411 capability.promise = new Promise(function (resolve, reject) { 1412 capability.resolve = function (data) { 1413 isSettled = true; 1414 resolve(data); 1415 }; 1416 1417 capability.reject = function (reason) { 1418 isSettled = true; 1419 reject(reason); 1420 }; 1421 }); 1422 return capability; 1423} 1424 1425function createObjectURL(data, contentType = "", forceDataSchema = false) { 1426 if (URL.createObjectURL && !forceDataSchema) { 1427 return URL.createObjectURL(new Blob([data], { 1428 type: contentType 1429 })); 1430 } 1431 1432 const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
1432+/="; 1433 let buffer = `data:${contentType};base64,`; 1434 1435 for (let i = 0, ii = data.length; i < ii; i += 3) { 1436 const b1 = data[i] & 0xff; 1437 const b2 = data[i + 1] & 0xff; 1438 const b3 = data[i + 2] & 0xff; 1439 const d1 = b1 >> 2, 1440 d2 = (b1 & 3) << 4 | b2 >> 4; 1441 const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64; 1442 const d4 = i + 2 < ii ? b3 & 0x3f : 64; 1443 buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; 1444 } 1445 1446 return buffer; 1447} 1448 1449/***/ }), 1450/* 3 */ 1451/***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => { 1452 1453 1454 1455var _is_node = __w_pdfjs_require__(4); 1456 1457; 1458 1459/***/ }), 1460/* 4 */ 1461/***/ ((__unused_webpack_module, exports) => { 1462 1463 1464 1465Object.defineProperty(exports, "__esModule", ({ 1466 value: true 1467})); 1468exports.isNodeJS = void 0; 1469const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); 1470exports.isNodeJS = isNodeJS; 1471 1472/***/ }), 1473/* 5 */ 1474/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 1475 1476 1477 1478Object.defineProperty(exports, "__esModule", ({ 1479 value: true 1480})); 1481exports.BaseSVGFactory = exports.BaseStandardFontDataFactory = exports.BaseCMapReaderFactory = exports.BaseCanvasFactory = void 0; 1482 1483var _util = __w_pdfjs_require__(2); 1484 1485class BaseCanvasFactory { 1486 constructor() { 1487 if (this.constructor === BaseCanvasFactory) { 1488 (0, _util.unreachable)("Cannot initialize BaseCanvasFactory."); 1489 } 1490 } 1491 1492 create(width, height) { 1493 if (width <= 0 || height <= 0) { 1494 throw new Error("Invalid canvas size"); 1495 } 1496 1497 const canvas = this._createCanvas(width, height); 1498 1499 return { 1500 canvas, 1501 context: canvas.getContext("2d") 1502 }; 1503 } 1504 1505 reset(canvasAndContext, width, height) { 1506 if (!canvasAndContext.canvas) { 1507 throw new Error("Canvas is not specified"); 1508 } 1509 1510 if (width <= 0 || height <= 0) { 1511 throw new Error("Invalid canvas size"); 1512 } 1513 1514 canvasAndContext.canvas.width = width; 1515 canvasAndContext.canvas.height = height; 1516 } 1517 1518 destroy(canvasAndContext) { 1519 if (!canvasAndContext.canvas) { 1520 throw new Error("Canvas is not specified"); 1521 } 1522 1523 canvasAndContext.canvas.width = 0; 1524 canvasAndContext.canvas.height = 0; 1525 canvasAndContext.canvas = null; 1526 canvasAndContext.context = null; 1527 } 1528 1529 _createCanvas(width, height) { 1530 (0, _util.unreachable)("Abstract method `_createCanvas` called."); 1531 } 1532 1533} 1534 1535exports.BaseCanvasFactory = BaseCanvasFactory; 1536 1537class BaseCMapReaderFactory { 1538 constructor({ 1539 baseUrl = null, 1540 isCompressed = false 1541 }) { 1542 if (this.constructor === BaseCMapReaderFactory) { 1543 (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory."); 1544 } 1545 1546 this.baseUrl = baseUrl; 1547 this.isCompressed = isCompressed; 1548 } 1549 1550 async fetch({ 1551 name 1552 }) { 1553 if (!this.baseUrl) { 1554 throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.'); 1555 } 1556 1557 if (!name) { 1558 throw new Error("CMap name must be specified."); 1559 } 1560 1561 const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); 1562 const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE; 1563 return this._fetchData(url, compressionType).catch(reason => { 1564 throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); 1565 }); 1566 } 1567 1568 _fetchData(url, compressionType) { 1569 (0, _util.unreachable)("Abstract method `_fetchData` called."); 1570 } 1571 1572} 1573 1574exports.BaseCMapReaderFactory = BaseCMapReaderFactory; 1575 1576class BaseStandardFontDataFactory { 1577 constructor({ 1578 baseUrl = null 1579 }) { 1580 if (this.constructor === BaseStandardFontDataFactory) { 1581 (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory."); 1582 } 1583 1584 this.baseUrl = baseUrl; 1585 } 1586 1587 async fetch({ 1588 filename 1589 }) { 1590 if (!this.baseUrl) { 1591 throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.'); 1592 } 1593 1594 if (!filename) { 1595 throw new Error("Font filename must be specified."); 1596 } 1597 1598 const url = `${this.baseUrl}${filename}`; 1599 return this._fetchData(url).catch(reason => { 1600 throw new Error(`Unable to load font data at: ${url}`); 1601 }); 1602 } 1603 1604 _fetchData(url) { 1605 (0, _util.unreachable)("Abstract method `_fetchData` called."); 1606 } 1607 1608} 1609 1610exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory; 1611 1612class BaseSVGFactory { 1613 constructor() { 1614 if (this.constructor === BaseSVGFactory) { 1615 (0, _util.unreachable)("Cannot initialize BaseSVGFactory."); 1616 } 1617 } 1618 1619 create(width, height) { 1620 if (width <= 0 || height <= 0) { 1621 throw new Error("Invalid SVG dimensions"); 1622 } 1623 1624 const svg = this._createSVG("svg:svg"); 1625 1626 svg.setAttribute("version", "1.1"); 1627 svg.setAttribute("width", `${width}px`); 1628 svg.setAttribute("height", `${height}px`); 1629 svg.setAttribute("preserveAspectRatio", "none"); 1630 svg.setAttribute("viewBox", `0 0 ${width} ${height}`); 1631 return svg; 1632 } 1633 1634 createElement(type) { 1635 if (typeof type !== "string") { 1636 throw new Error("Invalid SVG element type"); 1637 } 1638 1639 return this._createSVG(type); 1640 } 1641 1642 _createSVG(type) { 1643 (0, _util.unreachable)("Abstract method `_createSVG` called."); 1644 } 1645 1646} 1647 1648exports.BaseSVGFactory = BaseSVGFactory; 1649 1650/***/ }), 1651/* 6 */ 1652/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 1653 1654 1655 1656Object.defineProperty(exports, "__esModule", ({ 1657 value: true 1658})); 1659exports.getDocument = getDocument; 1660exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory; 1661exports.version = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exp
1661orts.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0; 1662 1663var _util = __w_pdfjs_require__(2); 1664 1665var _display_utils = __w_pdfjs_require__(1); 1666 1667var _font_loader = __w_pdfjs_require__(7); 1668 1669var _node_utils = __w_pdfjs_require__(8); 1670 1671var _annotation_storage = __w_pdfjs_require__(9); 1672 1673var _canvas = __w_pdfjs_require__(10); 1674 1675var _worker_options = __w_pdfjs_require__(12); 1676 1677var _is_node = __w_pdfjs_require__(4); 1678 1679var _message_handler = __w_pdfjs_require__(13); 1680 1681var _metadata = __w_pdfjs_require__(14); 1682 1683var _optional_content_config = __w_pdfjs_require__(15); 1684 1685var _transport_stream = __w_pdfjs_require__(16); 1686 1687const DEFAULT_RANGE_CHUNK_SIZE = 65536; 1688const RENDERING_CANCELLED_TIMEOUT = 100; 1689const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory; 1690exports.DefaultCanvasFactory = DefaultCanvasFactory; 1691const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory; 1692exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory; 1693const DefaultStandardFontDataFactory = _is_node.isNodeJS ? _node_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory; 1694exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory; 1695let createPDFNetworkStream; 1696 1697function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) { 1698 createPDFNetworkStream = pdfNetworkStreamFactory; 1699} 1700 1701function getDocument(src) { 1702 const task = new PDFDocumentLoadingTask(); 1703 let source; 1704 1705 if (typeof src === "string" || src instanceof URL) { 1706 source = { 1707 url: src 1708 }; 1709 } else if ((0, _util.isArrayBuffer)(src)) { 1710 source = { 1711 data: src 1712 }; 1713 } else if (src instanceof PDFDataRangeTransport) { 1714 source = { 1715 range: src 1716 }; 1717 } else { 1718 if (typeof src !== "object") { 1719 throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object."); 1720 } 1721 1722 if (!src.url && !src.data && !src.range) { 1723 throw new Error("Invalid parameter object: need either .data, .range or .url"); 1724 } 1725 1726 source = src; 1727 } 1728 1729 const params = Object.create(null); 1730 let rangeTransport = null, 1731 worker = null; 1732 1733 for (const key in source) { 1734 const value = source[key]; 1735 1736 switch (key) { 1737 case "url": 1738 if (typeof window !== "undefined") { 1739 try { 1740 params[key] = new URL(value, window.location).href; 1741 continue; 1742 } catch (ex) { 1743 (0, _util.warn)(`Cannot create valid URL: "${ex}".`); 1744 } 1745 } else if (typeof value === "string" || value instanceof URL) { 1746 params[key] = value.toString(); 1747 continue; 1748 } 1749 1750 throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property."); 1751 1752 case "range": 1753 rangeTransport = value; 1754 continue; 1755 1756 case "worker": 1757 worker = value; 1758 continue; 1759 1760 case "data": 1761 if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) { 1762 params[key] = new Uint8Array(value); 1763 } else if (value instanceof Uint8Array) { 1764 break; 1765 } else if (typeof value === "string") { 1766 params[key] = (0, _util.stringToBytes)(value); 1767 } else if (typeof value === "object" && value !== null && !isNaN(value.length)) { 1768 params[key] = new Uint8Array(value); 1769 } else if ((0, _util.isArrayBuffer)(value)) { 1770 params[key] = new Uint8Array(value); 1771 } else { 1772 throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property."); 1773 } 1774 1775 continue; 1776 } 1777 1778 params[key] = value; 1779 } 1780 1781 params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; 1782 params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory; 1783 params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory; 1784 params.ignoreErrors = params.stopAtErrors !== true; 1785 params.fontExtraProperties = params.fontExtraProperties === true; 1786 params.pdfBug = params.pdfBug === true; 1787 params.enableXfa = params.enableXfa === true; 1788 1789 if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) { 1790 params.docBaseUrl = null; 1791 } 1792 1793 if (!Number.isInteger(params.maxImageSize)) { 1794 params.maxImageSize = -1; 1795 } 1796 1797 if (typeof params.useWorkerFetch !== "boolean") { 1798 params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory; 1799 } 1800 1801 if (typeof params.isEvalSupported !== "boolean") { 1802 params.isEvalSupported = true; 1803 } 1804 1805 if (typeof params.disableFontFace !== "boolean") { 1806 params.disableFontFace = _is_node.isNodeJS; 1807 } 1808 1809 if (typeof params.useSystemFonts !== "boolean") { 1810 params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace; 1811 } 1812 1813 if (typeof params.ownerDocument === "undefined") { 1814 params.ownerDocument = globalThis.document; 1815 } 1816 1817 if (typeof params.disableRange !== "boolean") { 1818 params.disableRange = false;
1819 } 1820 1821 if (typeof params.disableStream !== "boolean") { 1822 params.disableStream = false; 1823 } 1824 1825 if (typeof params.disableAutoFetch !== "boolean") { 1826 params.disableAutoFetch = false; 1827 } 1828 1829 (0, _util.setVerbosityLevel)(params.verbosity); 1830 1831 if (!worker) { 1832 const workerParams = { 1833 verbosity: params.verbosity, 1834 port: _worker_options.GlobalWorkerOptions.workerPort 1835 }; 1836 worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams); 1837 task._worker = worker; 1838 } 1839 1840 const docId = task.docId; 1841 worker.promise.then(function () { 1842 if (task.destroyed) { 1843 throw new Error("Loading aborted"); 1844 } 1845 1846 const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId); 1847 1848 const networkStreamPromise = new Promise(function (resolve) { 1849 let networkStream; 1850 1851 if (rangeTransport) { 1852 networkStream = new _transport_stream.PDFDataTransportStream({ 1853 length: params.length, 1854 initialData: params.initialData, 1855 progressiveDone: params.progressiveDone, 1856 contentDispositionFilename: params.contentDispositionFilename, 1857 disableRange: params.disableRange, 1858 disableStream: params.disableStream 1859 }, rangeTransport); 1860 } else if (!params.data) { 1861 networkStream = createPDFNetworkStream({ 1862 url: params.url, 1863 length: params.length, 1864 httpHeaders: params.httpHeaders, 1865 withCredentials: params.withCredentials, 1866 rangeChunkSize: params.rangeChunkSize, 1867 disableRange: params.disableRange, 1868 disableStream: params.disableStream 1869 }); 1870 } 1871 1872 resolve(networkStream); 1873 }); 1874 return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) { 1875 if (task.destroyed) { 1876 throw new Error("Loading aborted"); 1877 } 1878 1879 const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port); 1880 messageHandler.postMessageTransfers = worker.postMessageTransfers; 1881 const transport = new WorkerTransport(messageHandler, task, networkStream, params); 1882 task._transport = transport; 1883 messageHandler.send("Ready", null); 1884 }); 1885 }).catch(task._capability.reject); 1886 return task; 1887} 1888 1889function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { 1890 if (worker.destroyed) { 1891 return Promise.reject(new Error("Worker was destroyed")); 1892 } 1893 1894 if (pdfDataRangeTransport) { 1895 source.length = pdfDataRangeTransport.length; 1896 source.initialData = pdfDataRangeTransport.initialData; 1897 source.progressiveDone = pdfDataRangeTransport.progressiveDone; 1898 source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename; 1899 } 1900 1901 return worker.messageHandler.sendWithPromise("GetDocRequest", { 1902 docId, 1903 apiVersion: '2.10.377', 1904 source: { 1905 data: source.data, 1906 url: source.url, 1907 password: source.password, 1908 disableAutoFetch: source.disableAutoFetch, 1909 rangeChunkSize: source.rangeChunkSize, 1910 length: source.length 1911 }, 1912 maxImageSize: source.maxImageSize, 1913 disableFontFace: source.disableFontFace, 1914 postMessageTransfers: worker.postMessageTransfers, 1915 docBaseUrl: source.docBaseUrl, 1916 ignoreErrors: source.ignoreErrors, 1917 isEvalSupported: source.isEvalSupported, 1918 fontExtraProperties: source.fontExtraProperties, 1919 enableXfa: source.enableXfa, 1920 useSystemFonts: source.useSystemFonts, 1921 cMapUrl: source.useWorkerFetch ? source.cMapUrl : null, 1922 standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null 1923 }).then(function (workerId) { 1924 if (worker.destroyed) { 1925 throw new Error("Worker was destroyed"); 1926 } 1927 1928 return workerId; 1929 }); 1930} 1931 1932const PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() { 1933 let nextDocumentId = 0; 1934 1935 class PDFDocumentLoadingTask { 1936 constructor() { 1937 this._capability = (0, _util.createPromiseCapability)(); 1938 this._transport = null; 1939 this._worker = null; 1940 this.docId = "d" + nextDocumentId++; 1941 this.destroyed = false; 1942 this.onPassword = null; 1943 this.onProgress = null; 1944 this.onUnsupportedFeature = null; 1945 } 1946 1947 get promise() { 1948 return this._capability.promise; 1949 } 1950 1951 destroy() { 1952 this.destroyed = true; 1953 const transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); 1954 return transportDestroyed.then(() => { 1955 this._transport = null; 1956 1957 if (this._worker) { 1958 this._worker.destroy(); 1959 1960 this._worker = null; 1961 } 1962 }); 1963 } 1964 1965 } 1966 1967 return PDFDocumentLoadingTask; 1968}(); 1969 1970class PDFDataRangeTransport { 1971 constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { 1972 this.length = length; 1973 this.initialData = initialData; 1974 this.progressiveDone = progressiveDone; 1975 this.contentDispositionFilename = contentDispositionFilename; 1976 this._rangeListeners = []; 1977 this._progressListeners = []; 1978 this._progressiveReadListeners = []; 1979 this._progressiveDoneListeners = []; 1980 this._readyCapability = (0, _util.createPromiseCapability)(); 1981 } 1982 1983 addRangeListener(listener) { 1984 this._rangeListeners.push(listener); 1985 } 1986 1987 addProgressListener(listener) { 1988 this._progressListeners.push(listener); 1989 } 1990 1991 addProgressiveReadListener(listener) { 1992 this._progressiveReadListeners.push(listener); 1993 } 1994 1995 addProgressiveDoneListener(listener) { 1996 this._progressiveDoneListeners.push(listener); 1997 } 1998 1999 onDataRange(begin, chunk) { 2000 for (const listener of this._rangeListeners) { 2001 listener(begin, chunk); 2002 } 2003 } 2004 2005 onDataProgress(loaded, total) { 2006 this._readyCapability.promise.then(() => { 2007 for (const listener of this._progressListeners) { 2008 listener(loaded, total); 2009 } 2010 }); 2011 } 2012 2013 onDataProgressiveRead(chunk) { 2014 this._readyCapability.promise.then(() => { 2015 for (const listener of this._progressiveReadListeners) { 2016 listener(chunk); 2017 } 2018 }); 2019 } 2020 2021 onDataProgressiveDone() { 2022 this._readyCapability.promise.then(() => { 2023 for (const listener of this._progressiveDoneListeners) { 2024 listener(); 2025 } 2026 }); 2027 } 2028 2029 transportReady() { 2030 this._readyCapability.resolve(); 2031 } 2032 2033 requestDataRange(begin, end) { 2034 (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange"); 2035 } 2036 2037 abort() {} 2038 2039} 2040 2041exports.PDFDataRangeTransport = PDFDataRangeTransport; 2042 2043class PDFDocumentProxy { 2044 constructor(pdfInfo, transport) { 2045 this._pdfInfo = pdfInfo; 2046 this._transport = transport; 2047 Object.defineProperty(this, "fingerprint", { 2048 get() { 2049 (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead."); 2050 return this.fingerprints[0]; 2051 } 2052 2053 }); 2054 } 2055 2056 get annotationStorage() { 2057 return this._transport.annotationStorage; 2058 } 2059 2060 get numPages() { 2061 return this._pdfInfo.numPages; 2062 } 2063 2064 get fingerprints() { 2065 return this._pdfInfo.fingerprints; 2066 } 2067 2068 get isPureXfa() { 2069 return !!this._transport._htmlForXfa; 2070 } 2071 2072 get allXfaHtml() { 2073 return this._transport._htmlForXfa; 2074 } 2075 2076 getPage(pageNumber) { 2077 return this._transport.getPage(pageNumber); 2078 } 2079 2080 getPageIndex(ref) { 2081 return this._transport.getPageIndex(ref); 2082 } 2083 2084 getDestinations() { 2085 return this._transport.getDestinations(); 2086 } 2087 2088 getDestination(id) { 2089 return this._transport.getDestination(id); 2090 } 2091 2092 getPageLabels() { 2093 return this._transport.getPageLabels(); 2094 } 2095 2096 getPageLayout() { 2097 return this._transport.getPageLayout(); 2098 } 2099 2100 getPageMode() { 2101 return this._transport.getPageMode(); 2102 } 2103 2104 getViewerPreferences() { 2105 return this._transport.getViewerPreferences(); 2106 } 2107 2108 getOpenAction() { 2109 return this._transport.getOpenAction(); 2110 } 2111 2112 getAttachments() { 2113 return this._transport.getAttachments(); 2114 } 2115 2116 getJavaScript() { 2117 return this._transport.getJavaScript(); 2118 } 2119 2120 getJSActions() { 2121 return this._transport.getDocJSActions(); 2122 } 2123 2124 getOutline() { 2125 return this._transport.getOutline(); 2126 } 2127 2128 getOptionalContentConfig() { 2129 return this._transport.getOptionalContentConfig(); 2130 } 2131 2132 getPermissions() { 2133 return this._transport.getPermissions(); 2134 } 2135 2136 getMetadata() { 2137 return this._transport.getMetadata(); 2138 } 2139 2140 getMarkInfo() { 2141 return this._transport.getMarkInfo(); 2142 } 2143 2144 getData() { 2145 return this._transport.getData(); 2146 } 2147 2148 getDownloadInfo() { 2149 return this._transport.downloadInfoCapability.promise; 2150 } 2151 2152 getStats() { 2153 return this._transport.getStats(); 2154 } 2155 2156 cleanup(keepLoadedFonts = false) { 2157 return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); 2158 } 2159 2160 destroy() { 2161 return this.loadingTask.destroy(); 2162 } 2163 2164 get loadingParams() { 2165 return this._transport.loadingParams; 2166 } 2167 2168 get loadingTask() { 2169 return this._transport.loadingTask; 2170 } 2171 2172 saveDocument() { 2173 if (this._transport.annotationStorage.size <= 0) { 2174 (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead."); 2175 } 2176 2177 return this._transport.saveDocument(); 2178 } 2179 2180 getFieldObjects() { 2181 return this._transport.getFieldObjects(); 2182 } 2183 2184 hasJSActions() { 2185 return this._transport.hasJSActions(); 2186 } 2187 2188 getCalculationOrderIds() { 2189 return this._transport.getCalculationOrderIds(); 2190 } 2191 2192} 2193 2194exports.PDFDocumentProxy = PDFDocumentProxy; 2195 2196class PDFPageProxy { 2197 constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) { 2198 this._pageIndex = pageIndex; 2199 this._pageInfo = pageInfo; 2200 this._ownerDocument = ownerDocument; 2201 this._transport = transport; 2202 this._stats = pdfBug ? new _display_utils.StatTimer() : null; 2203 this._pdfBug = pdfBug; 2204 this.commonObjs = transport.commonObjs; 2205 this.objs = new PDFObjects(); 2206 this.cleanupAfterRender = false;
2207 this.pendingCleanup = false; 2208 this._intentStates = new Map(); 2209 this.destroyed = false; 2210 } 2211 2212 get pageNumber() { 2213 return this._pageIndex + 1; 2214 } 2215 2216 get rotate() { 2217 return this._pageInfo.rotate; 2218 } 2219 2220 get ref() { 2221 return this._pageInfo.ref; 2222 } 2223 2224 get userUnit() { 2225 return this._pageInfo.userUnit; 2226 } 2227 2228 get view() { 2229 return this._pageInfo.view; 2230 } 2231 2232 getViewport({ 2233 scale, 2234 rotation = this.rotate, 2235 offsetX = 0, 2236 offsetY = 0, 2237 dontFlip = false 2238 } = {}) { 2239 return new _display_utils.PageViewport({ 2240 viewBox: this.view, 2241 scale, 2242 rotation, 2243 offsetX, 2244 offsetY, 2245 dontFlip 2246 }); 2247 } 2248 2249 getAnnotations({ 2250 intent = null 2251 } = {}) { 2252 const renderingIntent = intent === "display" || intent === "print" ? intent : null; 2253 2254 if (!this._annotationsPromise || this._annotationsIntent !== renderingIntent) { 2255 this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, renderingIntent); 2256 this._annotationsIntent = renderingIntent; 2257 } 2258 2259 return this._annotationsPromise; 2260 } 2261 2262 getJSActions() { 2263 return this._jsActionsPromise || (this._jsActionsPromise = this._transport.getPageJSActions(this._pageIndex)); 2264 } 2265 2266 async getXfa() { 2267 return this._transport._htmlForXfa?.children[this._pageIndex] || null; 2268 } 2269 2270 render({ 2271 canvasContext, 2272 viewport, 2273 intent = "display", 2274 renderInteractiveForms = false, 2275 transform = null, 2276 imageLayer = null, 2277 canvasFactory = null, 2278 background = null, 2279 includeAnnotationStorage = false, 2280 optionalContentConfigPromise = null 2281 }) { 2282 var _intentState; 2283 2284 if (this._stats) { 2285 this._stats.time("Overall"); 2286 } 2287 2288 const renderingIntent = intent === "print" ? "print" : "display"; 2289 this.pendingCleanup = false; 2290 2291 if (!optionalContentConfigPromise) { 2292 optionalContentConfigPromise = this._transport.getOptionalContentConfig(); 2293 } 2294 2295 let intentState = this._intentStates.get(renderingIntent); 2296 2297 if (!intentState) { 2298 intentState = Object.create(null); 2299 2300 this._intentStates.set(renderingIntent, intentState); 2301 } 2302 2303 if (intentState.streamReaderCancelTimeout) { 2304 clearTimeout(intentState.streamReaderCancelTimeout); 2305 intentState.streamReaderCancelTimeout = null; 2306 } 2307 2308 const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({ 2309 ownerDocument: this._ownerDocument 2310 }); 2311 const annotationStorage = includeAnnotationStorage ? this._transport.annotationStorage.serializable : null; 2312 2313 if (!intentState.displayReadyCapability) { 2314 intentState.displayReadyCapability = (0, _util.createPromiseCapability)(); 2315 intentState.operatorList = { 2316 fnArray: [], 2317 argsArray: [], 2318 lastChunk: false 2319 }; 2320 2321 if (this._stats) { 2322 this._stats.time("Page Request"); 2323 } 2324 2325 this._pumpOperatorList({ 2326 pageIndex: this._pageIndex, 2327 intent: renderingIntent, 2328 renderInteractiveForms: renderInteractiveForms === true, 2329 annotationStorage 2330 }); 2331 } 2332 2333 const complete = error => { 2334 intentState.renderTasks.delete(internalRenderTask); 2335 2336 if (this.cleanupAfterRender || renderingIntent === "print") { 2337 this.pendingCleanup = true; 2338 } 2339 2340 this._tryCleanup(); 2341 2342 if (error) { 2343 internalRenderTask.capability.reject(error); 2344 2345 this._abortOperatorList({ 2346 intentState, 2347 reason: error 2348 }); 2349 } else { 2350 internalRenderTask.capability.resolve(); 2351 } 2352 2353 if (this._stats) { 2354 this._stats.timeEnd("Rendering"); 2355 2356 this._stats.timeEnd("Overall"); 2357 } 2358 }; 2359 2360 const internalRenderTask = new InternalRenderTask({ 2361 callback: complete, 2362 params: { 2363 canvasContext, 2364 viewport, 2365 transform, 2366 imageLayer, 2367 background 2368 }, 2369 objs: this.objs, 2370 commonObjs: this.commonObjs, 2371 operatorList: intentState.operatorList, 2372 pageIndex: this._pageIndex, 2373 canvasFactory: canvasFactoryInstance, 2374 useRequestAnimationFrame: renderingIntent !== "print", 2375 pdfBug: this._pdfBug 2376 }); 2377 ((_intentState = intentState).renderTasks || (_intentState.renderTasks = new Set())).add(internalRenderTask); 2378 const renderTask = internalRenderTask.task; 2379 Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { 2380 if (this.pendingCleanup) { 2381 complete(); 2382 return; 2383 } 2384 2385 if (this._stats) {
2386 this._stats.time("Rendering"); 2387 } 2388 2389 internalRenderTask.initializeGraphics({ 2390 transparency, 2391 optionalContentConfig 2392 }); 2393 internalRenderTask.operatorListChanged(); 2394 }).catch(complete); 2395 return renderTask; 2396 } 2397 2398 getOperatorList({ 2399 intent = "display" 2400 } = {}) { 2401 function operatorListChanged() { 2402 if (intentState.operatorList.lastChunk) { 2403 intentState.opListReadCapability.resolve(intentState.operatorList); 2404 intentState.renderTasks.delete(opListTask); 2405 } 2406 } 2407 2408 const renderingIntent = `oplist-${intent === "print" ? "print" : "display"}`; 2409 2410 let intentState = this._intentStates.get(renderingIntent); 2411 2412 if (!intentState) { 2413 intentState = Object.create(null); 2414 2415 this._intentStates.set(renderingIntent, intentState); 2416 } 2417 2418 let opListTask; 2419 2420 if (!intentState.opListReadCapability) { 2421 var _intentState2; 2422 2423 opListTask = Object.create(null); 2424 opListTask.operatorListChanged = operatorListChanged; 2425 intentState.opListReadCapability = (0, _util.createPromiseCapability)(); 2426 ((_intentState2 = intentState).renderTasks || (_intentState2.renderTasks = new Set())).add(opListTask); 2427 intentState.operatorList = { 2428 fnArray: [], 2429 argsArray: [], 2430 lastChunk: false 2431 }; 2432 2433 if (this._stats) { 2434 this._stats.time("Page Request"); 2435 } 2436 2437 this._pumpOperatorList({ 2438 pageIndex: this._pageIndex, 2439 intent: renderingIntent 2440 }); 2441 } 2442 2443 return intentState.opListReadCapability.promise; 2444 } 2445 2446 streamTextContent({ 2447 normalizeWhitespace = false, 2448 disableCombineTextItems = false, 2449 includeMarkedContent = false 2450 } = {}) { 2451 const TEXT_CONTENT_CHUNK_SIZE = 100; 2452 return this._transport.messageHandler.sendWithStream("GetTextContent", { 2453 pageIndex: this._pageIndex, 2454 normalizeWhitespace: normalizeWhitespace === true, 2455 combineTextItems: disableCombineTextItems !== true, 2456 includeMarkedContent: includeMarkedContent === true 2457 }, { 2458 highWaterMark: TEXT_CONTENT_CHUNK_SIZE, 2459 2460 size(textContent) { 2461 return textContent.items.length; 2462 } 2463 2464 }); 2465 } 2466 2467 getTextContent(params = {}) { 2468 const readableStream = this.streamTextContent(params); 2469 return new Promise(function (resolve, reject) { 2470 function pump() { 2471 reader.read().then(function ({ 2472 value, 2473 done 2474 }) { 2475 if (done) { 2476 resolve(textContent); 2477 return; 2478 } 2479 2480 Object.assign(textContent.styles, value.styles); 2481 textContent.items.push(...value.items); 2482 pump(); 2483 }, reject); 2484 } 2485 2486 const reader = readableStream.getReader(); 2487 const textContent = { 2488 items: [], 2489 styles: Object.create(null) 2490 }; 2491 pump(); 2492 }); 2493 } 2494 2495 getStructTree() { 2496 return this._structTreePromise || (this._structTreePromise = this._transport.getStructTree(this._pageIndex)); 2497 } 2498 2499 _destroy() { 2500 this.destroyed = true; 2501 this._transport.pageCache[this._pageIndex] = null; 2502 const waitOn = []; 2503 2504 for (const [intent, intentState] of this._intentStates) { 2505 this._abortOperatorList({ 2506 intentState, 2507 reason: new Error("Page was destroyed."), 2508 force: true 2509 }); 2510 2511 if (intent.startsWith("oplist-")) { 2512 continue; 2513 } 2514 2515 for (const internalRenderTask of intentState.renderTasks) { 2516 waitOn.push(internalRenderTask.completed); 2517 internalRenderTask.cancel(); 2518 } 2519 } 2520 2521 this.objs.clear(); 2522 this._annotationsPromise = null; 2523 this._jsActionsPromise = null; 2524 this._structTreePromise = null; 2525 this.pendingCleanup = false; 2526 return Promise.all(waitOn); 2527 } 2528 2529 cleanup(resetStats = false) { 2530 this.pendingCleanup = true; 2531 return this._tryCleanup(resetStats); 2532 } 2533 2534 _tryCleanup(resetStats = false) { 2535 if (!this.pendingCleanup) { 2536 return false; 2537 } 2538 2539 for (const { 2540 renderTasks, 2541 operatorList 2542 } of this._intentStates.values()) { 2543 if (renderTasks.size > 0 || !operatorList.lastChunk) { 2544 return false;
2545 } 2546 } 2547 2548 this._intentStates.clear(); 2549 2550 this.objs.clear(); 2551 this._annotationsPromise = null; 2552 this._jsActionsPromise = null; 2553 this._structTreePromise = null; 2554 2555 if (resetStats && this._stats) { 2556 this._stats = new _display_utils.StatTimer(); 2557 } 2558 2559 this.pendingCleanup = false; 2560 return true; 2561 } 2562 2563 _startRenderPage(transparency, intent) { 2564 const intentState = this._intentStates.get(intent); 2565 2566 if (!intentState) { 2567 return; 2568 } 2569 2570 if (this._stats) { 2571 this._stats.timeEnd("Page Request"); 2572 } 2573 2574 if (intentState.displayReadyCapability) { 2575 intentState.displayReadyCapability.resolve(transparency); 2576 } 2577 } 2578 2579 _renderPageChunk(operatorListChunk, intentState) { 2580 for (let i = 0, ii = operatorListChunk.length; i < ii; i++) { 2581 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); 2582 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); 2583 } 2584 2585 intentState.operatorList.lastChunk = operatorListChunk.lastChunk; 2586 2587 for (const internalRenderTask of intentState.renderTasks) { 2588 internalRenderTask.operatorListChanged(); 2589 } 2590 2591 if (operatorListChunk.lastChunk) { 2592 this._tryCleanup(); 2593 } 2594 } 2595 2596 _pumpOperatorList(args) { 2597 (0, _util.assert)(args.intent, 'PDFPageProxy._pumpOperatorList: Expected "intent" argument.'); 2598 2599 const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", args); 2600 2601 const reader = readableStream.getReader(); 2602 2603 const intentState = this._intentStates.get(args.intent); 2604 2605 intentState.streamReader = reader; 2606 2607 const pump = () => { 2608 reader.read().then(({ 2609 value, 2610 done 2611 }) => { 2612 if (done) { 2613 intentState.streamReader = null; 2614 return; 2615 } 2616 2617 if (this._transport.destroyed) { 2618 return; 2619 } 2620 2621 this._renderPageChunk(value, intentState); 2622 2623 pump(); 2624 }, reason => { 2625 intentState.streamReader = null; 2626 2627 if (this._transport.destroyed) { 2628 return; 2629 } 2630 2631 if (intentState.operatorList) { 2632 intentState.operatorList.lastChunk = true; 2633 2634 for (const internalRenderTask of intentState.renderTasks) { 2635 internalRenderTask.operatorListChanged(); 2636 } 2637 2638 this._tryCleanup(); 2639 } 2640 2641 if (intentState.displayReadyCapability) { 2642 intentState.displayReadyCapability.reject(reason); 2643 } else if (intentState.opListReadCapability) { 2644 intentState.opListReadCapability.reject(reason); 2645 } else { 2646 throw reason; 2647 } 2648 }); 2649 }; 2650 2651 pump(); 2652 } 2653 2654 _abortOperatorList({ 2655 intentState, 2656 reason, 2657 force = false 2658 }) { 2659 (0, _util.assert)(reason instanceof Error || typeof reason === "object" && reason !== null, 'PDFPageProxy._abortOperatorList: Expected "reason" argument.'); 2660 2661 if (!intentState.streamReader) { 2662 return; 2663 } 2664 2665 if (!force) { 2666 if (intentState.renderTasks.size > 0) { 2667 return; 2668 } 2669 2670 if (reason instanceof _display_utils.RenderingCancelledException) { 2671 intentState.streamReaderCancelTimeout = setTimeout(() => { 2672 this._abortOperatorList({ 2673 intentState, 2674 reason, 2675 force: true 2676 }); 2677 2678 intentState.streamReaderCancelTimeout = null; 2679 }, RENDERING_CANCELLED_TIMEOUT); 2680 return; 2681 } 2682 } 2683 2684 intentState.streamReader.cancel(new _util.AbortException(reason?.message)); 2685 intentState.streamReader = null; 2686 2687 if (this._transport.destroyed) { 2688 return; 2689 } 2690 2691 for (const [intent, curIntentState] of this._intentStates) { 2692 if (curIntentState === intentState) { 2693 this._intentStates.delete(intent); 2694 2695 break; 2696 } 2697 } 2698 2699 this.cleanup(); 2700 } 2701 2702 get stats() { 2703 return this._stats; 2704 } 2705 2706} 2707 2708exports.PDFPageProxy = PDFPageProxy; 2709 2710class LoopbackPort { 2711 constructor() { 2712 this._listeners = []; 2713 this._deferred = Promise.resolve(undefined); 2714 } 2715 2716 postMessage(obj, transfers) { 2717 function cloneValue(value) { 2718 if (typeof value === "function" || typeof value === "symbol" || value instanceof URL) { 2719 throw new Error(`LoopbackPort.postMessage - cannot clone: ${value?.toString()}`); 2720 } 2721 2722 if (typeof value !== "object" || value === null) { 2723 return value; 2724 } 2725 2726 if (cloned.has(value)) { 2727 return cloned.get(value); 2728 } 2729 2730 let buffer, result; 2731 2732 if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) { 2733 if (transfers?.includes(buffer)) { 2734 result = new value.constructor(buffer, value.byteOffset, value.byteLength); 2735 } else { 2736 result = new value.constructor(value); 2737 } 2738 2739 cloned.set(value, result); 2740 return result; 2741 } 2742 2743 if (value instanceof Map) { 2744 result = new Map(); 2745 cloned.set(value, result); 2746 2747 for (const [key, val] of value) { 2748 result.set(key, cloneValue(val)); 2749 } 2750 2751 return result; 2752 } 2753 2754 if (value instanceof Set) { 2755 result = new Set(); 2756 cloned.set(value, result); 2757 2758 for (const val of value) { 2759 result.add(cloneValue(val)); 2760 } 2761 2762 return result; 2763 } 2764 2765 result = Array.isArray(value) ? [] : Object.create(null); 2766 cloned.set(value, result); 2767 2768 for (const i in value) { 2769 let desc, 2770 p = value; 2771 2772 while (!(desc = Object.getOwnPropertyDescriptor(p, i))) { 2773 p = Object.getPrototypeOf(p); 2774 } 2775 2776 if (typeof desc.value === "undefined") { 2777 continue; 2778 } 2779 2780 if (typeof desc.value === "function" && !value.hasOwnProperty?.(i)) { 2781 continue; 2782 } 2783 2784 result[i] = cloneValue(desc.value); 2785 } 2786 2787 return result; 2788 } 2789 2790 const cloned = new WeakMap(); 2791 const event = { 2792 data: cloneValue(obj) 2793 }; 2794 2795 this._deferred.then(() => { 2796 for (const listener of this._listeners) { 2797 listener.call(this, event); 2798 } 2799 }); 2800 } 2801 2802 addEventListener(name, listener) { 2803 this._listeners.push(listener); 2804 } 2805 2806 removeEventListener(name, listener) { 2807 const i = this._listeners.indexOf(listener); 2808 2809 this._listeners.splice(i, 1); 2810 } 2811 2812 terminate() { 2813 this._listeners.length = 0; 2814 } 2815 2816} 2817 2818exports.LoopbackPort = LoopbackPort; 2819 2820const PDFWorker = function PDFWorkerClosure() { 2821 const pdfWorkerPorts = new WeakMap(); 2822 let isWorkerDisabled = false;
2823 let fallbackWorkerSrc; 2824 let nextFakeWorkerId = 0; 2825 let fakeWorkerCapability; 2826 2827 if (_is_node.isNodeJS && typeof require === "function") { 2828 isWorkerDisabled = true; 2829 fallbackWorkerSrc = "./pdf.worker.js"; 2830 } else if (typeof document === "object" && "currentScript" in document) { 2831 const pdfjsFilePath = document.currentScript?.src; 2832 2833 if (pdfjsFilePath) { 2834 fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2"); 2835 } 2836 } 2837 2838 function getWorkerSrc() { 2839 if (_worker_options.GlobalWorkerOptions.workerSrc) { 2840 return _worker_options.GlobalWorkerOptions.workerSrc; 2841 } 2842 2843 if (typeof fallbackWorkerSrc !== "undefined") { 2844 if (!_is_node.isNodeJS) { 2845 (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.'); 2846 } 2847 2848 return fallbackWorkerSrc; 2849 } 2850 2851 throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); 2852 } 2853 2854 function getMainThreadWorkerMessageHandler() { 2855 let mainWorkerMessageHandler; 2856 2857 try { 2858 mainWorkerMessageHandler = globalThis.pdfjsWorker?.WorkerMessageHandler; 2859 } catch (ex) {} 2860 2861 return mainWorkerMessageHandler || null; 2862 } 2863 2864 function setupFakeWorkerGlobal() { 2865 if (fakeWorkerCapability) { 2866 return fakeWorkerCapability.promise; 2867 } 2868 2869 fakeWorkerCapability = (0, _util.createPromiseCapability)(); 2870 2871 const loader = async function () { 2872 const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler(); 2873 2874 if (mainWorkerMessageHandler) { 2875 return mainWorkerMessageHandler; 2876 } 2877 2878 if (_is_node.isNodeJS && typeof require === "function") { 2879 const worker = eval("require")(getWorkerSrc()); 2880 return worker.WorkerMessageHandler; 2881 } 2882 2883 await (0, _display_utils.loadScript)(getWorkerSrc()); 2884 return window.pdfjsWorker.WorkerMessageHandler; 2885 }; 2886 2887 loader().then(fakeWorkerCapability.resolve, fakeWorkerCapability.reject); 2888 return fakeWorkerCapability.promise; 2889 } 2890 2891 function createCDNWrapper(url) { 2892 const wrapper = "importScripts('" + url + "');"; 2893 return URL.createObjectURL(new Blob([wrapper])); 2894 } 2895 2896 class PDFWorker { 2897 constructor({ 2898 name = null, 2899 port = null, 2900 verbosity = (0, _util.getVerbosityLevel)() 2901 } = {}) { 2902 if (port && pdfWorkerPorts.has(port)) { 2903 throw new Error("Cannot use more than one PDFWorker per port"); 2904 } 2905 2906 this.name = name; 2907 this.destroyed = false; 2908 this.postMessageTransfers = true; 2909 this.verbosity = verbosity; 2910 this._readyCapability = (0, _util.createPromiseCapability)(); 2911 this._port = null; 2912 this._webWorker = null; 2913 this._messageHandler = null; 2914 2915 if (port) { 2916 pdfWorkerPorts.set(port, this); 2917 2918 this._initializeFromPort(port); 2919 2920 return; 2921 } 2922 2923 this._initialize(); 2924 } 2925 2926 get promise() { 2927 return this._readyCapability.promise; 2928 } 2929 2930 get port() { 2931 return this._port; 2932 } 2933 2934 get messageHandler() { 2935 return this._messageHandler; 2936 } 2937 2938 _initializeFromPort(port) { 2939 this._port = port; 2940 this._messageHandler = new _message_handler.MessageHandler("main", "worker", port); 2941 2942 this._messageHandler.on("ready", function () {}); 2943 2944 this._readyCapability.resolve(); 2945 } 2946 2947 _initialize() { 2948 if (typeof Worker !== "undefined" && !isWorkerDisabled && !getMainThreadWorkerMessageHandler()) { 2949 let workerSrc = getWorkerSrc(); 2950 2951 try { 2952 if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) { 2953 workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href); 2954 } 2955 2956 const worker = new Worker(workerSrc); 2957 const messageHandler = new _message_handler.MessageHandler("main", "worker", worker); 2958 2959 const terminateEarly = () => { 2960 worker.removeEventListener("error", onWorkerError); 2961 messageHandler.destroy(); 2962 worker.terminate(); 2963 2964 if (this.destroyed) { 2965 this._readyCapability.reject(new Error("Worker was destroyed")); 2966 } else { 2967 this._setupFakeWorker(); 2968 } 2969 }; 2970 2971 const onWorkerError = () => { 2972 if (!this._webWorker) { 2973 terminateEarly(); 2974 } 2975 }; 2976 2977 worker.addEventListener("error", onWorkerError); 2978 messageHandler.on("test", data => { 2979 worker.removeEventListener("error", onWorkerError); 2980 2981 if (this.destroyed) { 2982 terminateEarly(); 2983 return; 2984 } 2985 2986 if (data) { 2987 this._messageHandler = messageHandler; 2988 this._port = worker; 2989 this._webWorker = worker; 2990 2991 if (!data.supportTransfers) { 2992 this.postMessageTransfers = false;
2993 } 2994 2995 this._readyCapability.resolve(); 2996 2997 messageHandler.send("configure", { 2998 verbosity: this.verbosity 2999 }); 3000 } else { 3001 this._setupFakeWorker(); 3002 3003 messageHandler.destroy(); 3004 worker.terminate(); 3005 } 3006 }); 3007 messageHandler.on("ready", data => { 3008 worker.removeEventListener("error", onWorkerError); 3009 3010 if (this.destroyed) { 3011 terminateEarly(); 3012 return; 3013 } 3014 3015 try { 3016 sendTest(); 3017 } catch (e) { 3018 this._setupFakeWorker(); 3019 } 3020 }); 3021 3022 const sendTest = () => { 3023 const testObj = new Uint8Array([this.postMessageTransfers ? 255 : 0]); 3024 3025 try { 3026 messageHandler.send("test", testObj, [testObj.buffer]); 3027 } catch (ex) { 3028 (0, _util.warn)("Cannot use postMessage transfers."); 3029 testObj[0] = 0; 3030 messageHandler.send("test", testObj); 3031 } 3032 }; 3033 3034 sendTest(); 3035 return; 3036 } catch (e) { 3037 (0, _util.info)("The worker has been disabled."); 3038 } 3039 } 3040 3041 this._setupFakeWorker(); 3042 } 3043 3044 _setupFakeWorker() { 3045 if (!isWorkerDisabled) { 3046 (0, _util.warn)("Setting up fake worker."); 3047 isWorkerDisabled = true; 3048 } 3049 3050 setupFakeWorkerGlobal().then(WorkerMessageHandler => { 3051 if (this.destroyed) { 3052 this._readyCapability.reject(new Error("Worker was destroyed")); 3053 3054 return; 3055 } 3056 3057 const port = new LoopbackPort(); 3058 this._port = port; 3059 const id = "fake" + nextFakeWorkerId++; 3060 const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port); 3061 WorkerMessageHandler.setup(workerHandler, port); 3062 const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port); 3063 this._messageHandler = messageHandler; 3064 3065 this._readyCapability.resolve(); 3066 3067 messageHandler.send("configure", { 3068 verbosity: this.verbosity 3069 }); 3070 }).catch(reason => { 3071 this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); 3072 }); 3073 } 3074 3075 destroy() { 3076 this.destroyed = true; 3077 3078 if (this._webWorker) { 3079 this._webWorker.terminate(); 3080 3081 this._webWorker = null; 3082 } 3083 3084 pdfWorkerPorts.delete(this._port); 3085 this._port = null; 3086 3087 if (this._messageHandler) { 3088 this._messageHandler.destroy(); 3089 3090 this._messageHandler = null; 3091 } 3092 } 3093 3094 static fromPort(params) { 3095 if (!params || !params.port) { 3096 throw new Error("PDFWorker.fromPort - invalid method signature."); 3097 } 3098 3099 if (pdfWorkerPorts.has(params.port)) { 3100 return pdfWorkerPorts.get(params.port); 3101 } 3102 3103 return new PDFWorker(params); 3104 } 3105 3106 static getWorkerSrc() { 3107 return getWorkerSrc(); 3108 } 3109 3110 } 3111 3112 return PDFWorker; 3113}(); 3114 3115exports.PDFWorker = PDFWorker; 3116 3117class WorkerTransport { 3118 constructor(messageHandler, loadingTask, networkStream, params) { 3119 this.messageHandler = messageHandler; 3120 this.loadingTask = loadingTask; 3121 this.commonObjs = new PDFObjects(); 3122 this.fontLoader = new _font_loader.FontLoader({ 3123 docId: loadingTask.docId, 3124 onUnsupportedFeature: this._onUnsupportedFeature.bind(this), 3125 ownerDocument: params.ownerDocument, 3126 styleElement: params.styleElement 3127 }); 3128 this._params = params; 3129 3130 if (!params.useWorkerFetch) { 3131 this.CMapReaderFactory = new params.CMapReaderFactory({ 3132 baseUrl: params.cMapUrl, 3133 isCompressed: params.cMapPacked 3134 }); 3135 this.StandardFontDataFactory = new params.StandardFontDataFactory({ 3136 baseUrl: params.standardFontDataUrl 3137 }); 3138 } 3139 3140 this.destroyed = false; 3141 this.destroyCapability = null; 3142 this._passwordCapability = null; 3143 this._networkStream = networkStream; 3144 this._fullReader = null; 3145 this._lastProgress = null; 3146 this.pageCache = []; 3147 this.pagePromises = []; 3148 this.downloadInfoCapability = (0, _util.createPromiseCapability)(); 3149 this.setupMessageHandler(); 3150 } 3151 3152 get annotationStorage() { 3153 return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage()); 3154 } 3155 3156 destroy() { 3157 if (this.destroyCapability) { 3158 return this.destroyCapability.promise; 3159 } 3160 3161 this.destroyed = true; 3162 this.destroyCapability = (0, _util.createPromiseCapability)(); 3163 3164 if (this._passwordCapability) { 3165 this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback")); 3166 } 3167 3168 const waitOn = []; 3169 3170 for (const page of this.pageCache) { 3171 if (page) { 3172 waitOn.push(page._destroy()); 3173 } 3174 } 3175 3176 this.pageCache.length = 0; 3177 this.pagePromises.length = 0; 3178 3179 if (this.hasOwnProperty("annotationStorage")) { 3180 this.annotationStorage.resetModified(); 3181 } 3182
3183 const terminated = this.messageHandler.sendWithPromise("Terminate", null); 3184 waitOn.push(terminated); 3185 Promise.all(waitOn).then(() => { 3186 this.commonObjs.clear(); 3187 this.fontLoader.clear(); 3188 this._hasJSActionsPromise = null; 3189 3190 if (this._networkStream) { 3191 this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated.")); 3192 } 3193 3194 if (this.messageHandler) { 3195 this.messageHandler.destroy(); 3196 this.messageHandler = null; 3197 } 3198 3199 this.destroyCapability.resolve(); 3200 }, this.destroyCapability.reject); 3201 return this.destroyCapability.promise; 3202 } 3203 3204 setupMessageHandler() { 3205 const { 3206 messageHandler, 3207 loadingTask 3208 } = this; 3209 messageHandler.on("GetReader", (data, sink) => { 3210 (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available."); 3211 this._fullReader = this._networkStream.getFullReader(); 3212 3213 this._fullReader.onProgress = evt => { 3214 this._lastProgress = { 3215 loaded: evt.loaded, 3216 total: evt.total 3217 }; 3218 }; 3219 3220 sink.onPull = () => { 3221 this._fullReader.read().then(function ({ 3222 value, 3223 done 3224 }) { 3225 if (done) { 3226 sink.close(); 3227 return; 3228 } 3229 3230 (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer."); 3231 sink.enqueue(new Uint8Array(value), 1, [value]); 3232 }).catch(reason => { 3233 sink.error(reason); 3234 }); 3235 }; 3236 3237 sink.onCancel = reason => { 3238 this._fullReader.cancel(reason); 3239 3240 sink.ready.catch(readyReason => { 3241 if (this.destroyed) { 3242 return; 3243 } 3244 3245 throw readyReason; 3246 }); 3247 }; 3248 }); 3249 messageHandler.on("ReaderHeadersReady", data => { 3250 const headersCapability = (0, _util.createPromiseCapability)(); 3251 const fullReader = this._fullReader; 3252 fullReader.headersReady.then(() => { 3253 if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) { 3254 if (this._lastProgress && loadingTask.onProgress) { 3255 loadingTask.onProgress(this._lastProgress); 3256 } 3257 3258 fullReader.onProgress = evt => { 3259 if (loadingTask.onProgress) { 3260 loadingTask.onProgress({ 3261 loaded: evt.loaded, 3262 total: evt.total 3263 }); 3264 } 3265 }; 3266 } 3267 3268 headersCapability.resolve({ 3269 isStreamingSupported: fullReader.isStreamingSupported, 3270 isRangeSupported: fullReader.isRangeSupported, 3271 contentLength: fullReader.contentLength 3272 }); 3273 }, headersCapability.reject); 3274 return headersCapability.promise; 3275 }); 3276 messageHandler.on("GetRangeReader", (data, sink) => { 3277 (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available."); 3278 3279 const rangeReader = this._networkStream.getRangeReader(data.begin, data.end); 3280 3281 if (!rangeReader) { 3282 sink.close(); 3283 return; 3284 } 3285 3286 sink.onPull = () => { 3287 rangeReader.read().then(function ({ 3288 value, 3289 done 3290 }) { 3291 if (done) { 3292 sink.close(); 3293 return; 3294 } 3295 3296 (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer."); 3297 sink.enqueue(new Uint8Array(value), 1, [value]); 3298 }).catch(reason => { 3299 sink.error(reason); 3300 }); 3301 }; 3302 3303 sink.onCancel = reason => { 3304 rangeReader.cancel(reason); 3305 sink.ready.catch(readyReason => { 3306 if (this.destroyed) { 3307 return; 3308 } 3309 3310 throw readyReason; 3311 }); 3312 }; 3313 }); 3314 messageHandler.on("GetDoc", ({ 3315 pdfInfo 3316 }) => { 3317 this._numPages = pdfInfo.numPages; 3318 this._htmlForXfa = pdfInfo.htmlForXfa; 3319 delete pdfInfo.htmlForXfa; 3320 3321 loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); 3322 }); 3323 messageHandler.on("DocException", function (ex) { 3324 let reason; 3325 3326 switch (ex.name) { 3327 case "PasswordException": 3328 reason = new _util.PasswordException(ex.message, ex.code); 3329 break; 3330 3331 case "InvalidPDFException": 3332 reason = new _util.InvalidPDFException(ex.message); 3333 break; 3334 3335 case "MissingPDFException": 3336 reason = new _util.MissingPDFException(ex.message); 3337 break; 3338 3339 case "UnexpectedResponseException": 3340 reason = new _util.UnexpectedResponseException(ex.message, ex.status); 3341 break; 3342 3343 case "UnknownErrorException": 3344 reason = new _util.UnknownErrorException(ex.message, ex.details); 3345 break; 3346 } 3347 3348 if (!(reason instanceof Error)) { 3349 const msg = "DocException - expected a valid Error."; 3350 (0, _util.warn)(msg); 3351 } 3352 3353 loadingTask._capability.reject(reason); 3354 }); 3355 messageHandler.on("PasswordRequest", exception => { 3356 this._passwordCapability = (0, _util.createPromiseCapability)(); 3357 3358 if (loadingTask.onPassword) { 3359 const updatePassword = password => { 3360 this._passwordCapability.resolve({ 3361 password 3362 }); 3363 }; 3364 3365 try { 3366 loadingTask.onPassword(updatePassword, exception.code); 3367 } catch (ex) { 3368 this._passwordCapability.reject(ex); 3369 } 3370 } else { 3371 this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code)); 3372 } 3373 3374 return this._passwordCapability.promise; 3375 }); 3376 messageHandler.on("DataLoaded", data => { 3377 if (loadingTask.onProgress) { 3378 loadingTask.onProgress({ 3379 loaded: data.length, 3380 total: data.length 3381 }); 3382 } 3383 3384 this.downloadInfoCapability.resolve(data); 3385 }); 3386 messageHandler.on("StartRenderPage", data => { 3387 if (this.destroyed) { 3388 return; 3389 } 3390 3391 const page = this.pageCache[data.pageIndex]; 3392 3393 page._startRenderPage(data.transparency, data.intent); 3394 }); 3395 messageHandler.on("commonobj", data => { 3396 if (this.destroyed) { 3397 return; 3398 } 3399 3400 const [id, type, exportedData] = data; 3401 3402 if (this.commonObjs.has(id)) { 3403 return; 3404 } 3405 3406 switch (type) { 3407 case "Font": 3408 const params = this._params; 3409 3410 if ("error" in exportedData) { 3411 const exportedError = exportedData.error; 3412 (0, _util.warn)(`Error during font loading: ${exportedError}`); 3413 this.commonObjs.resolve(id, exportedError); 3414 break; 3415 } 3416 3417 let fontRegistry = null; 3418 3419 if (params.pdfBug && globalThis.FontInspector?.enabled) { 3420 fontRegistry = { 3421 registerFont(font, url) { 3422 globalThis.FontInspector.fontAdded(font, url); 3423 } 3424 3425 }; 3426 } 3427 3428 const font = new _font_loader.FontFaceObject(exportedData, { 3429 isEvalSupported: params.isEvalSupported, 3430 disableFontFace: params.disableFontFace, 3431 ignoreErrors: params.ignoreErrors, 3432 onUnsupportedFeature: this._onUnsupportedFeature.bind(this), 3433 fontRegistry 3434 });
3435 this.fontLoader.bind(font).catch(reason => { 3436 return messageHandler.sendWithPromise("FontFallback", { 3437 id 3438 }); 3439 }).finally(() => { 3440 if (!params.fontExtraProperties && font.data) { 3441 font.data = null; 3442 } 3443 3444 this.commonObjs.resolve(id, font); 3445 }); 3446 break; 3447 3448 case "FontPath": 3449 case "Image": 3450 this.commonObjs.resolve(id, exportedData); 3451 break; 3452 3453 default: 3454 throw new Error(`Got unknown common object type ${type}`); 3455 } 3456 }); 3457 messageHandler.on("obj", data => { 3458 if (this.destroyed) { 3459 return undefined; 3460 } 3461 3462 const [id, pageIndex, type, imageData] = data; 3463 const pageProxy = this.pageCache[pageIndex]; 3464 3465 if (pageProxy.objs.has(id)) { 3466 return undefined; 3467 } 3468 3469 switch (type) { 3470 case "Image": 3471 pageProxy.objs.resolve(id, imageData); 3472 const MAX_IMAGE_SIZE_TO_STORE = 8000000; 3473 3474 if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) { 3475 pageProxy.cleanupAfterRender = true; 3476 } 3477 3478 break; 3479 3480 case "Pattern": 3481 pageProxy.objs.resolve(id, imageData); 3482 break; 3483 3484 default: 3485 throw new Error(`Got unknown object type ${type}`); 3486 } 3487 3488 return undefined; 3489 }); 3490 messageHandler.on("DocProgress", data => { 3491 if (this.destroyed) { 3492 return; 3493 } 3494 3495 if (loadingTask.onProgress) { 3496 loadingTask.onProgress({ 3497 loaded: data.loaded, 3498 total: data.total 3499 }); 3500 } 3501 }); 3502 messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this)); 3503 messageHandler.on("FetchBuiltInCMap", data => { 3504 if (this.destroyed) { 3505 return Promise.reject(new Error("Worker was destroyed.")); 3506 } 3507 3508 if (!this.CMapReaderFactory) { 3509 return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")); 3510 } 3511 3512 return this.CMapReaderFactory.fetch(data); 3513 }); 3514 messageHandler.on("FetchStandardFontData", data => { 3515 if (this.destroyed) { 3516 return Promise.reject(new Error("Worker was destroyed.")); 3517 } 3518 3519 if (!this.StandardFontDataFactory) { 3520 return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")); 3521 } 3522 3523 return this.StandardFontDataFactory.fetch(data); 3524 }); 3525 } 3526 3527 _onUnsupportedFeature({ 3528 featureId 3529 }) { 3530 if (this.destroyed) { 3531 return; 3532 } 3533 3534 if (this.loadingTask.onUnsupportedFeature) { 3535 this.loadingTask.onUnsupportedFeature(featureId); 3536 } 3537 } 3538 3539 getData() { 3540 return this.messageHandler.sendWithPromise("GetData", null); 3541 } 3542 3543 getPage(pageNumber) { 3544 if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) { 3545 return Promise.reject(new Error("Invalid page request")); 3546 } 3547 3548 const pageIndex = pageNumber - 1; 3549 3550 if (pageIndex in this.pagePromises) { 3551 return this.pagePromises[pageIndex]; 3552 } 3553 3554 const promise = this.messageHandler.sendWithPromise("GetPage", { 3555 pageIndex 3556 }).then(pageInfo => { 3557 if (this.destroyed) { 3558 throw new Error("Transport destroyed"); 3559 } 3560 3561 const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug); 3562 this.pageCache[pageIndex] = page; 3563 return page; 3564 }); 3565 this.pagePromises[pageIndex] = promise; 3566 return promise; 3567 } 3568 3569 getPageIndex(ref) { 3570 return this.messageHandler.sendWithPromise("GetPageIndex", { 3571 ref 3572 }).catch(function (reason) { 3573 return Promise.reject(new Error(reason)); 3574 }); 3575 } 3576 3577 getAnnotations(pageIndex, intent) { 3578 return this.messageHandler.sendWithPromise("GetAnnotations", { 3579 pageIndex, 3580 intent 3581 }); 3582 } 3583 3584 saveDocument() { 3585 return this.messageHandler.sendWithPromise("SaveDocument", { 3586 isPureXfa: !!this._htmlForXfa, 3587 numPages: this._numPages, 3588 annotationStorage: this.annotationStorage.serializable, 3589 filename: this._fullReader?.filename ?? null 3590 }).finally(() => { 3591 this.annotationStorage.resetModified(); 3592 }); 3593 } 3594 3595 getFieldObjects() {
3596 return this.messageHandler.sendWithPromise("GetFieldObjects", null); 3597 } 3598 3599 hasJSActions() { 3600 return this._hasJSActionsPromise || (this._hasJSActionsPromise = this.messageHandler.sendWithPromise("HasJSActions", null)); 3601 } 3602 3603 getCalculationOrderIds() { 3604 return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); 3605 } 3606 3607 getDestinations() { 3608 return this.messageHandler.sendWithPromise("GetDestinations", null); 3609 } 3610 3611 getDestination(id) { 3612 if (typeof id !== "string") { 3613 return Promise.reject(new Error("Invalid destination request.")); 3614 } 3615 3616 return this.messageHandler.sendWithPromise("GetDestination", { 3617 id 3618 }); 3619 } 3620 3621 getPageLabels() { 3622 return this.messageHandler.sendWithPromise("GetPageLabels", null); 3623 } 3624 3625 getPageLayout() { 3626 return this.messageHandler.sendWithPromise("GetPageLayout", null); 3627 } 3628 3629 getPageMode() { 3630 return this.messageHandler.sendWithPromise("GetPageMode", null); 3631 } 3632 3633 getViewerPreferences() { 3634 return this.messageHandler.sendWithPromise("GetViewerPreferences", null); 3635 } 3636 3637 getOpenAction() { 3638 return this.messageHandler.sendWithPromise("GetOpenAction", null); 3639 } 3640 3641 getAttachments() { 3642 return this.messageHandler.sendWithPromise("GetAttachments", null); 3643 } 3644 3645 getJavaScript() { 3646 return this.messageHandler.sendWithPromise("GetJavaScript", null); 3647 } 3648 3649 getDocJSActions() { 3650 return this.messageHandler.sendWithPromise("GetDocJSActions", null); 3651 } 3652 3653 getPageJSActions(pageIndex) { 3654 return this.messageHandler.sendWithPromise("GetPageJSActions", { 3655 pageIndex 3656 }); 3657 } 3658 3659 getStructTree(pageIndex) { 3660 return this.messageHandler.sendWithPromise("GetStructTree", { 3661 pageIndex 3662 }); 3663 } 3664 3665 getOutline() { 3666 return this.messageHandler.sendWithPromise("GetOutline", null); 3667 } 3668 3669 getOptionalContentConfig() { 3670 return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => { 3671 return new _optional_content_config.OptionalContentConfig(results); 3672 }); 3673 } 3674 3675 getPermissions() { 3676 return this.messageHandler.sendWithPromise("GetPermissions", null); 3677 } 3678 3679 getMetadata() { 3680 return this.messageHandler.sendWithPromise("GetMetadata", null).then(results => { 3681 return { 3682 info: results[0], 3683 metadata: results[1] ? new _metadata.Metadata(results[1]) : null, 3684 contentDispositionFilename: this._fullReader?.filename ?? null, 3685 contentLength: this._fullReader?.contentLength ?? null 3686 }; 3687 }); 3688 } 3689 3690 getMarkInfo() { 3691 return this.messageHandler.sendWithPromise("GetMarkInfo", null); 3692 } 3693 3694 getStats() { 3695 return this.messageHandler.sendWithPromise("GetStats", null); 3696 } 3697 3698 async startCleanup(keepLoadedFonts = false) { 3699 await this.messageHandler.sendWithPromise("Cleanup", null); 3700 3701 if (this.destroyed) { 3702 return; 3703 } 3704 3705 for (let i = 0, ii = this.pageCache.length; i < ii; i++) { 3706 const page = this.pageCache[i]; 3707 3708 if (!page) { 3709 continue; 3710 } 3711 3712 const cleanupSuccessful = page.cleanup(); 3713 3714 if (!cleanupSuccessful) { 3715 throw new Error(`startCleanup: Page ${i + 1} is currently rendering.`); 3716 } 3717 } 3718 3719 this.commonObjs.clear(); 3720 3721 if (!keepLoadedFonts) { 3722 this.fontLoader.clear(); 3723 } 3724 3725 this._hasJSActionsPromise = null; 3726 } 3727 3728 get loadingParams() { 3729 const params = this._params; 3730 return (0, _util.shadow)(this, "loadingParams", { 3731 disableAutoFetch: params.disableAutoFetch 3732 }); 3733 } 3734 3735} 3736 3737class PDFObjects { 3738 constructor() { 3739 this._objs = Object.create(null); 3740 } 3741 3742 _ensureObj(objId) { 3743 if (this._objs[objId]) { 3744 return this._objs[objId]; 3745 } 3746 3747 return this._objs[objId] = { 3748 capability: (0, _util.createPromiseCapability)(), 3749 data: null, 3750 resolved: false 3751 }; 3752 } 3753 3754 get(objId, callback = null) { 3755 if (callback) { 3756 this._ensureObj(objId).capability.promise.then(callback); 3757 3758 return null; 3759 } 3760 3761 const obj = this._objs[objId]; 3762 3763 if (!obj || !obj.resolved) { 3764 throw new Error(`Requesting object that isn't resolved yet ${objId}.`); 3765 } 3766 3767 return obj.data; 3768 } 3769
3770 has(objId) { 3771 const obj = this._objs[objId]; 3772 return obj?.resolved || false; 3773 } 3774 3775 resolve(objId, data) { 3776 const obj = this._ensureObj(objId); 3777 3778 obj.resolved = true; 3779 obj.data = data; 3780 obj.capability.resolve(data); 3781 } 3782 3783 clear() { 3784 this._objs = Object.create(null); 3785 } 3786 3787} 3788 3789class RenderTask { 3790 constructor(internalRenderTask) { 3791 this._internalRenderTask = internalRenderTask; 3792 this.onContinue = null; 3793 } 3794 3795 get promise() { 3796 return this._internalRenderTask.capability.promise; 3797 } 3798 3799 cancel() { 3800 this._internalRenderTask.cancel(); 3801 } 3802 3803} 3804 3805const InternalRenderTask = function InternalRenderTaskClosure() { 3806 const canvasInRendering = new WeakSet(); 3807 3808 class InternalRenderTask { 3809 constructor({ 3810 callback, 3811 params, 3812 objs, 3813 commonObjs, 3814 operatorList, 3815 pageIndex, 3816 canvasFactory, 3817 useRequestAnimationFrame = false, 3818 pdfBug = false 3819 }) { 3820 this.callback = callback; 3821 this.params = params; 3822 this.objs = objs; 3823 this.commonObjs = commonObjs; 3824 this.operatorListIdx = null; 3825 this.operatorList = operatorList; 3826 this._pageIndex = pageIndex; 3827 this.canvasFactory = canvasFactory; 3828 this._pdfBug = pdfBug; 3829 this.running = false; 3830 this.graphicsReadyCallback = null; 3831 this.graphicsReady = false; 3832 this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; 3833 this.cancelled = false; 3834 this.capability = (0, _util.createPromiseCapability)(); 3835 this.task = new RenderTask(this); 3836 this._cancelBound = this.cancel.bind(this); 3837 this._continueBound = this._continue.bind(this); 3838 this._scheduleNextBound = this._scheduleNext.bind(this); 3839 this._nextBound = this._next.bind(this); 3840 this._canvas = params.canvasContext.canvas; 3841 } 3842 3843 get completed() { 3844 return this.capability.promise.catch(function () {}); 3845 } 3846 3847 initializeGraphics({ 3848 transparency = false, 3849 optionalContentConfig 3850 }) { 3851 if (this.cancelled) { 3852 return; 3853 } 3854 3855 if (this._canvas) { 3856 if (canvasInRendering.has(this._canvas)) { 3857 throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed."); 3858 } 3859 3860 canvasInRendering.add(this._canvas); 3861 } 3862 3863 if (this._pdfBug && globalThis.StepperManager?.enabled) { 3864 this.stepper = globalThis.StepperManager.create(this._pageIndex); 3865 this.stepper.init(this.operatorList); 3866 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); 3867 } 3868 3869 const { 3870 canvasContext, 3871 viewport, 3872 transform, 3873 imageLayer, 3874 background 3875 } = this.params; 3876 this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig); 3877 this.gfx.beginDrawing({ 3878 transform, 3879 viewport, 3880 transparency, 3881 background 3882 }); 3883 this.operatorListIdx = 0; 3884 this.graphicsReady = true; 3885 3886 if (this.graphicsReadyCallback) { 3887 this.graphicsReadyCallback(); 3888 } 3889 } 3890 3891 cancel(error = null) { 3892 this.running = false; 3893 this.cancelled = true; 3894 3895 if (this.gfx) { 3896 this.gfx.endDrawing(); 3897 } 3898 3899 if (this._canvas) { 3900 canvasInRendering.delete(this._canvas); 3901 } 3902 3903 this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas")); 3904 } 3905 3906 operatorListChanged() { 3907 if (!this.graphicsReady) { 3908 if (!this.graphicsReadyCallback) { 3909 this.graphicsReadyCallback = this._continueBound; 3910 } 3911 3912 return; 3913 } 3914 3915 if (this.stepper) { 3916 this.stepper.updateOperatorList(this.operatorList); 3917 } 3918 3919 if (this.running) { 3920 return; 3921 } 3922 3923 this._continue(); 3924 } 3925 3926 _continue() { 3927 this.running = true; 3928 3929 if (this.cancelled) { 3930 return; 3931 } 3932 3933 if (this.task.onContinue) { 3934 this.task.onContinue(this._scheduleNextBound); 3935 } else { 3936 this._scheduleNext(); 3937 } 3938 } 3939 3940 _scheduleNext() { 3941 if (this._useRequestAnimationFrame) { 3942 window.requestAnimationFrame(() => { 3943 this._nextBound().catch(this._cancelBound); 3944 }); 3945 } else {
3946 Promise.resolve().then(this._nextBound).catch(this._cancelBound); 3947 } 3948 } 3949 3950 async _next() { 3951 if (this.cancelled) { 3952 return; 3953 } 3954 3955 this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); 3956 3957 if (this.operatorListIdx === this.operatorList.argsArray.length) { 3958 this.running = false; 3959 3960 if (this.operatorList.lastChunk) { 3961 this.gfx.endDrawing(); 3962 3963 if (this._canvas) { 3964 canvasInRendering.delete(this._canvas); 3965 } 3966 3967 this.callback(); 3968 } 3969 } 3970 } 3971 3972 } 3973 3974 return InternalRenderTask; 3975}(); 3976 3977const version = '2.10.377'; 3978exports.version = version; 3979const build = '156762c48'; 3980exports.build = build; 3981 3982/***/ }), 3983/* 7 */ 3984/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 3985 3986 3987 3988Object.defineProperty(exports, "__esModule", ({ 3989 value: true 3990})); 3991exports.FontLoader = exports.FontFaceObject = void 0; 3992 3993var _util = __w_pdfjs_require__(2); 3994 3995class BaseFontLoader { 3996 constructor({ 3997 docId, 3998 onUnsupportedFeature, 3999 ownerDocument = globalThis.document, 4000 styleElement = null 4001 }) { 4002 if (this.constructor === BaseFontLoader) { 4003 (0, _util.unreachable)("Cannot initialize BaseFontLoader."); 4004 } 4005 4006 this.docId = docId; 4007 this._onUnsupportedFeature = onUnsupportedFeature; 4008 this._document = ownerDocument; 4009 this.nativeFontFaces = []; 4010 this.styleElement = null; 4011 } 4012 4013 addNativeFontFace(nativeFontFace) { 4014 this.nativeFontFaces.push(nativeFontFace); 4015 4016 this._document.fonts.add(nativeFontFace); 4017 } 4018 4019 insertRule(rule) { 4020 let styleElement = this.styleElement; 4021 4022 if (!styleElement) { 4023 styleElement = this.styleElement = this._document.createElement("style"); 4024 styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`; 4025 4026 this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement); 4027 } 4028 4029 const styleSheet = styleElement.sheet; 4030 styleSheet.insertRule(rule, styleSheet.cssRules.length); 4031 } 4032 4033 clear() { 4034 for (const nativeFontFace of this.nativeFontFaces) { 4035 this._document.fonts.delete(nativeFontFace); 4036 } 4037 4038 this.nativeFontFaces.length = 0; 4039 4040 if (this.styleElement) { 4041 this.styleElement.remove(); 4042 this.styleElement = null; 4043 } 4044 } 4045 4046 async bind(font) { 4047 if (font.attached || font.missingFile) { 4048 return; 4049 } 4050 4051 font.attached = true; 4052 4053 if (this.isFontLoadingAPISupported) { 4054 const nativeFontFace = font.createNativeFontFace(); 4055 4056 if (nativeFontFace) { 4057 this.addNativeFontFace(nativeFontFace); 4058 4059 try { 4060 await nativeFontFace.loaded; 4061 } catch (ex) { 4062 this._onUnsupportedFeature({ 4063 featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative 4064 }); 4065 4066 (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); 4067 font.disableFontFace = true; 4068 throw ex; 4069 } 4070 } 4071 4072 return; 4073 } 4074 4075 const rule = font.createFontFaceRule(); 4076 4077 if (rule) { 4078 this.insertRule(rule); 4079 4080 if (this.isSyncFontLoadingSupported) { 4081 return; 4082 } 4083 4084 await new Promise(resolve => { 4085 const request = this._queueLoadingCallback(resolve); 4086 4087 this._prepareFontLoadEvent([rule], [font], request); 4088 }); 4089 } 4090 } 4091 4092 _queueLoadingCallback(callback) { 4093 (0, _util.unreachable)("Abstract method `_queueLoadingCallback`."); 4094 } 4095 4096 get isFontLoadingAPISupported() { 4097 const hasFonts = !!this._document?.fonts; 4098 return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts); 4099 } 4100 4101 get isSyncFontLoadingSupported() { 4102 (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`."); 4103 } 4104 4105 get _loadTestFont() { 4106 (0, _util.unreachable)("Abstract method `_loadTestFont`."); 4107 } 4108 4109 _prepareFontLoadEvent(rules, fontsToLoad, request) { 4110 (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`."); 4111 } 4112 4113} 4114 4115let FontLoader; 4116exports.FontLoader = FontLoader; 4117{ 4118 exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader { 4119 constructor(params) { 4120 super(params); 4121 this.loadingContext = { 4122 requests: [], 4123 nextRequestId: 0 4124 }; 4125 this.loadTestFontId = 0; 4126 } 4127 4128 get isSyncFontLoadingSupported() { 4129 let supported = false;
4130 4131 if (typeof navigator === "undefined") { 4132 supported = true; 4133 } else { 4134 const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent); 4135 4136 if (m?.[1] >= 14) { 4137 supported = true; 4138 } 4139 } 4140 4141 return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported); 4142 } 4143 4144 _queueLoadingCallback(callback) { 4145 function completeRequest() { 4146 (0, _util.assert)(!request.done, "completeRequest() cannot be called twice."); 4147 request.done = true; 4148 4149 while (context.requests.length > 0 && context.requests[0].done) { 4150 const otherRequest = context.requests.shift(); 4151 setTimeout(otherRequest.callback, 0); 4152 } 4153 } 4154 4155 const context = this.loadingContext; 4156 const request = { 4157 id: `pdfjs-font-loading-${context.nextRequestId++}`, 4158 done: false, 4159 complete: completeRequest, 4160 callback 4161 }; 4162 context.requests.push(request); 4163 return request; 4164 } 4165 4166 get _loadTestFont() { 4167 const getLoadTestFont = function () { 4168 return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="); 4169 }; 4170 4171 return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont()); 4172 } 4173 4174 _prepareFontLoadEvent(rules, fonts, request) { 4175 function int32(data, offset) { 4176 return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff; 4177 } 4178 4179 function spliceString(s, offset, remove, insert) { 4180 const chunk1 = s.substring(0, offset); 4181 const chunk2 = s.substring(offset + remove); 4182 return chunk1 + insert + chunk2; 4183 } 4184 4185 let i, ii; 4186 4187 const canvas = this._document.createElement("canvas"); 4188 4189 canvas.width = 1; 4190 canvas.height = 1; 4191 const ctx = canvas.getContext("2d"); 4192 let called = 0; 4193 4194 function isFontReady(name, callback) { 4195 called++; 4196 4197 if (called > 30) { 4198 (0, _util.warn)("Load test font never loaded."); 4199 callback(); 4200 return; 4201 } 4202 4203 ctx.font = "30px " + name; 4204 ctx.fillText(".", 0, 20); 4205 const imageData = ctx.getImageData(0, 0, 1, 1); 4206 4207 if (imageData.data[3] > 0) { 4208 callback(); 4209 return; 4210 } 4211 4212 setTimeout(isFontReady.bind(null, name, callback)); 4213 } 4214 4215 const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`; 4216 let data = this._loadTestFont; 4217 const COMMENT_OFFSET = 976; 4218 data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); 4219 const CFF_CHECKSUM_OFFSET = 16; 4220 const XXXX_VALUE = 0x58585858; 4221 let checksum = int32(data, CFF_CHECKSUM_OFFSET); 4222 4223 for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { 4224 checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0; 4225 } 4226 4227 if (i < loadTestFontId.length) { 4228 checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0; 4229 } 4230
4231 data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum)); 4232 const url = `url(data:font/opentype;base64,${btoa(data)});`; 4233 const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`; 4234 this.insertRule(rule); 4235 const names = []; 4236 4237 for (const font of fonts) { 4238 names.push(font.loadedName); 4239 } 4240 4241 names.push(loadTestFontId); 4242 4243 const div = this._document.createElement("div"); 4244 4245 div.style.visibility = "hidden"; 4246 div.style.width = div.style.height = "10px"; 4247 div.style.position = "absolute"; 4248 div.style.top = div.style.left = "0px"; 4249 4250 for (const name of names) { 4251 const span = this._document.createElement("span"); 4252 4253 span.textContent = "Hi"; 4254 span.style.fontFamily = name; 4255 div.appendChild(span); 4256 } 4257 4258 this._document.body.appendChild(div); 4259 4260 isFontReady(loadTestFontId, () => { 4261 this._document.body.removeChild(div); 4262 4263 request.complete(); 4264 }); 4265 } 4266 4267 }; 4268} 4269 4270class FontFaceObject { 4271 constructor(translatedData, { 4272 isEvalSupported = true, 4273 disableFontFace = false, 4274 ignoreErrors = false, 4275 onUnsupportedFeature, 4276 fontRegistry = null 4277 }) { 4278 this.compiledGlyphs = Object.create(null); 4279 4280 for (const i in translatedData) { 4281 this[i] = translatedData[i]; 4282 } 4283 4284 this.isEvalSupported = isEvalSupported !== false; 4285 this.disableFontFace = disableFontFace === true; 4286 this.ignoreErrors = ignoreErrors === true; 4287 this._onUnsupportedFeature = onUnsupportedFeature; 4288 this.fontRegistry = fontRegistry; 4289 } 4290 4291 createNativeFontFace() { 4292 if (!this.data || this.disableFontFace) { 4293 return null; 4294 } 4295 4296 let nativeFontFace; 4297 4298 if (!this.cssFontInfo) { 4299 nativeFontFace = new FontFace(this.loadedName, this.data, {}); 4300 } else { 4301 const css = { 4302 weight: this.cssFontInfo.fontWeight 4303 }; 4304 4305 if (this.cssFontInfo.italicAngle) { 4306 css.style = `oblique ${this.cssFontInfo.italicAngle}deg`; 4307 } 4308 4309 nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css); 4310 } 4311 4312 if (this.fontRegistry) { 4313 this.fontRegistry.registerFont(this); 4314 } 4315 4316 return nativeFontFace; 4317 } 4318 4319 createFontFaceRule() { 4320 if (!this.data || this.disableFontFace) { 4321 return null; 4322 } 4323 4324 const data = (0, _util.bytesToString)(this.data); 4325 const url = `url(data:${this.mimetype};base64,${btoa(data)});`; 4326 let rule; 4327 4328 if (!this.cssFontInfo) { 4329 rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`; 4330 } else { 4331 let css = `font-weight: ${this.cssFontInfo.fontWeight};`; 4332 4333 if (this.cssFontInfo.italicAngle) { 4334 css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`; 4335 } 4336 4337 rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`; 4338 } 4339 4340 if (this.fontRegistry) { 4341 this.fontRegistry.registerFont(this, url); 4342 } 4343 4344 return rule; 4345 } 4346 4347 getPathGenerator(objs, character) { 4348 if (this.compiledGlyphs[character] !== undefined) { 4349 return this.compiledGlyphs[character]; 4350 } 4351 4352 let cmds; 4353 4354 try { 4355 cmds = objs.get(this.loadedName + "_path_" + character); 4356 } catch (ex) { 4357 if (!this.ignoreErrors) { 4358 throw ex; 4359 } 4360 4361 this._onUnsupportedFeature({ 4362 featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath 4363 }); 4364 4365 (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`); 4366 return this.compiledGlyphs[character] = function (c, size) {}; 4367 } 4368 4369 if (this.isEvalSupported && _util.IsEvalSupportedCached.value) { 4370 const jsBuf = []; 4371 4372 for (const current of cmds) { 4373 const args = current.args !== undefined ? current.args.join(",") : ""; 4374 jsBuf.push("c.", current.cmd, "(", args, ");\n"); 4375 } 4376 4377 return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join("")); 4378 } 4379 4380 return this.compiledGlyphs[character] = function (c, size) { 4381 for (const current of cmds) { 4382 if (current.cmd === "scale") { 4383 current.args = [size, -size]; 4384 } 4385 4386 c[current.cmd].apply(c, current.args); 4387 } 4388 }; 4389 } 4390 4391} 4392 4393exports.FontFaceObject = FontFaceObject; 4394 4395/***/ }), 4396/* 8 */ 4397/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 4398 4399 4400 4401Object.defineProperty(exports, "__esModule", ({ 4402 value: true 4403}));
4404exports.NodeStandardFontDataFactory = exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0; 4405 4406var _base_factory = __w_pdfjs_require__(5); 4407 4408var _is_node = __w_pdfjs_require__(4); 4409 4410var _util = __w_pdfjs_require__(2); 4411 4412let NodeCanvasFactory = class { 4413 constructor() { 4414 (0, _util.unreachable)("Not implemented: NodeCanvasFactory"); 4415 } 4416 4417}; 4418exports.NodeCanvasFactory = NodeCanvasFactory; 4419let NodeCMapReaderFactory = class { 4420 constructor() { 4421 (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory"); 4422 } 4423 4424}; 4425exports.NodeCMapReaderFactory = NodeCMapReaderFactory; 4426let NodeStandardFontDataFactory = class { 4427 constructor() { 4428 (0, _util.unreachable)("Not implemented: NodeStandardFontDataFactory"); 4429 } 4430 4431}; 4432exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory; 4433 4434if (_is_node.isNodeJS) { 4435 const fetchData = function (url) { 4436 return new Promise((resolve, reject) => { 4437 const fs = require("fs"); 4438 4439 fs.readFile(url, (error, data) => { 4440 if (error || !data) { 4441 reject(new Error(error)); 4442 return; 4443 } 4444 4445 resolve(new Uint8Array(data)); 4446 }); 4447 }); 4448 }; 4449 4450 exports.NodeCanvasFactory = NodeCanvasFactory = class extends _base_factory.BaseCanvasFactory { 4451 _createCanvas(width, height) { 4452 const Canvas = require("canvas"); 4453 4454 return Canvas.createCanvas(width, height); 4455 } 4456 4457 }; 4458 exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _base_factory.BaseCMapReaderFactory { 4459 _fetchData(url, compressionType) { 4460 return fetchData(url).then(data => { 4461 return { 4462 cMapData: data, 4463 compressionType 4464 }; 4465 }); 4466 } 4467 4468 }; 4469 exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory = class extends _base_factory.BaseStandardFontDataFactory { 4470 _fetchData(url) { 4471 return fetchData(url); 4472 } 4473 4474 }; 4475} 4476 4477/***/ }), 4478/* 9 */ 4479/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 4480 4481 4482 4483Object.defineProperty(exports, "__esModule", ({ 4484 value: true 4485})); 4486exports.AnnotationStorage = void 0; 4487 4488var _util = __w_pdfjs_require__(2); 4489 4490class AnnotationStorage { 4491 constructor() { 4492 this._storage = new Map(); 4493 this._modified = false; 4494 this.onSetModified = null; 4495 this.onResetModified = null; 4496 } 4497 4498 getValue(key, defaultValue) { 4499 const obj = this._storage.get(key); 4500 4501 return obj !== undefined ? obj : defaultValue; 4502 } 4503 4504 setValue(key, value) { 4505 const obj = this._storage.get(key); 4506 4507 let modified = false; 4508 4509 if (obj !== undefined) { 4510 for (const [entry, val] of Object.entries(value)) { 4511 if (obj[entry] !== val) { 4512 modified = true; 4513 obj[entry] = val; 4514 } 4515 } 4516 } else { 4517 this._storage.set(key, value); 4518 4519 modified = true; 4520 } 4521 4522 if (modified) { 4523 this._setModified(); 4524 } 4525 } 4526 4527 getAll() { 4528 return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null; 4529 } 4530 4531 get size() { 4532 return this._storage.size; 4533 } 4534 4535 _setModified() { 4536 if (!this._modified) { 4537 this._modified = true; 4538 4539 if (typeof this.onSetModified === "function") { 4540 this.onSetModified(); 4541 } 4542 } 4543 } 4544 4545 resetModified() { 4546 if (this._modified) { 4547 this._modified = false; 4548 4549 if (typeof this.onResetModified === "function") { 4550 this.onResetModified(); 4551 } 4552 } 4553 } 4554 4555 get serializable() { 4556 return this._storage.size > 0 ? this._storage : null; 4557 } 4558 4559} 4560 4561exports.AnnotationStorage = AnnotationStorage; 4562 4563/***/ }), 4564/* 10 */ 4565/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 4566 4567 4568 4569Object.defineProperty(exports, "__esModule", ({ 4570 value: true 4571})); 4572exports.CanvasGraphics = void 0; 4573 4574var _util = __w_pdfjs_require__(2); 4575 4576var _pattern_helper = __w_pdfjs_require__(11); 4577 4578const MIN_FONT_SIZE = 16; 4579const MAX_FONT_SIZE = 100; 4580const MAX_GROUP_SIZE = 4096; 4581const COMPILE_TYPE3_GLYPHS = true; 4582const MAX_SIZE_TO_COMPILE = 1000; 4583const FULL_CHUNK_HEIGHT = 16; 4584const LINEWIDTH_SCALE_FACTOR = 1.000001; 4585 4586function addContextCurrentTransform(ctx) { 4587 if (ctx.mozCurrentTransform) { 4588 return; 4589 } 4590 4591 ctx._originalSave = ctx.save; 4592 ctx._originalRestore = ctx.restore; 4593 ctx._originalRotate = ctx.rotate; 4594 ctx._originalScale = ctx.scale; 4595 ctx._originalTranslate = ctx.translate; 4596 ctx._originalTransform = ctx.transform; 4597 ctx._originalSetTransform = ctx.setTransform; 4598 ctx._originalResetTransform = ctx.resetTransform; 4599 ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; 4600 ctx._transformStack = []; 4601 4602 try { 4603 const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth"); 4604 ctx._setLineWidth = desc.set; 4605 ctx._getLineWidth = desc.get; 4606 Object.defineProperty(ctx, "lineWidth", { 4607 set: function setLineWidth(width) { 4608 this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR); 4609 }, 4610 get: function getLineWidth() { 4611 return this._getLineWidth(); 4612 } 4613 }); 4614 } catch (_) {} 4615 4616 Object.defineProperty(ctx, "mozCurrentTransform", { 4617 get: function getCurrentTransform() { 4618 return this._transformMatrix; 4619 } 4620 }); 4621 Object.defineProperty(ctx, "mozCurrentTransformInverse", { 4622 get: function getCurrentTransformInverse() { 4623 const [a, b, c, d, e, f] = this._transformMatrix; 4624 const ad_bc = a * d - b * c; 4625 const bc_ad = b * c - a * d; 4626 return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc]; 4627 } 4628 }); 4629 4630 ctx.save = function ctxSave() { 4631 const old = this._transformMatrix; 4632 4633 this._transformStack.push(old); 4634 4635 this._transformMatrix = old.slice(0, 6); 4636 4637 this._originalSave(); 4638 }; 4639 4640 ctx.restore = function ctxRestore() { 4641 const prev = this._transformStack.pop(); 4642 4643 if (prev) { 4644 this._transformMatrix = prev; 4645 4646 this._originalRestore(); 4647 } 4648 }; 4649 4650 ctx.translate = function ctxTranslate(x, y) { 4651 const m = this._transformMatrix; 4652 m[4] = m[0] * x + m[2] * y + m[4]; 4653 m[5] = m[1] * x + m[3] * y + m[5]; 4654 4655 this._originalTranslate(x, y); 4656 }; 4657 4658 ctx.scale = function ctxScale(x, y) { 4659 const m = this._transformMatrix; 4660 m[0] *= x; 4661 m[1] *= x; 4662 m[2] *= y; 4663 m[3] *= y; 4664 4665 this._originalScale(x, y); 4666 }; 4667 4668 ctx.transform = function ctxTransform(a, b, c, d, e, f) { 4669 const m = this._transformMatrix; 4670 this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]]; 4671 4672 ctx._originalTransform(a, b, c, d, e, f); 4673 }; 4674 4675 ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { 4676 this._transformMatrix = [a, b, c, d, e, f]; 4677 4678 ctx._originalSetTransform(a, b, c, d, e, f); 4679 }; 4680 4681 ctx.resetTransform = function ctxResetTransform() { 4682 this._transformMatrix = [1, 0, 0, 1, 0, 0]; 4683 4684 ctx._originalResetTransform(); 4685 }; 4686 4687 ctx.rotate = function ctxRotate(angle) {
4688 const cosValue = Math.cos(angle); 4689 const sinValue = Math.sin(angle); 4690 const m = this._transformMatrix; 4691 this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]]; 4692 4693 this._originalRotate(angle); 4694 }; 4695} 4696 4697class CachedCanvases { 4698 constructor(canvasFactory) { 4699 this.canvasFactory = canvasFactory; 4700 this.cache = Object.create(null); 4701 } 4702 4703 getCanvas(id, width, height, trackTransform) { 4704 let canvasEntry; 4705 4706 if (this.cache[id] !== undefined) { 4707 canvasEntry = this.cache[id]; 4708 this.canvasFactory.reset(canvasEntry, width, height); 4709 canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); 4710 } else { 4711 canvasEntry = this.canvasFactory.create(width, height); 4712 this.cache[id] = canvasEntry; 4713 } 4714 4715 if (trackTransform) { 4716 addContextCurrentTransform(canvasEntry.context); 4717 } 4718 4719 return canvasEntry; 4720 } 4721 4722 clear() { 4723 for (const id in this.cache) { 4724 const canvasEntry = this.cache[id]; 4725 this.canvasFactory.destroy(canvasEntry); 4726 delete this.cache[id]; 4727 } 4728 } 4729 4730} 4731 4732function compileType3Glyph(imgData) { 4733 const POINT_TO_PROCESS_LIMIT = 1000; 4734 const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); 4735 const width = imgData.width, 4736 height = imgData.height, 4737 width1 = width + 1; 4738 let i, ii, j, j0; 4739 const points = new Uint8Array(width1 * (height + 1)); 4740 const lineSize = width + 7 & ~7, 4741 data0 = imgData.data; 4742 const data = new Uint8Array(lineSize * height); 4743 let pos = 0; 4744 4745 for (i = 0, ii = data0.length; i < ii; i++) { 4746 const elem = data0[i]; 4747 let mask = 128; 4748 4749 while (mask > 0) { 4750 data[pos++] = elem & mask ? 0 : 255; 4751 mask >>= 1; 4752 } 4753 } 4754 4755 let count = 0; 4756 pos = 0; 4757 4758 if (data[pos] !== 0) { 4759 points[0] = 1; 4760 ++count; 4761 } 4762 4763 for (j = 1; j < width; j++) { 4764 if (data[pos] !== data[pos + 1]) { 4765 points[j] = data[pos] ? 2 : 1; 4766 ++count; 4767 } 4768 4769 pos++; 4770 } 4771 4772 if (data[pos] !== 0) { 4773 points[j] = 2; 4774 ++count; 4775 } 4776 4777 for (i = 1; i < height; i++) { 4778 pos = i * lineSize; 4779 j0 = i * width1; 4780 4781 if (data[pos - lineSize] !== data[pos]) { 4782 points[j0] = data[pos] ? 1 : 8; 4783 ++count; 4784 } 4785 4786 let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); 4787 4788 for (j = 1; j < width; j++) { 4789 sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); 4790 4791 if (POINT_TYPES[sum]) { 4792 points[j0 + j] = POINT_TYPES[sum]; 4793 ++count; 4794 } 4795 4796 pos++; 4797 } 4798 4799 if (data[pos - lineSize] !== data[pos]) { 4800 points[j0 + j] = data[pos] ? 2 : 4; 4801 ++count; 4802 } 4803 4804 if (count > POINT_TO_PROCESS_LIMIT) { 4805 return null; 4806 } 4807 } 4808 4809 pos = lineSize * (height - 1); 4810 j0 = i * width1; 4811 4812 if (data[pos] !== 0) { 4813 points[j0] = 8; 4814 ++count; 4815 } 4816 4817 for (j = 1; j < width; j++) { 4818 if (data[pos] !== data[pos + 1]) { 4819 points[j0 + j] = data[pos] ? 4 : 8; 4820 ++count; 4821 } 4822 4823 pos++; 4824 } 4825 4826 if (data[pos] !== 0) { 4827 points[j0 + j] = 4; 4828 ++count; 4829 } 4830 4831 if (count > POINT_TO_PROCESS_LIMIT) { 4832 return null; 4833 } 4834 4835 const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); 4836 const outlines = []; 4837 4838 for (i = 0; count && i <= height; i++) { 4839 let p = i * width1; 4840 const end = p + width; 4841 4842 while (p < end && !points[p]) { 4843 p++; 4844 } 4845 4846 if (p === end) { 4847 continue; 4848 } 4849 4850 const coords = [p % width1, i]; 4851 const p0 = p; 4852 let type = points[p]; 4853 4854 do { 4855 const step = steps[type]; 4856 4857 do { 4858 p += step; 4859 } while (!points[p]); 4860 4861 const pp = points[p]; 4862 4863 if (pp !== 5 && pp !== 10) { 4864 type = pp; 4865 points[p] = 0; 4866 } else { 4867 type = pp & 0x33 * type >> 4; 4868 points[p] &= type >> 2 | type << 2; 4869 } 4870 4871 coords.push(p % width1, p / width1 | 0); 4872 4873 if (!points[p]) { 4874 --count; 4875 } 4876 } while (p0 !== p); 4877 4878 outlines.push(coords); 4879 --i; 4880 } 4881 4882 const drawOutline = function (c) { 4883 c.save(); 4884 c.scale(1 / width, -1 / height); 4885 c.translate(0, -height); 4886 c.beginPath(); 4887 4888 for (let k = 0, kk = outlines.length; k < kk; k++) { 4889 const o = outlines[k]; 4890 c.moveTo(o[0], o[1]); 4891 4892 for (let l = 2, ll = o.length; l < ll;
4892 l += 2) { 4893 c.lineTo(o[l], o[l + 1]); 4894 } 4895 } 4896 4897 c.fill(); 4898 c.beginPath(); 4899 c.restore(); 4900 }; 4901 4902 return drawOutline; 4903} 4904 4905class CanvasExtraState { 4906 constructor() { 4907 this.alphaIsShape = false; 4908 this.fontSize = 0; 4909 this.fontSizeScale = 1; 4910 this.textMatrix = _util.IDENTITY_MATRIX; 4911 this.textMatrixScale = 1; 4912 this.fontMatrix = _util.FONT_IDENTITY_MATRIX; 4913 this.leading = 0; 4914 this.x = 0; 4915 this.y = 0; 4916 this.lineX = 0; 4917 this.lineY = 0; 4918 this.charSpacing = 0; 4919 this.wordSpacing = 0; 4920 this.textHScale = 1; 4921 this.textRenderingMode = _util.TextRenderingMode.FILL; 4922 this.textRise = 0; 4923 this.fillColor = "#000000"; 4924 this.strokeColor = "#000000"; 4925 this.patternFill = false; 4926 this.fillAlpha = 1; 4927 this.strokeAlpha = 1; 4928 this.lineWidth = 1; 4929 this.activeSMask = null; 4930 this.resumeSMaskCtx = null; 4931 this.transferMaps = null; 4932 } 4933 4934 clone() { 4935 return Object.create(this); 4936 } 4937 4938 setCurrentPoint(x, y) { 4939 this.x = x; 4940 this.y = y; 4941 } 4942 4943} 4944 4945const CanvasGraphics = function CanvasGraphicsClosure() { 4946 const EXECUTION_TIME = 15; 4947 const EXECUTION_STEPS = 10; 4948 4949 function putBinaryImageData(ctx, imgData, transferMaps = null) { 4950 if (typeof ImageData !== "undefined" && imgData instanceof ImageData) { 4951 ctx.putImageData(imgData, 0, 0); 4952 return; 4953 } 4954 4955 const height = imgData.height, 4956 width = imgData.width; 4957 const partialChunkHeight = height % FULL_CHUNK_HEIGHT; 4958 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; 4959 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; 4960 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); 4961 let srcPos = 0, 4962 destPos; 4963 const src = imgData.data; 4964 const dest = chunkImgData.data; 4965 let i, j, thisChunkHeight, elemsInThisChunk; 4966 let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray; 4967 4968 if (transferMaps) { 4969 switch (transferMaps.length) { 4970 case 1: 4971 transferMapRed = transferMaps[0]; 4972 transferMapGreen = transferMaps[0]; 4973 transferMapBlue = transferMaps[0]; 4974 transferMapGray = transferMaps[0]; 4975 break; 4976 4977 case 4: 4978 transferMapRed = transferMaps[0]; 4979 transferMapGreen = transferMaps[1]; 4980 transferMapBlue = transferMaps[2]; 4981 transferMapGray = transferMaps[3]; 4982 break; 4983 } 4984 } 4985 4986 if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) { 4987 const srcLength = src.byteLength; 4988 const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); 4989 const dest32DataLength = dest32.length; 4990 const fullSrcDiff = width + 7 >> 3; 4991 let white = 0xffffffff; 4992 let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff; 4993 4994 if (transferMapGray) { 4995 if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) { 4996 [white, black] = [black, white]; 4997 } 4998 } 4999 5000 for (i = 0; i < totalChunks; i++) { 5001 thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; 5002 destPos = 0; 5003 5004 for (j = 0; j < thisChunkHeight; j++) { 5005 const srcDiff = srcLength - srcPos; 5006 let k = 0; 5007 const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; 5008 const kEndUnrolled = kEnd & ~7; 5009 let mask = 0; 5010 let srcByte = 0; 5011 5012 for (; k < kEndUnrolled; k += 8) { 5013 srcByte = src[srcPos++]; 5014 dest32[destPos++] = srcByte & 128 ? white : black; 5015 dest32[destPos++] = srcByte & 64 ? white : black; 5016 dest32[destPos++] = srcByte & 32 ? white : black; 5017 dest32[destPos++] = srcByte & 16 ? white : black; 5018 dest32[destPos++] = srcByte & 8 ? white : black; 5019 dest32[destPos++] = srcByte & 4 ? white : black; 5020 dest32[destPos++] = srcByte & 2 ? white : black; 5021 dest32[destPos++] = srcByte & 1 ? white : black; 5022 } 5023 5024 for (; k < kEnd; k++) { 5025 if (mask === 0) { 5026 srcByte = src[srcPos++]; 5027 mask = 128; 5028 } 5029 5030 dest32[destPos++] = srcByte & mask ? white : black; 5031 mask >>= 1; 5032 } 5033 } 5034 5035 while (destPos < dest32DataLength) { 5036 dest32[destPos++] = 0; 5037 } 5038 5039 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); 5040 } 5041 } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) { 5042 const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue); 5043 j = 0; 5044 elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; 5045 5046 for (i = 0; i < fullChunks; i++) { 5047 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); 5048 srcPos += elemsInThisChunk; 5049 5050 if (hasTransferMaps) { 5051 for (let k = 0; k < elemsInThisChunk; k += 4) { 5052 if (transferMapRed) { 5053 dest[k + 0] = transferMapRed[dest[k + 0]]; 5054 } 5055 5056 if (transferMapGreen) { 5057 dest[k + 1] = transferMapGreen[dest[k + 1]]; 5058 } 5059 5060 if (transferMapBlue) { 5061 dest[k + 2] = transferMapBlue[dest[k + 2]]; 5062 } 5063 } 5064 } 5065 5066 ctx.putImageData(chunkImgData, 0, j); 5067 j += FULL_CHUNK_HEIGHT; 5068 } 5069 5070 if (i < totalChunks) { 5071 elemsInThisChunk = width * partialChunkHeight * 4; 5072 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); 5073 5074 if (hasTransferMaps) { 5075 for (let k = 0; k < elemsInThisChunk; k += 4) { 5076 if (transferMapRed) { 5077 dest[k + 0] = transferMapRed[dest[k + 0]]; 5078 } 5079 5080 if (transferMapGreen) { 5081 dest[k + 1] = transferMapGreen[dest[k + 1]]; 5082 } 5083 5084 if (transferMapBlue) { 5085 dest[k + 2] = transferMapBlue[dest[k + 2]]; 5086 } 5087 } 5088 } 5089 5090 ctx.putImageData(chunkImgData, 0, j); 5091 } 5092 } else if (imgData.kind === _util.ImageKind.RGB_24BPP) { 5093 const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue); 5094 thisChunkHeight = FULL_CHUNK_HEIGHT; 5095 elemsInThisChunk = width * thisChunkHeight; 5096 5097 for (i = 0; i < totalChunks; i++) { 5098 if (i >= fullChunks) { 5099 thisChunkHeight = partialChunkHeight; 5100 elemsInThisChunk = width * thisChunkHeight; 5101 } 5102 5103 destPos = 0; 5104
5105 for (j = elemsInThisChunk; j--;) { 5106 dest[destPos++] = src[srcPos++]; 5107 dest[destPos++] = src[srcPos++]; 5108 dest[destPos++] = src[srcPos++]; 5109 dest[destPos++] = 255; 5110 } 5111 5112 if (hasTransferMaps) { 5113 for (let k = 0; k < destPos; k += 4) { 5114 if (transferMapRed) { 5115 dest[k + 0] = transferMapRed[dest[k + 0]]; 5116 } 5117 5118 if (transferMapGreen) { 5119 dest[k + 1] = transferMapGreen[dest[k + 1]]; 5120 } 5121 5122 if (transferMapBlue) { 5123 dest[k + 2] = transferMapBlue[dest[k + 2]]; 5124 } 5125 } 5126 } 5127 5128 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); 5129 } 5130 } else { 5131 throw new Error(`bad image kind: ${imgData.kind}`); 5132 } 5133 } 5134 5135 function putBinaryImageMask(ctx, imgData) { 5136 const height = imgData.height, 5137 width = imgData.width; 5138 const partialChunkHeight = height % FULL_CHUNK_HEIGHT; 5139 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; 5140 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; 5141 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); 5142 let srcPos = 0; 5143 const src = imgData.data; 5144 const dest = chunkImgData.data; 5145 5146 for (let i = 0; i < totalChunks; i++) { 5147 const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; 5148 let destPos = 3; 5149 5150 for (let j = 0; j < thisChunkHeight; j++) { 5151 let elem, 5152 mask = 0; 5153 5154 for (let k = 0; k < width; k++) { 5155 if (!mask) { 5156 elem = src[srcPos++]; 5157 mask = 128; 5158 } 5159 5160 dest[destPos] = elem & mask ? 0 : 255; 5161 destPos += 4; 5162 mask >>= 1; 5163 } 5164 } 5165 5166 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); 5167 } 5168 } 5169 5170 function copyCtxState(sourceCtx, destCtx) { 5171 const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"]; 5172 5173 for (let i = 0, ii = properties.length; i < ii; i++) { 5174 const property = properties[i]; 5175 5176 if (sourceCtx[property] !== undefined) { 5177 destCtx[property] = sourceCtx[property]; 5178 } 5179 } 5180 5181 if (sourceCtx.setLineDash !== undefined) { 5182 destCtx.setLineDash(sourceCtx.getLineDash()); 5183 destCtx.lineDashOffset = sourceCtx.lineDashOffset; 5184 } 5185 } 5186 5187 function resetCtxToDefault(ctx) { 5188 ctx.strokeStyle = "#000000"; 5189 ctx.fillStyle = "#000000"; 5190 ctx.fillRule = "nonzero"; 5191 ctx.globalAlpha = 1; 5192 ctx.lineWidth = 1; 5193 ctx.lineCap = "butt"; 5194 ctx.lineJoin = "miter"; 5195 ctx.miterLimit = 10; 5196 ctx.globalCompositeOperation = "source-over"; 5197 ctx.font = "10px sans-serif"; 5198 5199 if (ctx.setLineDash !== undefined) { 5200 ctx.setLineDash([]); 5201 ctx.lineDashOffset = 0; 5202 } 5203 } 5204 5205 function composeSMaskBackdrop(bytes, r0, g0, b0) { 5206 const length = bytes.length; 5207 5208 for (let i = 3; i < length; i += 4) { 5209 const alpha = bytes[i]; 5210 5211 if (alpha === 0) { 5212 bytes[i - 3] = r0; 5213 bytes[i - 2] = g0; 5214 bytes[i - 1] = b0; 5215 } else if (alpha < 255) { 5216 const alpha_ = 255 - alpha; 5217 bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8; 5218 bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8; 5219 bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8; 5220 } 5221 } 5222 } 5223 5224 function composeSMaskAlpha(maskData, layerData, transferMap) { 5225 const length = maskData.length; 5226 const scale = 1 / 255; 5227 5228 for (let i = 3; i < length; i += 4) { 5229 const alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; 5230 layerData[i] = layerData[i] * alpha * scale | 0; 5231 } 5232 } 5233 5234 function composeSMaskLuminosity(maskData, layerData, transferMap) { 5235 const length = maskData.length; 5236 5237 for (let i = 3; i < length; i += 4) { 5238 const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28; 5239 layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16; 5240 } 5241 } 5242 5243 function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { 5244 const hasBackdrop = !!backdrop; 5245 const r0 = hasBackdrop ? backdrop[0] : 0; 5246 const g0 = hasBackdrop ? backdrop[1] : 0; 5247 const b0 = hasBackdrop ? backdrop[2] : 0;
5248 let composeFn; 5249 5250 if (subtype === "Luminosity") { 5251 composeFn = composeSMaskLuminosity; 5252 } else { 5253 composeFn = composeSMaskAlpha; 5254 } 5255 5256 const PIXELS_TO_PROCESS = 1048576; 5257 const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); 5258 5259 for (let row = 0; row < height; row += chunkSize) { 5260 const chunkHeight = Math.min(chunkSize, height - row); 5261 const maskData = maskCtx.getImageData(0, row, width, chunkHeight); 5262 const layerData = layerCtx.getImageData(0, row, width, chunkHeight); 5263 5264 if (hasBackdrop) { 5265 composeSMaskBackdrop(maskData.data, r0, g0, b0); 5266 } 5267 5268 composeFn(maskData.data, layerData.data, transferMap); 5269 maskCtx.putImageData(layerData, 0, row); 5270 } 5271 } 5272 5273 function composeSMask(ctx, smask, layerCtx) { 5274 const mask = smask.canvas; 5275 const maskCtx = smask.context; 5276 ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); 5277 genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, smask.backdrop, smask.transferMap); 5278 ctx.drawImage(mask, 0, 0); 5279 } 5280 5281 const LINE_CAP_STYLES = ["butt", "round", "square"]; 5282 const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; 5283 const NORMAL_CLIP = {}; 5284 const EO_CLIP = {}; 5285 5286 class CanvasGraphics { 5287 constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig) { 5288 this.ctx = canvasCtx; 5289 this.current = new CanvasExtraState(); 5290 this.stateStack = []; 5291 this.pendingClip = null; 5292 this.pendingEOFill = false; 5293 this.res = null; 5294 this.xobjs = null; 5295 this.commonObjs = commonObjs; 5296 this.objs = objs; 5297 this.canvasFactory = canvasFactory; 5298 this.imageLayer = imageLayer; 5299 this.groupStack = []; 5300 this.processingType3 = null; 5301 this.baseTransform = null; 5302 this.baseTransformStack = []; 5303 this.groupLevel = 0; 5304 this.smaskStack = []; 5305 this.smaskCounter = 0; 5306 this.tempSMask = null; 5307 this.contentVisible = true; 5308 this.markedContentStack = []; 5309 this.optionalContentConfig = optionalContentConfig; 5310 this.cachedCanvases = new CachedCanvases(this.canvasFactory); 5311 this.cachedPatterns = new Map(); 5312 5313 if (canvasCtx) { 5314 addContextCurrentTransform(canvasCtx); 5315 } 5316 5317 this._cachedGetSinglePixelWidth = null; 5318 } 5319 5320 beginDrawing({ 5321 transform, 5322 viewport, 5323 transparency = false, 5324 background = null 5325 }) { 5326 const width = this.ctx.canvas.width; 5327 const height = this.ctx.canvas.height; 5328 this.ctx.save(); 5329 this.ctx.fillStyle = background || "rgb(255, 255, 255)"; 5330 this.ctx.fillRect(0, 0, width, height); 5331 this.ctx.restore(); 5332 5333 if (transparency) { 5334 const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true); 5335 this.compositeCtx = this.ctx; 5336 this.transparentCanvas = transparentCanvas.canvas; 5337 this.ctx = transparentCanvas.context; 5338 this.ctx.save(); 5339 this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); 5340 } 5341 5342 this.ctx.save(); 5343 resetCtxToDefault(this.ctx); 5344 5345 if (transform) { 5346 this.ctx.transform.apply(this.ctx, transform); 5347 } 5348 5349 this.ctx.transform.apply(this.ctx, viewport.transform); 5350 this.baseTransform = this.ctx.mozCurrentTransform.slice(); 5351 this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]); 5352 5353 if (this.imageLayer) { 5354 this.imageLayer.beginLayout(); 5355 } 5356 } 5357 5358 executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) { 5359 const argsArray = operatorList.argsArray; 5360 const fnArray = operatorList.fnArray; 5361 let i = executionStartIdx || 0; 5362 const argsArrayLen = argsArray.length; 5363 5364 if (argsArrayLen === i) { 5365 return i; 5366 } 5367 5368 const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function"; 5369 const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; 5370 let steps = 0; 5371 const commonObjs = this.commonObjs; 5372 const objs = this.objs; 5373 let fnId; 5374 5375 while (true) { 5376 if (stepper !== undefined && i === stepper.nextBreakPoint) { 5377 stepper.breakIt(i, continueCallback); 5378 return i; 5379 } 5380 5381 fnId = fnArray[i]; 5382 5383 if (fnId !== _util.OPS.dependency) { 5384 this[fnId].apply(this, argsArray[i]); 5385 } else { 5386 for (const depObjId of argsArray[i]) { 5387 const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; 5388 5389 if (!objsPool.has(depObjId)) { 5390 objsPool.get(depObjId, continueCallback); 5391 return i; 5392 } 5393 } 5394 } 5395 5396 i++; 5397 5398 if (i === argsArrayLen) { 5399 return i; 5400 } 5401 5402 if (chunkOperations && ++steps > EXECUTION_STEPS) { 5403 if (Date.now() > endTime) { 5404 continueCallback(); 5405 return i; 5406 } 5407 5408 steps = 0; 5409 } 5410 } 5411 } 5412 5413 endDrawing() { 5414 while (this.stateStack.length || this.current.activeSMask !== null) {
5415 this.restore(); 5416 } 5417 5418 this.ctx.restore(); 5419 5420 if (this.transparentCanvas) { 5421 this.ctx = this.compositeCtx; 5422 this.ctx.save(); 5423 this.ctx.setTransform(1, 0, 0, 1, 0, 0); 5424 this.ctx.drawImage(this.transparentCanvas, 0, 0); 5425 this.ctx.restore(); 5426 this.transparentCanvas = null; 5427 } 5428 5429 this.cachedCanvases.clear(); 5430 this.cachedPatterns.clear(); 5431 5432 if (this.imageLayer) { 5433 this.imageLayer.endLayout(); 5434 } 5435 } 5436 5437 _scaleImage(img, inverseTransform) { 5438 const width = img.width; 5439 const height = img.height; 5440 let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); 5441 let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); 5442 let paintWidth = width, 5443 paintHeight = height; 5444 let tmpCanvasId = "prescale1"; 5445 let tmpCanvas, tmpCtx; 5446 5447 while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { 5448 let newWidth = paintWidth, 5449 newHeight = paintHeight; 5450 5451 if (widthScale > 2 && paintWidth > 1) { 5452 newWidth = Math.ceil(paintWidth / 2); 5453 widthScale /= paintWidth / newWidth; 5454 } 5455 5456 if (heightScale > 2 && paintHeight > 1) { 5457 newHeight = Math.ceil(paintHeight / 2); 5458 heightScale /= paintHeight / newHeight; 5459 } 5460 5461 tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); 5462 tmpCtx = tmpCanvas.context; 5463 tmpCtx.clearRect(0, 0, newWidth, newHeight); 5464 tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); 5465 img = tmpCanvas.canvas; 5466 paintWidth = newWidth; 5467 paintHeight = newHeight; 5468 tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; 5469 } 5470 5471 return { 5472 img, 5473 paintWidth, 5474 paintHeight 5475 }; 5476 } 5477 5478 _createMaskCanvas(img) { 5479 const ctx = this.ctx; 5480 const width = img.width, 5481 height = img.height; 5482 const fillColor = this.current.fillColor; 5483 const isPatternFill = this.current.patternFill; 5484 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); 5485 const maskCtx = maskCanvas.context; 5486 putBinaryImageMask(maskCtx, img); 5487 const objToCanvas = ctx.mozCurrentTransform; 5488 5489 let maskToCanvas = _util.Util.transform(objToCanvas, [1 / width, 0, 0, -1 / height, 0, 0]); 5490 5491 maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); 5492 5493 const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas); 5494 5495 const cord2 = _util.Util.applyTransform([width, height], maskToCanvas); 5496 5497 const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]); 5498 5499 const drawnWidth = Math.ceil(rect[2] - rect[0]); 5500 const drawnHeight = Math.ceil(rect[3] - rect[1]); 5501 const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true); 5502 const fillCtx = fillCanvas.context; 5503 const offsetX = Math.min(cord1[0], cord2[0]); 5504 const offsetY = Math.min(cord1[1], cord2[1]); 5505 fillCtx.translate(-offsetX, -offsetY); 5506 fillCtx.transform.apply(fillCtx, maskToCanvas); 5507 5508 const scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse); 5509 5510 fillCtx.drawImage(scaled.img, 0, 0, scaled.img.width, scaled.img.height, 0, 0, width, height); 5511 fillCtx.globalCompositeOperation = "source-in"; 5512 5513 const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]); 5514 5515 fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, false) : fillColor; 5516 fillCtx.fillRect(0, 0, width, height); 5517 return { 5518 canvas: fillCanvas.canvas, 5519 offsetX: Math.round(offsetX), 5520 offsetY: Math.round(offsetY) 5521 }; 5522 } 5523 5524 setLineWidth(width) { 5525 this.current.lineWidth = width; 5526 this.ctx.lineWidth = width; 5527 } 5528 5529 setLineCap(style) { 5530 this.ctx.lineCap = LINE_CAP_STYLES[style]; 5531 } 5532 5533 setLineJoin(style) { 5534 this.ctx.lineJoin = LINE_JOIN_STYLES[style]; 5535 } 5536 5537 setMiterLimit(limit) { 5538 this.ctx.miterLimit = limit; 5539 } 5540 5541 setDash(dashArray, dashPhase) { 5542 const ctx = this.ctx; 5543 5544 if (ctx.setLineDash !== undefined) { 5545 ctx.setLineDash(dashArray); 5546 ctx.lineDashOffset = dashPhase; 5547 } 5548 } 5549
5550 setRenderingIntent(intent) {} 5551 5552 setFlatness(flatness) {} 5553 5554 setGState(states) { 5555 for (let i = 0, ii = states.length; i < ii; i++) { 5556 const state = states[i]; 5557 const key = state[0]; 5558 const value = state[1]; 5559 5560 switch (key) { 5561 case "LW": 5562 this.setLineWidth(value); 5563 break; 5564 5565 case "LC": 5566 this.setLineCap(value); 5567 break; 5568 5569 case "LJ": 5570 this.setLineJoin(value); 5571 break; 5572 5573 case "ML": 5574 this.setMiterLimit(value); 5575 break; 5576 5577 case "D": 5578 this.setDash(value[0], value[1]); 5579 break; 5580 5581 case "RI": 5582 this.setRenderingIntent(value); 5583 break; 5584 5585 case "FL": 5586 this.setFlatness(value); 5587 break; 5588 5589 case "Font": 5590 this.setFont(value[0], value[1]); 5591 break; 5592 5593 case "CA": 5594 this.current.strokeAlpha = state[1]; 5595 break; 5596 5597 case "ca": 5598 this.current.fillAlpha = state[1]; 5599 this.ctx.globalAlpha = state[1]; 5600 break; 5601 5602 case "BM": 5603 this.ctx.globalCompositeOperation = value; 5604 break; 5605 5606 case "SMask": 5607 if (this.current.activeSMask) { 5608 if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) { 5609 this.suspendSMaskGroup(); 5610 } else { 5611 this.endSMaskGroup(); 5612 } 5613 } 5614 5615 this.current.activeSMask = value ? this.tempSMask : null; 5616 5617 if (this.current.activeSMask) { 5618 this.beginSMaskGroup(); 5619 } 5620 5621 this.tempSMask = null; 5622 break; 5623 5624 case "TR": 5625 this.current.transferMaps = value; 5626 } 5627 } 5628 } 5629 5630 beginSMaskGroup() { 5631 const activeSMask = this.current.activeSMask; 5632 const drawnWidth = activeSMask.canvas.width; 5633 const drawnHeight = activeSMask.canvas.height; 5634 const cacheId = "smaskGroupAt" + this.groupLevel; 5635 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true); 5636 const currentCtx = this.ctx; 5637 const currentTransform = currentCtx.mozCurrentTransform; 5638 this.ctx.save(); 5639 const groupCtx = scratchCanvas.context; 5640 groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); 5641 groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); 5642 groupCtx.transform.apply(groupCtx, currentTransform); 5643 activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse; 5644 copyCtxState(currentCtx, groupCtx); 5645 this.ctx = groupCtx; 5646 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); 5647 this.groupStack.push(currentCtx); 5648 this.groupLevel++; 5649 } 5650 5651 suspendSMaskGroup() { 5652 const groupCtx = this.ctx; 5653 this.groupLevel--; 5654 this.ctx = this.groupStack.pop(); 5655 composeSMask(this.ctx, this.current.activeSMask, groupCtx); 5656 this.ctx.restore(); 5657 this.ctx.save(); 5658 copyCtxState(groupCtx, this.ctx); 5659 this.current.resumeSMaskCtx = groupCtx; 5660 5661 const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); 5662 5663 this.ctx.transform.apply(this.ctx, deltaTransform); 5664 groupCtx.save(); 5665 groupCtx.setTransform(1, 0, 0, 1, 0, 0); 5666 groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height); 5667 groupCtx.restore(); 5668 } 5669 5670 resumeSMaskGroup() { 5671 const groupCtx = this.current.resumeSMaskCtx; 5672 const currentCtx = this.ctx; 5673 this.ctx = groupCtx; 5674 this.groupStack.push(currentCtx); 5675 this.groupLevel++; 5676 } 5677 5678 endSMaskGroup() { 5679 const groupCtx = this.ctx; 5680 this.groupLevel--; 5681 this.ctx = this.groupStack.pop(); 5682 composeSMask(this.ctx, this.current.activeSMask, groupCtx); 5683 this.ctx.restore(); 5684 copyCtxState(groupCtx, this.ctx); 5685 5686 const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); 5687 5688 this.ctx.transform.apply(this.ctx, deltaTransform); 5689 } 5690 5691 save() { 5692 this.ctx.save(); 5693 const old = this.current; 5694 this.stateStack.push(old); 5695 this.current = old.clone(); 5696 this.current.resumeSMaskCtx = null; 5697 } 5698
5699 restore() { 5700 if (this.current.resumeSMaskCtx) { 5701 this.resumeSMaskGroup(); 5702 } 5703 5704 if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) { 5705 this.endSMaskGroup(); 5706 } 5707 5708 if (this.stateStack.length !== 0) { 5709 this.current = this.stateStack.pop(); 5710 this.ctx.restore(); 5711 this.pendingClip = null; 5712 this._cachedGetSinglePixelWidth = null; 5713 } else { 5714 this.current.activeSMask = null; 5715 } 5716 } 5717 5718 transform(a, b, c, d, e, f) { 5719 this.ctx.transform(a, b, c, d, e, f); 5720 this._cachedGetSinglePixelWidth = null; 5721 } 5722 5723 constructPath(ops, args) { 5724 const ctx = this.ctx; 5725 const current = this.current; 5726 let x = current.x, 5727 y = current.y; 5728 5729 for (let i = 0, j = 0, ii = ops.length; i < ii; i++) { 5730 switch (ops[i] | 0) { 5731 case _util.OPS.rectangle: 5732 x = args[j++]; 5733 y = args[j++]; 5734 const width = args[j++]; 5735 const height = args[j++]; 5736 const xw = x + width; 5737 const yh = y + height; 5738 ctx.moveTo(x, y); 5739 5740 if (width === 0 || height === 0) { 5741 ctx.lineTo(xw, yh); 5742 } else { 5743 ctx.lineTo(xw, y); 5744 ctx.lineTo(xw, yh); 5745 ctx.lineTo(x, yh); 5746 } 5747 5748 ctx.closePath(); 5749 break; 5750 5751 case _util.OPS.moveTo: 5752 x = args[j++]; 5753 y = args[j++]; 5754 ctx.moveTo(x, y); 5755 break; 5756 5757 case _util.OPS.lineTo: 5758 x = args[j++]; 5759 y = args[j++]; 5760 ctx.lineTo(x, y); 5761 break; 5762 5763 case _util.OPS.curveTo: 5764 x = args[j + 4]; 5765 y = args[j + 5]; 5766 ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); 5767 j += 6; 5768 break; 5769 5770 case _util.OPS.curveTo2: 5771 ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); 5772 x = args[j + 2]; 5773 y = args[j + 3]; 5774 j += 4; 5775 break; 5776 5777 case _util.OPS.curveTo3: 5778 x = args[j + 2]; 5779 y = args[j + 3]; 5780 ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); 5781 j += 4; 5782 break; 5783 5784 case _util.OPS.closePath: 5785 ctx.closePath(); 5786 break; 5787 } 5788 } 5789 5790 current.setCurrentPoint(x, y); 5791 } 5792 5793 closePath() { 5794 this.ctx.closePath(); 5795 } 5796 5797 stroke(consumePath) { 5798 consumePath = typeof consumePath !== "undefined" ? consumePath : true; 5799 const ctx = this.ctx; 5800 const strokeColor = this.current.strokeColor; 5801 ctx.globalAlpha = this.current.strokeAlpha; 5802 5803 if (this.contentVisible) { 5804 if (typeof strokeColor === "object" && strokeColor?.getPattern) { 5805 const lineWidth = this.getSinglePixelWidth(); 5806 ctx.save(); 5807 ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse); 5808 ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth); 5809 ctx.stroke(); 5810 ctx.restore(); 5811 } else { 5812 const lineWidth = this.getSinglePixelWidth(); 5813 5814 if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) { 5815 ctx.save(); 5816 ctx.resetTransform(); 5817 ctx.lineWidth = Math.round(this._combinedScaleFactor); 5818 ctx.stroke(); 5819 ctx.restore(); 5820 } else { 5821 ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth); 5822 ctx.stroke(); 5823 } 5824 } 5825 } 5826 5827 if (consumePath) { 5828 this.consumePath(); 5829 } 5830 5831 ctx.globalAlpha = this.current.fillAlpha; 5832 } 5833 5834 closeStroke() { 5835 this.closePath(); 5836 this.stroke(); 5837 } 5838 5839 fill(consumePath) { 5840 consumePath = typeof consumePath !== "undefined" ? consumePath : true; 5841 const ctx = this.ctx; 5842 const fillColor = this.current.fillColor; 5843 const isPatternFill = this.current.patternFill; 5844 let needRestore = false;
5845 5846 if (isPatternFill) { 5847 ctx.save(); 5848 ctx.fillStyle = fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse); 5849 needRestore = true; 5850 } 5851 5852 if (this.contentVisible) { 5853 if (this.pendingEOFill) { 5854 ctx.fill("evenodd"); 5855 this.pendingEOFill = false; 5856 } else { 5857 ctx.fill(); 5858 } 5859 } 5860 5861 if (needRestore) { 5862 ctx.restore(); 5863 } 5864 5865 if (consumePath) { 5866 this.consumePath(); 5867 } 5868 } 5869 5870 eoFill() { 5871 this.pendingEOFill = true; 5872 this.fill(); 5873 } 5874 5875 fillStroke() { 5876 this.fill(false); 5877 this.stroke(false); 5878 this.consumePath(); 5879 } 5880 5881 eoFillStroke() { 5882 this.pendingEOFill = true; 5883 this.fillStroke(); 5884 } 5885 5886 closeFillStroke() { 5887 this.closePath(); 5888 this.fillStroke(); 5889 } 5890 5891 closeEOFillStroke() { 5892 this.pendingEOFill = true; 5893 this.closePath(); 5894 this.fillStroke(); 5895 } 5896 5897 endPath() { 5898 this.consumePath(); 5899 } 5900 5901 clip() { 5902 this.pendingClip = NORMAL_CLIP; 5903 } 5904 5905 eoClip() { 5906 this.pendingClip = EO_CLIP; 5907 } 5908 5909 beginText() { 5910 this.current.textMatrix = _util.IDENTITY_MATRIX; 5911 this.current.textMatrixScale = 1; 5912 this.current.x = this.current.lineX = 0; 5913 this.current.y = this.current.lineY = 0; 5914 } 5915 5916 endText() { 5917 const paths = this.pendingTextPaths; 5918 const ctx = this.ctx; 5919 5920 if (paths === undefined) { 5921 ctx.beginPath(); 5922 return; 5923 } 5924 5925 ctx.save(); 5926 ctx.beginPath(); 5927 5928 for (let i = 0; i < paths.length; i++) { 5929 const path = paths[i]; 5930 ctx.setTransform.apply(ctx, path.transform); 5931 ctx.translate(path.x, path.y); 5932 path.addToPath(ctx, path.fontSize); 5933 } 5934 5935 ctx.restore(); 5936 ctx.clip(); 5937 ctx.beginPath(); 5938 delete this.pendingTextPaths; 5939 } 5940 5941 setCharSpacing(spacing) { 5942 this.current.charSpacing = spacing; 5943 } 5944 5945 setWordSpacing(spacing) { 5946 this.current.wordSpacing = spacing; 5947 } 5948 5949 setHScale(scale) { 5950 this.current.textHScale = scale / 100; 5951 } 5952 5953 setLeading(leading) { 5954 this.current.leading = -leading; 5955 } 5956 5957 setFont(fontRefName, size) { 5958 const fontObj = this.commonObjs.get(fontRefName); 5959 const current = this.current; 5960 5961 if (!fontObj) { 5962 throw new Error(`Can't find font for ${fontRefName}`); 5963 } 5964 5965 current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX; 5966 5967 if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { 5968 (0, _util.warn)("Invalid font matrix for font " + fontRefName); 5969 } 5970 5971 if (size < 0) { 5972 size = -size; 5973 current.fontDirection = -1; 5974 } else { 5975 current.fontDirection = 1; 5976 } 5977 5978 this.current.font = fontObj; 5979 this.current.fontSize = size; 5980 5981 if (fontObj.isType3Font) { 5982 return; 5983 } 5984 5985 const name = fontObj.loadedName || "sans-serif"; 5986 let bold = "normal"; 5987 5988 if (fontObj.black) { 5989 bold = "900"; 5990 } else if (fontObj.bold) { 5991 bold = "bold"; 5992 } 5993 5994 const italic = fontObj.italic ? "italic" : "normal"; 5995 const typeface = `"${name}", ${fontObj.fallbackName}`; 5996 let browserFontSize = size; 5997 5998 if (size < MIN_FONT_SIZE) { 5999 browserFontSize = MIN_FONT_SIZE; 6000 } else if (size > MAX_FONT_SIZE) { 6001 browserFontSize = MAX_FONT_SIZE; 6002 } 6003 6004 this.current.fontSizeScale = size / browserFontSize; 6005 this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`; 6006 } 6007 6008 setTextRenderingMode(mode) { 6009 this.current.textRenderingMode = mode; 6010 } 6011 6012 setTextRise(rise) { 6013 this.current.textRise = rise; 6014 } 6015 6016 moveText(x, y) { 6017 this.current.x = this.current.lineX += x; 6018 this.current.y = this.current.lineY += y; 6019 } 6020 6021 setLeadingMoveText(x, y) { 6022 this.setLeading(-y); 6023 this.moveText(x, y); 6024 } 6025 6026 setTextMatrix(a, b, c, d, e, f) { 6027 this.current.textMatrix = [a, b, c, d, e, f]; 6028 this.current.textMatrixScale = Math.hypot(a, b); 6029 this.current.x = this.current.lineX = 0; 6030 this.current.y = this.current.lineY = 0; 6031 } 6032 6033 nextLine() { 6034 this.moveText(0, this.current.leading); 6035 } 6036 6037 paintChar(character, x, y, patternTransform, resetLineWidthToOne) { 6038 const ctx = this.ctx; 6039 const current = this.current; 6040 const font = current.font; 6041 const textRenderingMode = current.textRenderingMode; 6042 const fontSize = current.fontSize / current.fontSizeScale; 6043 const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; 6044 const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG); 6045 const patternFill = current.patternFill && !font.missingFile; 6046 let addToPath; 6047 6048 if (font.disableFontFace || isAddToPathSet || patternFill) { 6049 addToPath = font.getPathGenerator(this.commonObjs, character); 6050 } 6051 6052 if (font.disableFontFace || patternFill) { 6053 ctx.save(); 6054 ctx.translate(x, y); 6055 ctx.beginPath(); 6056 addToPath(ctx, fontSize); 6057 6058 if (patternTransform) { 6059 ctx.setTransform.apply(ctx, patternTransform); 6060 } 6061 6062 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { 6063 ctx.fill(); 6064 } 6065 6066 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6067 if (resetLineWidthToOne) { 6068 ctx.resetTransform(); 6069 ctx.lineWidth = Math.round(this._combinedScaleFactor); 6070 } 6071 6072 ctx.stroke(); 6073 } 6074 6075 ctx.restore(); 6076 } else { 6077 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { 6078 ctx.fillText(character, x, y); 6079 } 6080 6081 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { 6082 if (resetLineWidthToOne) { 6083 ctx.save(); 6084 ctx.moveTo(x, y); 6085 ctx.resetTransform(); 6086 ctx.lineWidth = Math.round(this._combinedScaleFactor); 6087 ctx.strokeText(character, 0, 0); 6088 ctx.restore(); 6089 } else { 6090 ctx.strokeText(character, x, y); 6091 } 6092 } 6093 } 6094 6095 if (isAddToPathSet) { 6096 const paths = this.pendingTextPaths || (this.pendingTextPaths = []); 6097 paths.push({ 6098 transform: ctx.mozCurrentTransform, 6099 x, 6100 y, 6101 fontSize, 6102 addToPath 6103 }); 6104 } 6105 } 6106 6107 get isFontSubpixelAAEnabled() { 6108 const { 6109 context: ctx 6110 } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); 6111 ctx.scale(1.5, 1); 6112 ctx.fillText("I", 0, 10); 6113 const data = ctx.getImageData(0, 0, 10, 10).data; 6114 let enabled = false; 6115 6116 for (let i = 3; i < data.length; i += 4) { 6117 if (data[i] > 0 && data[i] < 255) { 6118 enabled = true; 6119 break; 6120 } 6121 } 6122 6123 return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled); 6124 } 6125 6126 showText(glyphs) { 6127 const current = this.current; 6128 const font = current.font; 6129 6130 if (font.isType3Font) { 6131 return this.showType3Text(glyphs); 6132 } 6133 6134 const fontSize = current.fontSize; 6135 6136 if (fontSize === 0) { 6137 return undefined; 6138 } 6139 6140 const ctx = this.ctx; 6141 const fontSizeScale = current.fontSizeScale; 6142 const charSpacing = current.charSpacing; 6143 const wordSpacing = current.wordSpacing; 6144 const fontDirection = current.fontDirection; 6145 const textHScale = current.textHScale * fontDirection; 6146 const glyphsLength = glyphs.length; 6147 const vertical = font.vertical; 6148 const spacingDir = vertical ? 1 : -1; 6149 const defaultVMetrics = font.defaultVMetrics; 6150 const widthAdvanceScale = fontSize * current.fontMatrix[0]; 6151 const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill; 6152 ctx.save(); 6153 let patternTransform; 6154 6155 if (current.patternFill) { 6156 ctx.save(); 6157 const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse); 6158 patternTransform = ctx.mozCurrentTransform; 6159 ctx.restore(); 6160 ctx.fillStyle = pattern; 6161 } 6162 6163 ctx.transform.apply(ctx, current.textMatrix); 6164 ctx.translate(current.x, current.y + current.textRise); 6165 6166 if (fontDirection > 0) { 6167 ctx.scale(textHScale, -1); 6168 } else { 6169 ctx.scale(textHScale, 1); 6170 } 6171 6172 let lineWidth = current.lineWidth; 6173 let resetLineWidthToOne = false;
6174 const scale = current.textMatrixScale; 6175 6176 if (scale === 0 || lineWidth === 0) { 6177 const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; 6178 6179 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { 6180 this._cachedGetSinglePixelWidth = null; 6181 lineWidth = this.getSinglePixelWidth(); 6182 resetLineWidthToOne = lineWidth < 0; 6183 } 6184 } else { 6185 lineWidth /= scale; 6186 } 6187 6188 if (fontSizeScale !== 1.0) { 6189 ctx.scale(fontSizeScale, fontSizeScale); 6190 lineWidth /= fontSizeScale; 6191 } 6192 6193 ctx.lineWidth = lineWidth; 6194 let x = 0, 6195 i; 6196 6197 for (i = 0; i < glyphsLength; ++i) { 6198 const glyph = glyphs[i]; 6199 6200 if ((0, _util.isNum)(glyph)) { 6201 x += spacingDir * glyph * fontSize / 1000; 6202 continue; 6203 } 6204 6205 let restoreNeeded = false; 6206 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; 6207 const character = glyph.fontChar; 6208 const accent = glyph.accent; 6209 let scaledX, scaledY; 6210 let width = glyph.width; 6211 6212 if (vertical) { 6213 const vmetric = glyph.vmetric || defaultVMetrics; 6214 const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; 6215 const vy = vmetric[2] * widthAdvanceScale; 6216 width = vmetric ? -vmetric[0] : width; 6217 scaledX = vx / fontSizeScale; 6218 scaledY = (x + vy) / fontSizeScale; 6219 } else { 6220 scaledX = x / fontSizeScale; 6221 scaledY = 0; 6222 } 6223 6224 if (font.remeasure && width > 0) { 6225 const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; 6226 6227 if (width < measuredWidth && this.isFontSubpixelAAEnabled) { 6228 const characterScaleX = width / measuredWidth; 6229 restoreNeeded = true; 6230 ctx.save(); 6231 ctx.scale(characterScaleX, 1); 6232 scaledX /= characterScaleX; 6233 } else if (width !== measuredWidth) { 6234 scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; 6235 } 6236 } 6237 6238 if (this.contentVisible && (glyph.isInFont || font.missingFile)) { 6239 if (simpleFillText && !accent) { 6240 ctx.fillText(character, scaledX, scaledY); 6241 } else { 6242 this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne); 6243 6244 if (accent) { 6245 const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale; 6246 const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale; 6247 this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne); 6248 } 6249 } 6250 } 6251 6252 let charWidth; 6253 6254 if (vertical) { 6255 charWidth = width * widthAdvanceScale - spacing * fontDirection; 6256 } else { 6257 charWidth = width * widthAdvanceScale + spacing * fontDirection; 6258 } 6259 6260 x += charWidth; 6261 6262 if (restoreNeeded) { 6263 ctx.restore(); 6264 } 6265 } 6266 6267 if (vertical) { 6268 current.y -= x; 6269 } else { 6270 current.x += x * textHScale; 6271 } 6272 6273 ctx.restore(); 6274 return undefined; 6275 } 6276 6277 showType3Text(glyphs) { 6278 const ctx = this.ctx; 6279 const current = this.current; 6280 const font = current.font; 6281 const fontSize = current.fontSize; 6282 const fontDirection = current.fontDirection; 6283 const spacingDir = font.vertical ? 1 : -1; 6284 const charSpacing = current.charSpacing; 6285 const wordSpacing = current.wordSpacing; 6286 const textHScale = current.textHScale * fontDirection; 6287 const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX; 6288 const glyphsLength = glyphs.length; 6289 const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE; 6290 let i, glyph, width, spacingLength; 6291 6292 if (isTextInvisible || fontSize === 0) { 6293 return; 6294 } 6295 6296 this._cachedGetSinglePixelWidth = null; 6297 ctx.save(); 6298 ctx.transform.apply(ctx, current.textMatrix); 6299 ctx.translate(current.x, current.y); 6300 ctx.scale(textHScale, fontDirection); 6301 6302 for (i = 0; i < glyphsLength; ++i) { 6303 glyph = glyphs[i]; 6304
6305 if ((0, _util.isNum)(glyph)) { 6306 spacingLength = spacingDir * glyph * fontSize / 1000; 6307 this.ctx.translate(spacingLength, 0); 6308 current.x += spacingLength * textHScale; 6309 continue; 6310 } 6311 6312 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; 6313 const operatorList = font.charProcOperatorList[glyph.operatorListId]; 6314 6315 if (!operatorList) { 6316 (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`); 6317 continue; 6318 } 6319 6320 if (this.contentVisible) { 6321 this.processingType3 = glyph; 6322 this.save(); 6323 ctx.scale(fontSize, fontSize); 6324 ctx.transform.apply(ctx, fontMatrix); 6325 this.executeOperatorList(operatorList); 6326 this.restore(); 6327 } 6328 6329 const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix); 6330 6331 width = transformed[0] * fontSize + spacing; 6332 ctx.translate(width, 0); 6333 current.x += width * textHScale; 6334 } 6335 6336 ctx.restore(); 6337 this.processingType3 = null; 6338 } 6339 6340 setCharWidth(xWidth, yWidth) {} 6341 6342 setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { 6343 this.ctx.rect(llx, lly, urx - llx, ury - lly); 6344 this.clip(); 6345 this.endPath(); 6346 } 6347 6348 getColorN_Pattern(IR) { 6349 let pattern; 6350 6351 if (IR[0] === "TilingPattern") { 6352 const color = IR[1]; 6353 const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); 6354 const canvasGraphicsFactory = { 6355 createCanvasGraphics: ctx => { 6356 return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory); 6357 } 6358 }; 6359 pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); 6360 } else { 6361 pattern = this._getPattern(IR[1]); 6362 } 6363 6364 return pattern; 6365 } 6366 6367 setStrokeColorN() { 6368 this.current.strokeColor = this.getColorN_Pattern(arguments); 6369 } 6370 6371 setFillColorN() { 6372 this.current.fillColor = this.getColorN_Pattern(arguments); 6373 this.current.patternFill = true; 6374 } 6375 6376 setStrokeRGBColor(r, g, b) { 6377 const color = _util.Util.makeHexColor(r, g, b); 6378 6379 this.ctx.strokeStyle = color; 6380 this.current.strokeColor = color; 6381 } 6382 6383 setFillRGBColor(r, g, b) { 6384 const color = _util.Util.makeHexColor(r, g, b); 6385 6386 this.ctx.fillStyle = color; 6387 this.current.fillColor = color; 6388 this.current.patternFill = false; 6389 } 6390 6391 _getPattern(objId) { 6392 if (this.cachedPatterns.has(objId)) { 6393 return this.cachedPatterns.get(objId); 6394 } 6395 6396 const pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId)); 6397 this.cachedPatterns.set(objId, pattern); 6398 return pattern; 6399 } 6400 6401 shadingFill(objId) { 6402 if (!this.contentVisible) { 6403 return; 6404 } 6405 6406 const ctx = this.ctx; 6407 this.save(); 6408 6409 const pattern = this._getPattern(objId); 6410 6411 ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, true); 6412 const inv = ctx.mozCurrentTransformInverse; 6413 6414 if (inv) { 6415 const canvas = ctx.canvas; 6416 const width = canvas.width; 6417 const height = canvas.height; 6418 6419 const bl = _util.Util.applyTransform([0, 0], inv); 6420 6421 const br = _util.Util.applyTransform([0, height], inv); 6422 6423 const ul = _util.Util.applyTransform([width, 0], inv); 6424 6425 const ur = _util.Util.applyTransform([width, height], inv); 6426 6427 const x0 = Math.min(bl[0], br[0], ul[0], ur[0]); 6428 const y0 = Math.min(bl[1], br[1], ul[1], ur[1]); 6429 const x1 = Math.max(bl[0], br[0], ul[0], ur[0]); 6430 const y1 = Math.max(bl[1], br[1], ul[1], ur[1]); 6431 this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); 6432 } else { 6433 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); 6434 } 6435 6436 this.restore(); 6437 } 6438 6439 beginInlineImage() { 6440 (0, _util.unreachable)("Should not call beginInlineImage"); 6441 } 6442 6443 beginImageData() { 6444 (0, _util.unreachable)("Should not call beginImageData"); 6445 } 6446 6447 paintFormXObjectBegin(matrix, bbox) { 6448 if (!this.contentVisible) { 6449 return; 6450 } 6451 6452 this.save(); 6453 this.baseTransformStack.push(this.baseTransform); 6454 6455 if (Array.isArray(matrix) && matrix.length === 6) { 6456 this.transform.apply(this, matrix); 6457 } 6458 6459 this.baseTransform = this.ctx.mozCurrentTransform; 6460 6461 if (bbox) { 6462 const width = bbox[2] - bbox[0]; 6463 const height = bbox[3] - bbox[1]; 6464 this.ctx.rect(bbox[0], bbox[1], width, height); 6465 this.clip(); 6466 this.endPath(); 6467 } 6468 } 6469 6470 paintFormXObjectEnd() { 6471 if (!this.contentVisible) { 6472 return; 6473 } 6474
6475 this.restore(); 6476 this.baseTransform = this.baseTransformStack.pop(); 6477 } 6478 6479 beginGroup(group) { 6480 if (!this.contentVisible) { 6481 return; 6482 } 6483 6484 this.save(); 6485 const currentCtx = this.ctx; 6486 6487 if (!group.isolated) { 6488 (0, _util.info)("TODO: Support non-isolated groups."); 6489 } 6490 6491 if (group.knockout) { 6492 (0, _util.warn)("Knockout groups not supported."); 6493 } 6494 6495 const currentTransform = currentCtx.mozCurrentTransform; 6496 6497 if (group.matrix) { 6498 currentCtx.transform.apply(currentCtx, group.matrix); 6499 } 6500 6501 if (!group.bbox) { 6502 throw new Error("Bounding box is required."); 6503 } 6504 6505 let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform); 6506 6507 const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; 6508 bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; 6509 const offsetX = Math.floor(bounds[0]); 6510 const offsetY = Math.floor(bounds[1]); 6511 let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); 6512 let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); 6513 let scaleX = 1, 6514 scaleY = 1; 6515 6516 if (drawnWidth > MAX_GROUP_SIZE) { 6517 scaleX = drawnWidth / MAX_GROUP_SIZE; 6518 drawnWidth = MAX_GROUP_SIZE; 6519 } 6520 6521 if (drawnHeight > MAX_GROUP_SIZE) { 6522 scaleY = drawnHeight / MAX_GROUP_SIZE; 6523 drawnHeight = MAX_GROUP_SIZE; 6524 } 6525 6526 let cacheId = "groupAt" + this.groupLevel; 6527 6528 if (group.smask) { 6529 cacheId += "_smask_" + this.smaskCounter++ % 2; 6530 } 6531 6532 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true); 6533 const groupCtx = scratchCanvas.context; 6534 groupCtx.scale(1 / scaleX, 1 / scaleY); 6535 groupCtx.translate(-offsetX, -offsetY); 6536 groupCtx.transform.apply(groupCtx, currentTransform); 6537 6538 if (group.smask) { 6539 this.smaskStack.push({ 6540 canvas: scratchCanvas.canvas, 6541 context: groupCtx, 6542 offsetX, 6543 offsetY, 6544 scaleX, 6545 scaleY, 6546 subtype: group.smask.subtype, 6547 backdrop: group.smask.backdrop, 6548 transferMap: group.smask.transferMap || null, 6549 startTransformInverse: null 6550 }); 6551 } else { 6552 currentCtx.setTransform(1, 0, 0, 1, 0, 0); 6553 currentCtx.translate(offsetX, offsetY); 6554 currentCtx.scale(scaleX, scaleY); 6555 } 6556 6557 copyCtxState(currentCtx, groupCtx); 6558 this.ctx = groupCtx; 6559 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); 6560 this.groupStack.push(currentCtx); 6561 this.groupLevel++; 6562 this.current.activeSMask = null; 6563 } 6564 6565 endGroup(group) { 6566 if (!this.contentVisible) { 6567 return; 6568 } 6569 6570 this.groupLevel--; 6571 const groupCtx = this.ctx; 6572 this.ctx = this.groupStack.pop(); 6573 6574 if (this.ctx.imageSmoothingEnabled !== undefined) { 6575 this.ctx.imageSmoothingEnabled = false; 6576 } else { 6577 this.ctx.mozImageSmoothingEnabled = false; 6578 } 6579 6580 if (group.smask) { 6581 this.tempSMask = this.smaskStack.pop(); 6582 } else { 6583 this.ctx.drawImage(groupCtx.canvas, 0, 0); 6584 } 6585 6586 this.restore(); 6587 } 6588 6589 beginAnnotations() { 6590 this.save(); 6591 6592 if (this.baseTransform) { 6593 this.ctx.setTransform.apply(this.ctx, this.baseTransform); 6594 } 6595 } 6596 6597 endAnnotations() { 6598 this.restore(); 6599 } 6600 6601 beginAnnotation(id, rect, transform, matrix) { 6602 this.save(); 6603 resetCtxToDefault(this.ctx); 6604 this.current = new CanvasExtraState(); 6605 6606 if (Array.isArray(rect) && rect.length === 4) { 6607 const width = rect[2] - rect[0]; 6608 const height = rect[3] - rect[1]; 6609 this.ctx.rect(rect[0], rect[1], width, height); 6610 this.clip(); 6611 this.endPath(); 6612 } 6613 6614 this.transform.apply(this, transform); 6615 this.transform.apply(this, matrix); 6616 } 6617 6618 endAnnotation() { 6619 this.restore(); 6620 } 6621 6622 paintImageMaskXObject(img) { 6623 if (!this.contentVisible) { 6624 return; 6625 } 6626 6627 const ctx = this.ctx; 6628 const width = img.width,
6629 height = img.height; 6630 const glyph = this.processingType3; 6631 6632 if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { 6633 if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { 6634 glyph.compiled = compileType3Glyph({ 6635 data: img.data, 6636 width, 6637 height 6638 }); 6639 } else { 6640 glyph.compiled = null; 6641 } 6642 } 6643 6644 if (glyph?.compiled) { 6645 glyph.compiled(ctx); 6646 return; 6647 } 6648 6649 const mask = this._createMaskCanvas(img); 6650 6651 const maskCanvas = mask.canvas; 6652 ctx.save(); 6653 ctx.setTransform(1, 0, 0, 1, 0, 0); 6654 ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); 6655 ctx.restore(); 6656 } 6657 6658 paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) { 6659 if (!this.contentVisible) { 6660 return; 6661 } 6662 6663 const ctx = this.ctx; 6664 ctx.save(); 6665 const currentTransform = ctx.mozCurrentTransform; 6666 ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); 6667 6668 const mask = this._createMaskCanvas(imgData); 6669 6670 ctx.setTransform(1, 0, 0, 1, 0, 0); 6671 6672 for (let i = 0, ii = positions.length; i < ii; i += 2) { 6673 const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]); 6674 6675 const [x, y] = _util.Util.applyTransform([0, 0], trans); 6676 6677 ctx.drawImage(mask.canvas, x, y); 6678 } 6679 6680 ctx.restore(); 6681 } 6682 6683 paintImageMaskXObjectGroup(images) { 6684 if (!this.contentVisible) { 6685 return; 6686 } 6687 6688 const ctx = this.ctx; 6689 const fillColor = this.current.fillColor; 6690 const isPatternFill = this.current.patternFill; 6691 6692 for (let i = 0, ii = images.length; i < ii; i++) { 6693 const image = images[i]; 6694 const width = image.width, 6695 height = image.height; 6696 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); 6697 const maskCtx = maskCanvas.context; 6698 maskCtx.save(); 6699 putBinaryImageMask(maskCtx, image); 6700 maskCtx.globalCompositeOperation = "source-in"; 6701 maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, false) : fillColor; 6702 maskCtx.fillRect(0, 0, width, height); 6703 maskCtx.restore(); 6704 ctx.save(); 6705 ctx.transform.apply(ctx, image.transform); 6706 ctx.scale(1, -1); 6707 ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); 6708 ctx.restore(); 6709 } 6710 } 6711 6712 paintImageXObject(objId) { 6713 if (!this.contentVisible) { 6714 return; 6715 } 6716 6717 const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId); 6718 6719 if (!imgData) { 6720 (0, _util.warn)("Dependent image isn't ready yet"); 6721 return; 6722 } 6723 6724 this.paintInlineImageXObject(imgData); 6725 } 6726 6727 paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { 6728 if (!this.contentVisible) { 6729 return; 6730 } 6731 6732 const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId); 6733 6734 if (!imgData) { 6735 (0, _util.warn)("Dependent image isn't ready yet"); 6736 return; 6737 } 6738 6739 const width = imgData.width; 6740 const height = imgData.height; 6741 const map = []; 6742 6743 for (let i = 0, ii = positions.length; i < ii; i += 2) { 6744 map.push({ 6745 transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], 6746 x: 0, 6747 y: 0, 6748 w: width, 6749 h: height 6750 }); 6751 } 6752 6753 this.paintInlineImageXObjectGroup(imgData, map); 6754 } 6755 6756 paintInlineImageXObject(imgData) { 6757 if (!this.contentVisible) { 6758 return; 6759 } 6760 6761 const width = imgData.width; 6762 const height = imgData.height; 6763 const ctx = this.ctx; 6764 this.save(); 6765 ctx.scale(1 / width, -1 / height); 6766 let imgToPaint; 6767 6768 if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { 6769 imgToPaint = imgData; 6770 } else { 6771 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); 6772 const tmpCtx = tmpCanvas.context; 6773 putBinaryImageData(tmpCtx, imgData, this.current.transferMaps); 6774 imgToPaint = tmpCanvas.canvas; 6775 } 6776 6777 const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse); 6778 6779 ctx.drawImage(scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); 6780 6781 if (this.imageLayer) { 6782 const position = this.getCanvasPosition(0, -height); 6783 this.imageLayer.appendImage({ 6784 imgData, 6785 left: position[0], 6786 top: position[1], 6787 width: width / ctx.mozCurrentTransformInverse[0], 6788 height: height / ctx.mozCurrentTransformInverse[3] 6789 }); 6790 } 6791
6792 this.restore(); 6793 } 6794 6795 paintInlineImageXObjectGroup(imgData, map) { 6796 if (!this.contentVisible) { 6797 return; 6798 } 6799 6800 const ctx = this.ctx; 6801 const w = imgData.width; 6802 const h = imgData.height; 6803 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h); 6804 const tmpCtx = tmpCanvas.context; 6805 putBinaryImageData(tmpCtx, imgData, this.current.transferMaps); 6806 6807 for (let i = 0, ii = map.length; i < ii; i++) { 6808 const entry = map[i]; 6809 ctx.save(); 6810 ctx.transform.apply(ctx, entry.transform); 6811 ctx.scale(1, -1); 6812 ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); 6813 6814 if (this.imageLayer) { 6815 const position = this.getCanvasPosition(entry.x, entry.y); 6816 this.imageLayer.appendImage({ 6817 imgData, 6818 left: position[0], 6819 top: position[1], 6820 width: w, 6821 height: h 6822 }); 6823 } 6824 6825 ctx.restore(); 6826 } 6827 } 6828 6829 paintSolidColorImageMask() { 6830 if (!this.contentVisible) { 6831 return; 6832 } 6833 6834 this.ctx.fillRect(0, 0, 1, 1); 6835 } 6836 6837 markPoint(tag) {} 6838 6839 markPointProps(tag, properties) {} 6840 6841 beginMarkedContent(tag) { 6842 this.markedContentStack.push({ 6843 visible: true 6844 }); 6845 } 6846 6847 beginMarkedContentProps(tag, properties) { 6848 if (tag === "OC") { 6849 this.markedContentStack.push({ 6850 visible: this.optionalContentConfig.isVisible(properties) 6851 }); 6852 } else { 6853 this.markedContentStack.push({ 6854 visible: true 6855 }); 6856 } 6857 6858 this.contentVisible = this.isContentVisible(); 6859 } 6860 6861 endMarkedContent() { 6862 this.markedContentStack.pop(); 6863 this.contentVisible = this.isContentVisible(); 6864 } 6865 6866 beginCompat() {} 6867 6868 endCompat() {} 6869 6870 consumePath() { 6871 const ctx = this.ctx; 6872 6873 if (this.pendingClip) { 6874 if (this.pendingClip === EO_CLIP) { 6875 ctx.clip("evenodd"); 6876 } else { 6877 ctx.clip(); 6878 } 6879 6880 this.pendingClip = null; 6881 } 6882 6883 ctx.beginPath(); 6884 } 6885 6886 getSinglePixelWidth() { 6887 if (this._cachedGetSinglePixelWidth === null) { 6888 const m = this.ctx.mozCurrentTransform; 6889 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]); 6890 const sqNorm1 = m[0] ** 2 + m[2] ** 2; 6891 const sqNorm2 = m[1] ** 2 + m[3] ** 2; 6892 const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet; 6893 6894 if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) { 6895 this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight); 6896 } else if (absDet > Number.EPSILON) { 6897 this._cachedGetSinglePixelWidth = pixelHeight; 6898 } else { 6899 this._cachedGetSinglePixelWidth = 1; 6900 } 6901 } 6902 6903 return this._cachedGetSinglePixelWidth; 6904 } 6905 6906 getCanvasPosition(x, y) { 6907 const transform = this.ctx.mozCurrentTransform; 6908 return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]]; 6909 } 6910 6911 isContentVisible() { 6912 for (let i = this.markedContentStack.length - 1; i >= 0; i--) { 6913 if (!this.markedContentStack[i].visible) { 6914 return false; 6915 } 6916 } 6917 6918 return true; 6919 } 6920 6921 } 6922 6923 for (const op in _util.OPS) { 6924 CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op]; 6925 } 6926 6927 return CanvasGraphics; 6928}(); 6929 6930exports.CanvasGraphics = CanvasGraphics; 6931 6932/***/ }), 6933/* 11 */ 6934/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 6935 6936 6937 6938Object.defineProperty(exports, "__esModule", ({ 6939 value: true 6940})); 6941exports.getShadingPattern = getShadingPattern; 6942exports.TilingPattern = void 0; 6943 6944var _util = __w_pdfjs_require__(2); 6945 6946function applyBoundingBox(ctx, bbox) { 6947 if (!bbox || typeof Path2D === "undefined") { 6948 return; 6949 } 6950 6951 const width = bbox[2] - bbox[0]; 6952 const height = bbox[3] - bbox[1]; 6953 const region = new Path2D(); 6954 region.rect(bbox[0], bbox[1], width, height); 6955 ctx.clip(region); 6956} 6957 6958class BaseShadingPattern { 6959 constructor() { 6960 if (this.constructor === BaseShadingPattern) { 6961 (0, _util.unreachable)("Cannot initialize BaseShadingPattern."); 6962 } 6963 } 6964 6965 getPattern() { 6966 (0, _util.unreachable)("Abstract method `getPattern` called."); 6967 } 6968 6969} 6970 6971class RadialAxialShadingPattern extends BaseShadingPattern { 6972 constructor(IR) { 6973 super(); 6974 this._type = IR[1]; 6975 this._bbox = IR[2]; 6976 this._colorStops = IR[3]; 6977 this._p0 = IR[4]; 6978 this._p1 = IR[5]; 6979 this._r0 = IR[6]; 6980 this._r1 = IR[7]; 6981 this._matrix = IR[8]; 6982 this._patternCache = null; 6983 } 6984 6985 _createGradient(ctx) { 6986 let grad; 6987 6988 if (this._type === "axial") { 6989 grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]); 6990 } else if (this._type === "radial") { 6991 grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1); 6992 } 6993 6994 for (const colorStop of this._colorStops) { 6995 grad.addColorStop(colorStop[0], colorStop[1]); 6996 } 6997 6998 return grad; 6999 } 7000 7001 getPattern(ctx, owner, inverse, shadingFill = false) { 7002 let pattern; 7003 7004 if (this._patternCache) { 7005 pattern = this._patternCache; 7006 } else { 7007 if (!shadingFill) { 7008 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", owner.ctx.canvas.width, owner.ctx.canvas.height, true); 7009 const tmpCtx = tmpCanvas.context; 7010 tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); 7011 tmpCtx.beginPath(); 7012 tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); 7013 tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform); 7014 7015 if (this._matrix) { 7016 tmpCtx.transform.apply(tmpCtx, this._matrix); 7017 } 7018 7019 applyBoundingBox(tmpCtx, this._bbox); 7020 tmpCtx.fillStyle = this._createGradient(tmpCtx); 7021 tmpCtx.fill(); 7022 pattern = ctx.createPattern(tmpCanvas.canvas, "repeat"); 7023 } else { 7024 applyBoundingBox(ctx, this._bbox); 7025 pattern = this._createGradient(ctx); 7026 } 7027 7028 this._patternCache = pattern; 7029 } 7030 7031 if (!shadingFill) { 7032 const domMatrix = new DOMMatrix(inverse); 7033
vendor: 4,514 bytes, lines 7034-7223
7034 try { 7035 pattern.setTransform(domMatrix); 7036 } catch (ex) { 7037 (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`); 7038 } 7039 } 7040 7041 return pattern; 7042 } 7043 7044} 7045 7046function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { 7047 const coords = context.coords, 7048 colors = context.colors; 7049 const bytes = data.data, 7050 rowSize = data.width * 4; 7051 let tmp; 7052 7053 if (coords[p1 + 1] > coords[p2 + 1]) { 7054 tmp = p1; 7055 p1 = p2; 7056 p2 = tmp; 7057 tmp = c1; 7058 c1 = c2; 7059 c2 = tmp; 7060 } 7061 7062 if (coords[p2 + 1] > coords[p3 + 1]) { 7063 tmp = p2; 7064 p2 = p3; 7065 p3 = tmp; 7066 tmp = c2; 7067 c2 = c3; 7068 c3 = tmp; 7069 } 7070 7071 if (coords[p1 + 1] > coords[p2 + 1]) { 7072 tmp = p1; 7073 p1 = p2; 7074 p2 = tmp; 7075 tmp = c1; 7076 c1 = c2; 7077 c2 = tmp; 7078 } 7079 7080 const x1 = (coords[p1] + context.offsetX) * context.scaleX; 7081 const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; 7082 const x2 = (coords[p2] + context.offsetX) * context.scaleX; 7083 const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; 7084 const x3 = (coords[p3] + context.offsetX) * context.scaleX; 7085 const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; 7086 7087 if (y1 >= y3) { 7088 return; 7089 } 7090 7091 const c1r = colors[c1], 7092 c1g = colors[c1 + 1], 7093 c1b = colors[c1 + 2]; 7094 const c2r = colors[c2], 7095 c2g = colors[c2 + 1], 7096 c2b = colors[c2 + 2]; 7097 const c3r = colors[c3], 7098 c3g = colors[c3 + 1], 7099 c3b = colors[c3 + 2]; 7100 const minY = Math.round(y1), 7101 maxY = Math.round(y3); 7102 let xa, car, cag, cab; 7103 let xb, cbr, cbg, cbb; 7104 7105 for (let y = minY; y <= maxY; y++) { 7106 if (y < y2) { 7107 let k; 7108 7109 if (y < y1) { 7110 k = 0; 7111 } else { 7112 k = (y1 - y) / (y1 - y2); 7113 } 7114 7115 xa = x1 - (x1 - x2) * k; 7116 car = c1r - (c1r - c2r) * k; 7117 cag = c1g - (c1g - c2g) * k; 7118 cab = c1b - (c1b - c2b) * k; 7119 } else { 7120 let k; 7121 7122 if (y > y3) { 7123 k = 1; 7124 } else if (y2 === y3) { 7125 k = 0; 7126 } else { 7127 k = (y2 - y) / (y2 - y3); 7128 } 7129 7130 xa = x2 - (x2 - x3) * k; 7131 car = c2r - (c2r - c3r) * k; 7132 cag = c2g - (c2g - c3g) * k; 7133 cab = c2b - (c2b - c3b) * k; 7134 } 7135 7136 let k; 7137 7138 if (y < y1) { 7139 k = 0; 7140 } else if (y > y3) { 7141 k = 1; 7142 } else { 7143 k = (y1 - y) / (y1 - y3); 7144 } 7145 7146 xb = x1 - (x1 - x3) * k; 7147 cbr = c1r - (c1r - c3r) * k; 7148 cbg = c1g - (c1g - c3g) * k; 7149 cbb = c1b - (c1b - c3b) * k; 7150 const x1_ = Math.round(Math.min(xa, xb)); 7151 const x2_ = Math.round(Math.max(xa, xb)); 7152 let j = rowSize * y + x1_ * 4; 7153 7154 for (let x = x1_; x <= x2_; x++) { 7155 k = (xa - x) / (xa - xb); 7156 7157 if (k < 0) { 7158 k = 0; 7159 } else if (k > 1) { 7160 k = 1; 7161 } 7162 7163 bytes[j++] = car - (car - cbr) * k | 0; 7164 bytes[j++] = cag - (cag - cbg) * k | 0; 7165 bytes[j++] = cab - (cab - cbb) * k | 0; 7166 bytes[j++] = 255; 7167 } 7168 } 7169} 7170 7171function drawFigure(data, figure, context) { 7172 const ps = figure.coords; 7173 const cs = figure.colors; 7174 let i, ii; 7175 7176 switch (figure.type) { 7177 case "lattice": 7178 const verticesPerRow = figure.verticesPerRow; 7179 const rows = Math.floor(ps.length / verticesPerRow) - 1; 7180 const cols = verticesPerRow - 1; 7181 7182 for (i = 0; i < rows; i++) { 7183 let q = i * verticesPerRow; 7184 7185 for (let j = 0; j < cols; j++, q++) { 7186 drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); 7187 drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); 7188 } 7189 } 7190 7191 break; 7192 7193 case "triangles": 7194 for (i = 0, ii = ps.length; i < ii; i += 3) { 7195 drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); 7196 } 7197 7198 break; 7199 7200 default: 7201 throw new Error("illegal figure"); 7202 } 7203} 7204 7205class MeshShadingPattern extends BaseShadingPattern { 7206 constructor(IR) { 7207 super(); 7208 this._coords = IR[2]; 7209 this._colors = IR[3]; 7210 this._figures = IR[4]; 7211 this._bounds = IR[5]; 7212 this._matrix = IR[6]; 7213 this._bbox = IR[7]; 7214 this._background = IR[8]; 7215 } 7216 7217 _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) { 7218 const EXPECTED_SCALE = 1.1; 7219 const MAX_PATTERN_SIZE = 3000; 7220 const BORDER_SIZE = 2; 7221 const offsetX = Math.floor(this._bounds[0]); 7222 const offsetY = Math.floor(this._bounds[1]); 7223 const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
7224 const boundsHeight = Math.ceil(this._bounds[3]) - offsetY; 7225 const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); 7226 const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); 7227 const scaleX = boundsWidth / width; 7228 const scaleY = boundsHeight / height; 7229 const context = { 7230 coords: this._coords, 7231 colors: this._colors, 7232 offsetX: -offsetX, 7233 offsetY: -offsetY, 7234 scaleX: 1 / scaleX, 7235 scaleY: 1 / scaleY 7236 }; 7237 const paddedWidth = width + BORDER_SIZE * 2; 7238 const paddedHeight = height + BORDER_SIZE * 2; 7239 const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false); 7240 const tmpCtx = tmpCanvas.context; 7241 const data = tmpCtx.createImageData(width, height); 7242 7243 if (backgroundColor) { 7244 const bytes = data.data; 7245 7246 for (let i = 0, ii = bytes.length; i < ii; i += 4) { 7247 bytes[i] = backgroundColor[0]; 7248 bytes[i + 1] = backgroundColor[1]; 7249 bytes[i + 2] = backgroundColor[2]; 7250 bytes[i + 3] = 255; 7251 } 7252 } 7253 7254 for (const figure of this._figures) { 7255 drawFigure(data, figure, context); 7256 } 7257 7258 tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); 7259 const canvas = tmpCanvas.canvas; 7260 return { 7261 canvas, 7262 offsetX: offsetX - BORDER_SIZE * scaleX, 7263 offsetY: offsetY - BORDER_SIZE * scaleY, 7264 scaleX, 7265 scaleY 7266 }; 7267 } 7268 7269 getPattern(ctx, owner, inverse, shadingFill = false) { 7270 applyBoundingBox(ctx, this._bbox); 7271 let scale; 7272 7273 if (shadingFill) { 7274 scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); 7275 } else { 7276 scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform); 7277 7278 if (this._matrix) { 7279 const matrixScale = _util.Util.singularValueDecompose2dScale(this._matrix); 7280 7281 scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; 7282 } 7283 } 7284 7285 const temporaryPatternCanvas = this._createMeshCanvas(scale, shadingFill ? null : this._background, owner.cachedCanvases); 7286 7287 if (!shadingFill) { 7288 ctx.setTransform.apply(ctx, owner.baseTransform); 7289 7290 if (this._matrix) { 7291 ctx.transform.apply(ctx, this._matrix); 7292 } 7293 } 7294 7295 ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); 7296 ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); 7297 return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat"); 7298 } 7299 7300} 7301 7302class DummyShadingPattern extends BaseShadingPattern { 7303 getPattern() { 7304 return "hotpink"; 7305 } 7306 7307} 7308 7309function getShadingPattern(IR) { 7310 switch (IR[0]) { 7311 case "RadialAxial": 7312 return new RadialAxialShadingPattern(IR); 7313 7314 case "Mesh": 7315 return new MeshShadingPattern(IR); 7316 7317 case "Dummy": 7318 return new DummyShadingPattern(); 7319 } 7320 7321 throw new Error(`Unknown IR type: ${IR[0]}`); 7322} 7323 7324const PaintType = { 7325 COLORED: 1, 7326 UNCOLORED: 2 7327}; 7328 7329class TilingPattern { 7330 static get MAX_PATTERN_SIZE() { 7331 return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000); 7332 } 7333 7334 constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) { 7335 this.operatorList = IR[2]; 7336 this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; 7337 this.bbox = IR[4]; 7338 this.xstep = IR[5]; 7339 this.ystep = IR[6]; 7340 this.paintType = IR[7]; 7341 this.tilingType = IR[8]; 7342 this.color = color; 7343 this.ctx = ctx; 7344 this.canvasGraphicsFactory = canvasGraphicsFactory; 7345 this.baseTransform = baseTransform; 7346 } 7347 7348 createPatternCanvas(owner) { 7349 const operatorList = this.operatorList; 7350 const bbox = this.bbox; 7351 const xstep = this.xstep; 7352 const ystep = this.ystep; 7353 const paintType = this.paintType; 7354 const tilingType = this.tilingType; 7355 const color = this.color; 7356 const canvasGraphicsFactory = this.canvasGraphicsFactory; 7357 (0, _util.info)("TilingType: " + tilingType); 7358 const x0 = bbox[0], 7359 y0 = bbox[1], 7360 x1 = bbox[2], 7361 y1 = bbox[3]; 7362 7363 const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix); 7364 7365 const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform); 7366 7367 const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
7368 const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]); 7369 const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]); 7370 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true); 7371 const tmpCtx = tmpCanvas.context; 7372 const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); 7373 graphics.groupLevel = owner.groupLevel; 7374 this.setFillAndStrokeStyleToContext(graphics, paintType, color); 7375 let adjustedX0 = x0; 7376 let adjustedY0 = y0; 7377 let adjustedX1 = x1; 7378 let adjustedY1 = y1; 7379 7380 if (x0 < 0) { 7381 adjustedX0 = 0; 7382 adjustedX1 += Math.abs(x0); 7383 } 7384 7385 if (y0 < 0) { 7386 adjustedY0 = 0; 7387 adjustedY1 += Math.abs(y0); 7388 } 7389 7390 tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0)); 7391 graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0); 7392 this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1); 7393 graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice(); 7394 graphics.executeOperatorList(operatorList); 7395 graphics.endDrawing(); 7396 return { 7397 canvas: tmpCanvas.canvas, 7398 scaleX: dimx.scale, 7399 scaleY: dimy.scale, 7400 offsetX: adjustedX0, 7401 offsetY: adjustedY0 7402 }; 7403 } 7404 7405 getSizeAndScale(step, realOutputSize, scale) { 7406 step = Math.abs(step); 7407 const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize); 7408 let size = Math.ceil(step * scale); 7409 7410 if (size >= maxSize) { 7411 size = maxSize; 7412 } else { 7413 scale = size / step; 7414 } 7415 7416 return { 7417 scale, 7418 size 7419 }; 7420 } 7421 7422 clipBbox(graphics, x0, y0, x1, y1) { 7423 const bboxWidth = x1 - x0; 7424 const bboxHeight = y1 - y0; 7425 graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); 7426 graphics.clip(); 7427 graphics.endPath(); 7428 } 7429 7430 setFillAndStrokeStyleToContext(graphics, paintType, color) { 7431 const context = graphics.ctx, 7432 current = graphics.current; 7433 7434 switch (paintType) { 7435 case PaintType.COLORED: 7436 const ctx = this.ctx; 7437 context.fillStyle = ctx.fillStyle; 7438 context.strokeStyle = ctx.strokeStyle; 7439 current.fillColor = ctx.fillStyle; 7440 current.strokeColor = ctx.strokeStyle; 7441 break; 7442 7443 case PaintType.UNCOLORED: 7444 const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]); 7445 7446 context.fillStyle = cssColor; 7447 context.strokeStyle = cssColor; 7448 current.fillColor = cssColor; 7449 current.strokeColor = cssColor; 7450 break; 7451 7452 default: 7453 throw new _util.FormatError(`Unsupported paint type: ${paintType}`); 7454 } 7455 } 7456 7457 getPattern(ctx, owner, inverse, shadingFill = false) { 7458 let matrix = inverse; 7459 7460 if (!shadingFill) { 7461 matrix = _util.Util.transform(matrix, owner.baseTransform); 7462 7463 if (this.matrix) { 7464 matrix = _util.Util.transform(matrix, this.matrix); 7465 } 7466 } 7467 7468 const temporaryPatternCanvas = this.createPatternCanvas(owner); 7469 let domMatrix = new DOMMatrix(matrix); 7470 domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); 7471 domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY); 7472 const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat"); 7473 7474 try { 7475 pattern.setTransform(domMatrix); 7476 } catch (ex) { 7477 (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`); 7478 } 7479 7480 return pattern; 7481 } 7482 7483} 7484 7485exports.TilingPattern = TilingPattern; 7486 7487/***/ }), 7488/* 12 */ 7489/***/ ((__unused_webpack_module, exports) => { 7490 7491 7492 7493Object.defineProperty(exports, "__esModule", ({ 7494 value: true 7495})); 7496exports.GlobalWorkerOptions = void 0; 7497const GlobalWorkerOptions = Object.create(null); 7498exports.GlobalWorkerOptions = GlobalWorkerOptions; 7499GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort; 7500GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc; 7501 7502/***/ }), 7503/* 13 */ 7504/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 7505 7506 7507 7508Object.defineProperty(exports, "__esModule", ({ 7509 value: true 7510})); 7511exports.MessageHandler = void 0; 7512 7513var _util = __w_pdfjs_require__(2); 7514 7515const CallbackKind = { 7516 UNKNOWN: 0, 7517 DATA: 1, 7518 ERROR: 2 7519}; 7520const StreamKind = { 7521 UNKNOWN: 0, 7522 CANCEL: 1, 7523 CANCEL_COMPLETE: 2, 7524 CLOSE: 3, 7525 ENQUEUE: 4, 7526 ERROR: 5, 7527 PULL: 6, 7528 PULL_COMPLETE: 7, 7529 START_COMPLETE: 8 7530}; 7531 7532function wrapReason(reason) { 7533 if (typeof reason !== "object" || reason === null) { 7534 return reason; 7535 } 7536 7537 switch (reason.name) { 7538 case "AbortException": 7539 return new _util.AbortException(reason.message); 7540 7541 case "MissingPDFException": 7542 return new _util.MissingPDFException(reason.message); 7543 7544 case "UnexpectedResponseException": 7545 return new _util.UnexpectedResponseException(reason.message, reason.status); 7546 7547 case "UnknownErrorException": 7548 return new _util.UnknownErrorException(reason.message, reason.details); 7549 7550 default: 7551 return new _util.UnknownErrorException(reason.message, reason.toString()); 7552 } 7553} 7554 7555class MessageHandler {
7556 constructor(sourceName, targetName, comObj) { 7557 this.sourceName = sourceName; 7558 this.targetName = targetName; 7559 this.comObj = comObj; 7560 this.callbackId = 1; 7561 this.streamId = 1; 7562 this.postMessageTransfers = true; 7563 this.streamSinks = Object.create(null); 7564 this.streamControllers = Object.create(null); 7565 this.callbackCapabilities = Object.create(null); 7566 this.actionHandler = Object.create(null); 7567 7568 this._onComObjOnMessage = event => { 7569 const data = event.data; 7570 7571 if (data.targetName !== this.sourceName) { 7572 return; 7573 } 7574 7575 if (data.stream) { 7576 this._processStreamMessage(data); 7577 7578 return; 7579 } 7580 7581 if (data.callback) { 7582 const callbackId = data.callbackId; 7583 const capability = this.callbackCapabilities[callbackId]; 7584 7585 if (!capability) { 7586 throw new Error(`Cannot resolve callback ${callbackId}`); 7587 } 7588 7589 delete this.callbackCapabilities[callbackId]; 7590 7591 if (data.callback === CallbackKind.DATA) { 7592 capability.resolve(data.data); 7593 } else if (data.callback === CallbackKind.ERROR) { 7594 capability.reject(wrapReason(data.reason)); 7595 } else { 7596 throw new Error("Unexpected callback case"); 7597 } 7598 7599 return; 7600 } 7601 7602 const action = this.actionHandler[data.action]; 7603 7604 if (!action) { 7605 throw new Error(`Unknown action from worker: ${data.action}`); 7606 } 7607 7608 if (data.callbackId) { 7609 const cbSourceName = this.sourceName; 7610 const cbTargetName = data.sourceName; 7611 new Promise(function (resolve) { 7612 resolve(action(data.data)); 7613 }).then(function (result) { 7614 comObj.postMessage({ 7615 sourceName: cbSourceName, 7616 targetName: cbTargetName, 7617 callback: CallbackKind.DATA, 7618 callbackId: data.callbackId, 7619 data: result 7620 }); 7621 }, function (reason) { 7622 comObj.postMessage({ 7623 sourceName: cbSourceName, 7624 targetName: cbTargetName, 7625 callback: CallbackKind.ERROR, 7626 callbackId: data.callbackId, 7627 reason: wrapReason(reason) 7628 }); 7629 }); 7630 return; 7631 } 7632 7633 if (data.streamId) { 7634 this._createStreamSink(data); 7635 7636 return; 7637 } 7638 7639 action(data.data); 7640 }; 7641 7642 comObj.addEventListener("message", this._onComObjOnMessage); 7643 } 7644 7645 on(actionName, handler) { 7646 const ah = this.actionHandler; 7647 7648 if (ah[actionName]) { 7649 throw new Error(`There is already an actionName called "${actionName}"`); 7650 } 7651 7652 ah[actionName] = handler; 7653 } 7654 7655 send(actionName, data, transfers) { 7656 this._postMessage({ 7657 sourceName: this.sourceName, 7658 targetName: this.targetName, 7659 action: actionName, 7660 data 7661 }, transfers); 7662 } 7663 7664 sendWithPromise(actionName, data, transfers) { 7665 const callbackId = this.callbackId++; 7666 const capability = (0, _util.createPromiseCapability)(); 7667 this.callbackCapabilities[callbackId] = capability; 7668 7669 try { 7670 this._postMessage({ 7671 sourceName: this.sourceName, 7672 targetName: this.targetName, 7673 action: actionName, 7674 callbackId, 7675 data 7676 }, transfers); 7677 } catch (ex) { 7678 capability.reject(ex); 7679 } 7680 7681 return capability.promise; 7682 } 7683 7684 sendWithStream(actionName, data, queueingStrategy, transfers) { 7685 const streamId = this.streamId++; 7686 const sourceName = this.sourceName; 7687 const targetName = this.targetName; 7688 const comObj = this.comObj; 7689 return new ReadableStream({ 7690 start: controller => { 7691 const startCapability = (0, _util.createPromiseCapability)(); 7692 this.streamControllers[streamId] = { 7693 controller, 7694 startCall: startCapability, 7695 pullCall: null, 7696 cancelCall: null, 7697 isClosed: false 7698 }; 7699 7700 this._postMessage({ 7701 sourceName, 7702 targetName, 7703 action: actionName, 7704 streamId, 7705 data, 7706 desiredSize: controller.desiredSize 7707 }, transfers); 7708 7709 return startCapability.promise; 7710 }, 7711 pull: controller => { 7712 const pullCapability = (0, _util.createPromiseCapability)(); 7713 this.streamControllers[streamId].pullCall = pullCapability; 7714 comObj.postMessage({ 7715 sourceName, 7716 targetName, 7717 stream: StreamKind.PULL, 7718 streamId, 7719 desiredSize: controller.desiredSize 7720 }); 7721 return pullCapability.promise; 7722 }, 7723 cancel: reason => { 7724 (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason"); 7725 const cancelCapability = (0, _util.createPromiseCapability)(); 7726 this.streamControllers[streamId].cancelCall = cancelCapability; 7727 this.streamControllers[streamId].isClosed = true; 7728 comObj.postMessage({ 7729 sourceName, 7730 targetName, 7731 stream: StreamKind.CANCEL, 7732 streamId, 7733 reason: wrapReason(reason) 7734 }); 7735 return cancelCapability.promise; 7736 } 7737 }, queueingStrategy); 7738 } 7739 7740 _createStreamSink(data) { 7741 const self = this; 7742 const action = this.actionHandler[data.action]; 7743 const streamId = data.streamId; 7744 const sourceName = this.sourceName; 7745 const targetName = data.sourceName; 7746 const comObj = this.comObj; 7747 const streamSink = { 7748 enqueue(chunk, size = 1, transfers) { 7749 if (this.isCancelled) { 7750 return; 7751 } 7752 7753 const lastDesiredSize = this.desiredSize; 7754 this.desiredSize -= size; 7755 7756 if (lastDesiredSize > 0 && this.desiredSize <= 0) { 7757 this.sinkCapability = (0, _util.createPromiseCapability)(); 7758 this.ready = this.sinkCapability.promise; 7759 } 7760 7761 self._postMessage({ 7762 sourceName, 7763 targetName, 7764 stream: StreamKind.ENQUEUE, 7765 streamId, 7766 chunk 7767 }, transfers); 7768 }, 7769 7770 close() { 7771 if (this.isCancelled) { 7772 return; 7773 } 7774 7775 this.isCancelled = true; 7776 comObj.postMessage({ 7777 sourceName, 7778 targetName, 7779 stream: StreamKind.CLOSE, 7780 streamId 7781 }); 7782 delete self.streamSinks[streamId]; 7783 }, 7784 7785 error(reason) { 7786 (0, _util.assert)(reason instanceof Error, "error must have a valid reason"); 7787 7788 if (this.isCancelled) { 7789 return; 7790 } 7791 7792 this.isCancelled = true; 7793 comObj.postMessage({ 7794 sourceName, 7795 targetName, 7796 stream: StreamKind.ERROR, 7797 streamId, 7798 reason: wrapReason(reason) 7799 }); 7800 }, 7801 7802 sinkCapability: (0, _util.createPromiseCapability)(), 7803 onPull: null, 7804 onCancel: null, 7805 isCancelled: false, 7806 desiredSize: data.desiredSize, 7807 ready: null 7808 }; 7809 streamSink.sinkCapability.resolve(); 7810 streamSink.ready = streamSink.sinkCapability.promise; 7811 this.streamSinks[streamId] = streamSink; 7812 new Promise(function (resolve) { 7813 resolve(action(data.data, streamSink)); 7814 }).then(function () { 7815 comObj.postMessage({ 7816 sourceName, 7817 targetName, 7818 stream: StreamKind.START_COMPLETE, 7819 streamId, 7820 success: true 7821 }); 7822 }, function (reason) { 7823 comObj.postMessage({ 7824 sourceName, 7825 targetName, 7826 stream: StreamKind.START_COMPLETE, 7827 streamId, 7828 reason: wrapReason(reason) 7829 }); 7830 }); 7831 } 7832 7833 _processStreamMessage(data) { 7834 const streamId = data.streamId; 7835 const sourceName = this.sourceName; 7836 const targetName = data.sourceName; 7837 const comObj = this.comObj; 7838 7839 switch (data.stream) { 7840 case StreamKind.START_COMPLETE: 7841 if (data.success) { 7842 this.streamControllers[streamId].startCall.resolve(); 7843 } else { 7844 this.streamControllers[streamId].startCall.reject(wrapReason(data.reason)); 7845 } 7846 7847 break; 7848 7849 case StreamKind.PULL_COMPLETE: 7850 if (data.success) { 7851 this.streamControllers[streamId].pullCall.resolve(); 7852 } else { 7853 this.streamControllers[streamId].pullCall.reject(wrapReason(data.reason)); 7854 } 7855 7856 break; 7857 7858 case StreamKind.PULL: 7859 if (!this.streamSinks[streamId]) { 7860 comObj.postMessage({ 7861 sourceName, 7862 targetName, 7863 stream: StreamKind.PULL_COMPLETE, 7864 streamId, 7865 success: true 7866 }); 7867 break; 7868 } 7869 7870 if (this.streamSinks[streamId].desiredSize <= 0 && data.desiredSize > 0) { 7871 this.streamSinks[streamId].sinkCapability.resolve(); 7872 } 7873 7874 this.streamSinks[streamId].desiredSize = data.desiredSize; 7875 const { 7876 onPull 7877 } = this.streamSinks[data.streamId]; 7878 new Promise(function (resolve) { 7879 resolve(onPull && onPull()); 7880 }).then(function () { 7881 comObj.postMessage({ 7882 sourceName, 7883 targetName, 7884 stream: StreamKind.PULL_COMPLETE, 7885 streamId, 7886 success: true 7887 }); 7888 }, function (reason) { 7889 comObj.postMessage({ 7890 sourceName, 7891 targetName, 7892 stream: StreamKind.PULL_COMPLETE, 7893 streamId, 7894 reason: wrapReason(reason) 7895 }); 7896 }); 7897 break; 7898 7899 case StreamKind.ENQUEUE: 7900 (0, _util.assert)(this.streamControllers[streamId], "enqueue should have stream controller"); 7901 7902 if (this.streamControllers[streamId].isClosed) { 7903 break; 7904 } 7905 7906 this.streamControllers[streamId].controller.enqueue(data.chunk); 7907 break; 7908 7909 case StreamKind.CLOSE: 7910 (0, _util.assert)(this.streamControllers[streamId], "close should have stream controller"); 7911 7912 if (this.streamControllers[streamId].isClosed) { 7913 break; 7914 } 7915 7916 this.streamControllers[streamId].isClosed = true; 7917 this.streamControllers[streamId].controller.close(); 7918 7919 this._deleteStreamController(streamId); 7920 7921 break; 7922 7923 case StreamKind.ERROR: 7924 (0, _util.assert)(this.streamControllers[streamId], "error should have stream controller"); 7925 this.streamControllers[streamId].controller.error(wrapReason(data.reason)); 7926 7927 this._deleteStreamController(streamId); 7928 7929 break; 7930 7931 case StreamKind.CANCEL_COMPLETE: 7932 if (data.success) { 7933 this.streamControllers[streamId].cancelCall.resolve(); 7934 } else { 7935 this.streamControllers[streamId].cancelCall.reject(wrapReason(data.reason)); 7936 } 7937 7938 this._deleteStreamController(streamId); 7939 7940 break; 7941 7942 case StreamKind.CANCEL: 7943 if (!this.streamSinks[streamId]) { 7944 break; 7945 } 7946 7947 const { 7948 onCancel 7949 } = this.streamSinks[data.streamId]; 7950 new Promise(function (resolve) { 7951 resolve(onCancel && onCancel(wrapReason(data.reason))); 7952 }).then(function () { 7953 comObj.postMessage({ 7954 sourceName, 7955 targetName, 7956 stream: StreamKind.CANCEL_COMPLETE, 7957 streamId, 7958 success: true 7959 }); 7960 }, function (reason) { 7961 comObj.postMessage({ 7962 sourceName, 7963 targetName, 7964 stream: StreamKind.CANCEL_COMPLETE, 7965 streamId, 7966 reason: wrapReason(reason) 7967 }); 7968 }); 7969 this.streamSinks[streamId].sinkCapability.reject(wrapReason(data.reason)); 7970 this.streamSinks[streamId].isCancelled = true; 7971 delete this.streamSinks[streamId]; 7972 break; 7973 7974 default: 7975 throw new Error("Unexpected stream case"); 7976 } 7977 } 7978 7979 async _deleteStreamController(streamId) { 7980 await Promise.allSettled([this.streamControllers[streamId].startCall, this.streamControllers[streamId].pullCall, this.streamControllers[streamId].cancelCall].map(function (capability) { 7981 return capability && capability.promise; 7982 })); 7983 delete this.streamControllers[streamId]; 7984 } 7985 7986 _postMessage(message, transfers) { 7987 if (transfers && this.postMessageTransfers) { 7988 this.comObj.postMessage(message, transfers); 7989 } else { 7990 this.comObj.postMessage(message); 7991 } 7992 } 7993 7994 destroy() { 7995 this.comObj.removeEventListener("message", this._onComObjOnMessage); 7996 } 7997 7998} 7999 8000exports.MessageHandler = MessageHandler; 8001 8002/***/ }), 8003/* 14 */ 8004/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 8005 8006 8007 8008Object.defineProperty(exports, "__esModule", ({ 8009 value: true 8010})); 8011exports.Metadata = void 0; 8012 8013var _util = __w_pdfjs_require__(2); 8014 8015class Metadata { 8016 constructor({ 8017 parsedData, 8018 rawData 8019 }) { 8020 this._metadataMap = parsedData; 8021 this._data = rawData; 8022 } 8023 8024 getRaw() { 8025 return this._data; 8026 } 8027 8028 get(name) { 8029 return this._metadataMap.get(name) ?? null; 8030 } 8031 8032 getAll() { 8033 return (0, _util.objectFromMap)(this._metadataMap); 8034 } 8035 8036 has(name) { 8037 return this._metadataMap.has(name); 8038 } 8039 8040} 8041 8042exports.Metadata = Metadata; 8043 8044/***/ }), 8045/* 15 */ 8046/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 8047 8048 8049 8050Object.defineProperty(exports, "__esModule", ({ 8051 value: true 8052})); 8053exports.OptionalContentConfig = void 0; 8054 8055var _util = __w_pdfjs_require__(2); 8056 8057class OptionalContentGroup { 8058 constructor(name, intent) { 8059 this.visible = true; 8060 this.name = name; 8061 this.intent = intent; 8062 } 8063 8064} 8065 8066class OptionalContentConfig { 8067 constructor(data) { 8068 this.name = null; 8069 this.creator = null; 8070 this._order = null; 8071 this._groups = new Map(); 8072 8073 if (data === null) { 8074 return; 8075 } 8076 8077 this.name = data.name; 8078 this.creator = data.creator; 8079 this._order = data.order; 8080 8081 for (const group of data.groups) { 8082 this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent)); 8083 } 8084 8085 if (data.baseState === "OFF") { 8086 for (const group of this._groups) { 8087 group.visible = false;
8088 } 8089 } 8090 8091 for (const on of data.on) { 8092 this._groups.get(on).visible = true; 8093 } 8094 8095 for (const off of data.off) { 8096 this._groups.get(off).visible = false; 8097 } 8098 } 8099 8100 _evaluateVisibilityExpression(array) { 8101 const length = array.length; 8102 8103 if (length < 2) { 8104 return true; 8105 } 8106 8107 const operator = array[0]; 8108 8109 for (let i = 1; i < length; i++) { 8110 const element = array[i]; 8111 let state; 8112 8113 if (Array.isArray(element)) { 8114 state = this._evaluateVisibilityExpression(element); 8115 } else if (this._groups.has(element)) { 8116 state = this._groups.get(element).visible; 8117 } else { 8118 (0, _util.warn)(`Optional content group not found: ${element}`); 8119 return true; 8120 } 8121 8122 switch (operator) { 8123 case "And": 8124 if (!state) { 8125 return false; 8126 } 8127 8128 break; 8129 8130 case "Or": 8131 if (state) { 8132 return true; 8133 } 8134 8135 break; 8136 8137 case "Not": 8138 return !state; 8139 8140 default: 8141 return true; 8142 } 8143 } 8144 8145 return operator === "And"; 8146 } 8147 8148 isVisible(group) { 8149 if (group.type === "OCG") { 8150 if (!this._groups.has(group.id)) { 8151 (0, _util.warn)(`Optional content group not found: ${group.id}`); 8152 return true; 8153 } 8154 8155 return this._groups.get(group.id).visible; 8156 } else if (group.type === "OCMD") { 8157 if (group.expression) { 8158 return this._evaluateVisibilityExpression(group.expression); 8159 } 8160 8161 if (!group.policy || group.policy === "AnyOn") { 8162 for (const id of group.ids) { 8163 if (!this._groups.has(id)) { 8164 (0, _util.warn)(`Optional content group not found: ${id}`); 8165 return true; 8166 } 8167 8168 if (this._groups.get(id).visible) { 8169 return true; 8170 } 8171 } 8172 8173 return false; 8174 } else if (group.policy === "AllOn") { 8175 for (const id of group.ids) { 8176 if (!this._groups.has(id)) { 8177 (0, _util.warn)(`Optional content group not found: ${id}`); 8178 return true; 8179 } 8180 8181 if (!this._groups.get(id).visible) { 8182 return false; 8183 } 8184 } 8185 8186 return true; 8187 } else if (group.policy === "AnyOff") { 8188 for (const id of group.ids) { 8189 if (!this._groups.has(id)) { 8190 (0, _util.warn)(`Optional content group not found: ${id}`); 8191 return true; 8192 } 8193 8194 if (!this._groups.get(id).visible) { 8195 return true; 8196 } 8197 } 8198 8199 return false; 8200 } else if (group.policy === "AllOff") { 8201 for (const id of group.ids) { 8202 if (!this._groups.has(id)) { 8203 (0, _util.warn)(`Optional content group not found: ${id}`); 8204 return true; 8205 } 8206 8207 if (this._groups.get(id).visible) { 8208 return false; 8209 } 8210 } 8211 8212 return true; 8213 } 8214 8215 (0, _util.warn)(`Unknown optional content policy ${group.policy}.`); 8216 return true; 8217 } 8218 8219 (0, _util.warn)(`Unknown group type ${group.type}.`); 8220 return true; 8221 } 8222 8223 setVisibility(id, visible = true) { 8224 if (!this._groups.has(id)) { 8225 (0, _util.warn)(`Optional content group not found: ${id}`); 8226 return; 8227 } 8228 8229 this._groups.get(id).visible = !!visible; 8230 } 8231 8232 getOrder() { 8233 if (!this._groups.size) { 8234 return null; 8235 } 8236 8237 if (this._order) { 8238 return this._order.slice(); 8239 } 8240 8241 return Array.from(this._groups.keys()); 8242 } 8243 8244 getGroups() { 8245 return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null; 8246 } 8247 8248 getGroup(id) { 8249 return this._groups.get(id) || null; 8250 } 8251 8252} 8253 8254exports.OptionalContentConfig = OptionalContentConfig; 8255 8256/***/ }), 8257/* 16 */ 8258/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 8259 8260 8261 8262Object.defineProperty(exports, "__esModule", ({ 8263 value: true 8264})); 8265exports.PDFDataTransportStream = void 0; 8266 8267var _util = __w_pdfjs_require__(2); 8268 8269var _display_utils = __w_pdfjs_require__(1); 8270 8271class PDFDataTransportStream { 8272 constructor(params, pdfDataRangeTransport) { 8273 (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'); 8274 this._queuedChunks = []; 8275 this._progressiveDone = params.progressiveDone || false; 8276 this._contentDispositionFilename = params.contentDispositionFilename || null; 8277 const initialData = params.initialData; 8278 8279 if (initialData?.length > 0) { 8280 const buffer = new Uint8Array(initialData).buffer; 8281 8282 this._queuedChunks.push(buffer); 8283 } 8284 8285 this._pdfDataRangeTransport = pdfDataRangeTransport; 8286 this._isStreamingSupported = !params.disableStream; 8287 this._isRangeSupported = !params.disableRange; 8288 this._contentLength = params.length; 8289 this._fullRequestReader = null; 8290 this._rangeReaders = []; 8291 8292 this._pdfDataRangeTransport.addRangeListener((begin, chunk) => { 8293 this._onReceiveData({ 8294 begin, 8295 chunk 8296 }); 8297 }); 8298 8299 this._pdfDataRangeTransport.addProgressListener((loaded, total) => { 8300 this._onProgress({ 8301 loaded, 8302 total 8303 }); 8304 }); 8305 8306 this._pdfDataRangeTransport.addProgressiveReadListener(chunk => { 8307 this._onReceiveData({ 8308 chunk 8309 }); 8310 }); 8311 8312 this._pdfDataRangeTransport.addProgressiveDoneListener(() => { 8313 this._onProgressiveDone(); 8314 }); 8315 8316 this._pdfDataRangeTransport.transportReady(); 8317 } 8318 8319 _onReceiveData(args) { 8320 const buffer = new Uint8Array(args.chunk).buffer; 8321 8322 if (args.begin === undefined) { 8323 if (this._fullRequestReader) { 8324 this._fullRequestReader._enqueue(buffer); 8325 } else { 8326 this._queuedChunks.push(buffer); 8327 } 8328 } else { 8329 const found = this._rangeReaders.some(function (rangeReader) { 8330 if (rangeReader._begin !== args.begin) { 8331 return false;
8332 } 8333 8334 rangeReader._enqueue(buffer); 8335 8336 return true; 8337 }); 8338 8339 (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); 8340 } 8341 } 8342 8343 get _progressiveDataLength() { 8344 return this._fullRequestReader?._loaded ?? 0; 8345 } 8346 8347 _onProgress(evt) { 8348 if (evt.total === undefined) { 8349 const firstReader = this._rangeReaders[0]; 8350 8351 if (firstReader?.onProgress) { 8352 firstReader.onProgress({ 8353 loaded: evt.loaded 8354 }); 8355 } 8356 } else { 8357 const fullReader = this._fullRequestReader; 8358 8359 if (fullReader?.onProgress) { 8360 fullReader.onProgress({ 8361 loaded: evt.loaded, 8362 total: evt.total 8363 }); 8364 } 8365 } 8366 } 8367 8368 _onProgressiveDone() { 8369 if (this._fullRequestReader) { 8370 this._fullRequestReader.progressiveDone(); 8371 } 8372 8373 this._progressiveDone = true; 8374 } 8375 8376 _removeRangeReader(reader) { 8377 const i = this._rangeReaders.indexOf(reader); 8378 8379 if (i >= 0) { 8380 this._rangeReaders.splice(i, 1); 8381 } 8382 } 8383 8384 getFullReader() { 8385 (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once."); 8386 const queuedChunks = this._queuedChunks; 8387 this._queuedChunks = null; 8388 return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename); 8389 } 8390 8391 getRangeReader(begin, end) { 8392 if (end <= this._progressiveDataLength) { 8393 return null; 8394 } 8395 8396 const reader = new PDFDataTransportStreamRangeReader(this, begin, end); 8397 8398 this._pdfDataRangeTransport.requestDataRange(begin, end); 8399 8400 this._rangeReaders.push(reader); 8401 8402 return reader; 8403 } 8404 8405 cancelAllRequests(reason) { 8406 if (this._fullRequestReader) { 8407 this._fullRequestReader.cancel(reason); 8408 } 8409 8410 for (const reader of this._rangeReaders.slice(0)) { 8411 reader.cancel(reason); 8412 } 8413 8414 this._pdfDataRangeTransport.abort(); 8415 } 8416 8417} 8418 8419exports.PDFDataTransportStream = PDFDataTransportStream; 8420 8421class PDFDataTransportStreamReader { 8422 constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) { 8423 this._stream = stream; 8424 this._done = progressiveDone || false; 8425 this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null; 8426 this._queuedChunks = queuedChunks || []; 8427 this._loaded = 0; 8428 8429 for (const chunk of this._queuedChunks) { 8430 this._loaded += chunk.byteLength; 8431 } 8432 8433 this._requests = []; 8434 this._headersReady = Promise.resolve(); 8435 stream._fullRequestReader = this; 8436 this.onProgress = null; 8437 } 8438 8439 _enqueue(chunk) { 8440 if (this._done) { 8441 return; 8442 } 8443 8444 if (this._requests.length > 0) { 8445 const requestCapability = this._requests.shift(); 8446 8447 requestCapability.resolve({ 8448 value: chunk, 8449 done: false 8450 }); 8451 } else { 8452 this._queuedChunks.push(chunk); 8453 } 8454 8455 this._loaded += chunk.byteLength; 8456 } 8457 8458 get headersReady() { 8459 return this._headersReady; 8460 } 8461 8462 get filename() { 8463 return this._filename; 8464 } 8465 8466 get isRangeSupported() { 8467 return this._stream._isRangeSupported; 8468 } 8469 8470 get isStreamingSupported() { 8471 return this._stream._isStreamingSupported; 8472 } 8473 8474 get contentLength() { 8475 return this._stream._contentLength; 8476 } 8477 8478 async read() { 8479 if (this._queuedChunks.length > 0) { 8480 const chunk = this._queuedChunks.shift(); 8481 8482 return { 8483 value: chunk, 8484 done: false 8485 }; 8486 } 8487 8488 if (this._done) { 8489 return { 8490 value: undefined, 8491 done: true 8492 }; 8493 } 8494 8495 const requestCapability = (0, _util.createPromiseCapability)(); 8496 8497 this._requests.push(requestCapability); 8498 8499 return requestCapability.promise; 8500 } 8501 8502 cancel(reason) { 8503 this._done = true; 8504 8505 for (const requestCapability of this._requests) { 8506 requestCapability.resolve({ 8507 value: undefined, 8508 done: true 8509 }); 8510 } 8511 8512 this._requests.length = 0; 8513 } 8514 8515 progressiveDone() { 8516 if (this._done) { 8517 return; 8518 } 8519 8520 this._done = true; 8521 } 8522 8523} 8524 8525class PDFDataTransportStreamRangeReader { 8526 constructor(stream, begin, end) { 8527 this._stream = stream; 8528 this._begin = begin; 8529 this._end = end; 8530 this._queuedChunk = null; 8531 this._requests = []; 8532 this._done = false;
8533 this.onProgress = null; 8534 } 8535 8536 _enqueue(chunk) { 8537 if (this._done) { 8538 return; 8539 } 8540 8541 if (this._requests.length === 0) { 8542 this._queuedChunk = chunk; 8543 } else { 8544 const requestsCapability = this._requests.shift(); 8545 8546 requestsCapability.resolve({ 8547 value: chunk, 8548 done: false 8549 }); 8550 8551 for (const requestCapability of this._requests) { 8552 requestCapability.resolve({ 8553 value: undefined, 8554 done: true 8555 }); 8556 } 8557 8558 this._requests.length = 0; 8559 } 8560 8561 this._done = true; 8562 8563 this._stream._removeRangeReader(this); 8564 } 8565 8566 get isStreamingSupported() { 8567 return false; 8568 } 8569 8570 async read() { 8571 if (this._queuedChunk) { 8572 const chunk = this._queuedChunk; 8573 this._queuedChunk = null; 8574 return { 8575 value: chunk, 8576 done: false 8577 }; 8578 } 8579 8580 if (this._done) { 8581 return { 8582 value: undefined, 8583 done: true 8584 }; 8585 } 8586 8587 const requestCapability = (0, _util.createPromiseCapability)(); 8588 8589 this._requests.push(requestCapability); 8590 8591 return requestCapability.promise; 8592 } 8593 8594 cancel(reason) { 8595 this._done = true; 8596 8597 for (const requestCapability of this._requests) { 8598 requestCapability.resolve({ 8599 value: undefined, 8600 done: true 8601 }); 8602 } 8603 8604 this._requests.length = 0; 8605 8606 this._stream._removeRangeReader(this); 8607 } 8608 8609} 8610 8611/***/ }), 8612/* 17 */ 8613/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 8614 8615 8616 8617Object.defineProperty(exports, "__esModule", ({ 8618 value: true 8619})); 8620exports.AnnotationLayer = void 0; 8621 8622var _display_utils = __w_pdfjs_require__(1); 8623 8624var _util = __w_pdfjs_require__(2); 8625 8626var _annotation_storage = __w_pdfjs_require__(9); 8627 8628var _scripting_utils = __w_pdfjs_require__(18); 8629 8630class AnnotationElementFactory { 8631 static create(parameters) { 8632 const subtype = parameters.data.annotationType; 8633 8634 switch (subtype) { 8635 case _util.AnnotationType.LINK: 8636 return new LinkAnnotationElement(parameters); 8637 8638 case _util.AnnotationType.TEXT: 8639 return new TextAnnotationElement(parameters); 8640 8641 case _util.AnnotationType.WIDGET: 8642 const fieldType = parameters.data.fieldType; 8643 8644 switch (fieldType) { 8645 case "Tx": 8646 return new TextWidgetAnnotationElement(parameters); 8647 8648 case "Btn": 8649 if (parameters.data.radioButton) { 8650 return new RadioButtonWidgetAnnotationElement(parameters); 8651 } else if (parameters.data.checkBox) { 8652 return new CheckboxWidgetAnnotationElement(parameters); 8653 } 8654 8655 return new PushButtonWidgetAnnotationElement(parameters); 8656 8657 case "Ch": 8658 return new ChoiceWidgetAnnotationElement(parameters); 8659 } 8660 8661 return new WidgetAnnotationElement(parameters); 8662 8663 case _util.AnnotationType.POPUP: 8664 return new PopupAnnotationElement(parameters); 8665 8666 case _util.AnnotationType.FREETEXT: 8667 return new FreeTextAnnotationElement(parameters); 8668 8669 case _util.AnnotationType.LINE: 8670 return new LineAnnotationElement(parameters); 8671 8672 case _util.AnnotationType.SQUARE: 8673 return new SquareAnnotationElement(parameters); 8674 8675 case _util.AnnotationType.CIRCLE: 8676 return new CircleAnnotationElement(parameters); 8677 8678 case _util.AnnotationType.POLYLINE: 8679 return new PolylineAnnotationElement(parameters); 8680 8681 case _util.AnnotationType.CARET: 8682 return new CaretAnnotationElement(parameters); 8683 8684 case _util.AnnotationType.INK: 8685 return new InkAnnotationElement(parameters); 8686 8687 case _util.AnnotationType.POLYGON: 8688 return new PolygonAnnotationElement(parameters); 8689 8690 case _util.AnnotationType.HIGHLIGHT: 8691 return new HighlightAnnotationElement(parameters); 8692 8693 case _util.AnnotationType.UNDERLINE: 8694 return new UnderlineAnnotationElement(parameters); 8695 8696 case _util.AnnotationType.SQUIGGLY: 8697 return new SquigglyAnnotationElement(parameters); 8698 8699 case _util.AnnotationType.STRIKEOUT: 8700 return new StrikeOutAnnotationElement(parameters); 8701 8702 case _util.AnnotationType.STAMP: 8703 return new StampAnnotationElement(parameters); 8704 8705 case _util.AnnotationType.FILEATTACHMENT: 8706 return new FileAttachmentAnnotationElement(parameters); 8707 8708 default: 8709 return new AnnotationElement(parameters); 8710 } 8711 } 8712 8713} 8714 8715class AnnotationElement { 8716 constructor(parameters, { 8717 isRenderable = false, 8718 ignoreBorder = false, 8719 createQuadrilaterals = false 8720 }
8720 = {}) { 8721 this.isRenderable = isRenderable; 8722 this.data = parameters.data; 8723 this.layer = parameters.layer; 8724 this.page = parameters.page; 8725 this.viewport = parameters.viewport; 8726 this.linkService = parameters.linkService; 8727 this.downloadManager = parameters.downloadManager; 8728 this.imageResourcesPath = parameters.imageResourcesPath; 8729 this.renderInteractiveForms = parameters.renderInteractiveForms; 8730 this.svgFactory = parameters.svgFactory; 8731 this.annotationStorage = parameters.annotationStorage; 8732 this.enableScripting = parameters.enableScripting; 8733 this.hasJSActions = parameters.hasJSActions; 8734 this._mouseState = parameters.mouseState; 8735 8736 if (isRenderable) { 8737 this.container = this._createContainer(ignoreBorder); 8738 } 8739 8740 if (createQuadrilaterals) { 8741 this.quadrilaterals = this._createQuadrilaterals(ignoreBorder); 8742 } 8743 } 8744 8745 _createContainer(ignoreBorder = false) { 8746 const data = this.data, 8747 page = this.page, 8748 viewport = this.viewport; 8749 const container = document.createElement("section"); 8750 let width = data.rect[2] - data.rect[0]; 8751 let height = data.rect[3] - data.rect[1]; 8752 container.setAttribute("data-annotation-id", data.id); 8753 8754 const rect = _util.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]]); 8755 8756 container.style.transform = `matrix(${viewport.transform.join(",")})`; 8757 container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`; 8758 8759 if (!ignoreBorder && data.borderStyle.width > 0) { 8760 container.style.borderWidth = `${data.borderStyle.width}px`; 8761 8762 if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) { 8763 width -= 2 * data.borderStyle.width; 8764 height -= 2 * data.borderStyle.width; 8765 } 8766 8767 const horizontalRadius = data.borderStyle.horizontalCornerRadius; 8768 const verticalRadius = data.borderStyle.verticalCornerRadius; 8769 8770 if (horizontalRadius > 0 || verticalRadius > 0) { 8771 const radius = `${horizontalRadius}px / ${verticalRadius}px`; 8772 container.style.borderRadius = radius; 8773 } 8774 8775 switch (data.borderStyle.style) { 8776 case _util.AnnotationBorderStyleType.SOLID: 8777 container.style.borderStyle = "solid"; 8778 break; 8779 8780 case _util.AnnotationBorderStyleType.DASHED: 8781 container.style.borderStyle = "dashed"; 8782 break; 8783 8784 case _util.AnnotationBorderStyleType.BEVELED: 8785 (0, _util.warn)("Unimplemented border style: beveled"); 8786 break; 8787 8788 case _util.AnnotationBorderStyleType.INSET: 8789 (0, _util.warn)("Unimplemented border style: inset"); 8790 break; 8791 8792 case _util.AnnotationBorderStyleType.UNDERLINE: 8793 container.style.borderBottomStyle = "solid"; 8794 break; 8795 8796 default: 8797 break; 8798 } 8799 8800 if (data.color) { 8801 container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); 8802 } else { 8803 container.style.borderWidth = 0; 8804 } 8805 } 8806 8807 container.style.left = `${rect[0]}px`; 8808 container.style.top = `${rect[1]}px`; 8809 container.style.width = `${width}px`; 8810 container.style.height = `${height}px`; 8811 return container; 8812 } 8813 8814 _createQuadrilaterals(ignoreBorder = false) { 8815 if (!this.data.quadPoints) { 8816 return null; 8817 } 8818 8819 const quadrilaterals = []; 8820 const savedRect = this.data.rect; 8821 8822 for (const quadPoint of this.data.quadPoints) { 8823 this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y]; 8824 quadrilaterals.push(this._createContainer(ignoreBorder)); 8825 } 8826 8827 this.data.rect = savedRect; 8828 return quadrilaterals; 8829 } 8830 8831 _createPopup(trigger, data) {
8832 let container = this.container; 8833 8834 if (this.quadrilaterals) { 8835 trigger = trigger || this.quadrilaterals; 8836 container = this.quadrilaterals[0]; 8837 } 8838 8839 if (!trigger) { 8840 trigger = document.createElement("div"); 8841 trigger.style.height = container.style.height; 8842 trigger.style.width = container.style.width; 8843 container.appendChild(trigger); 8844 } 8845 8846 const popupElement = new PopupElement({ 8847 container, 8848 trigger, 8849 color: data.color, 8850 title: data.title, 8851 modificationDate: data.modificationDate, 8852 contents: data.contents, 8853 hideWrapper: true 8854 }); 8855 const popup = popupElement.render(); 8856 popup.style.left = container.style.width; 8857 container.appendChild(popup); 8858 } 8859 8860 _renderQuadrilaterals(className) { 8861 for (const quadrilateral of this.quadrilaterals) { 8862 quadrilateral.className = className; 8863 } 8864 8865 return this.quadrilaterals; 8866 } 8867 8868 render() { 8869 (0, _util.unreachable)("Abstract method `AnnotationElement.render` called"); 8870 } 8871 8872} 8873 8874class LinkAnnotationElement extends AnnotationElement { 8875 constructor(parameters) { 8876 const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"])); 8877 super(parameters, { 8878 isRenderable, 8879 createQuadrilaterals: true 8880 }); 8881 } 8882 8883 render() { 8884 const { 8885 data, 8886 linkService 8887 } = this; 8888 const link = document.createElement("a"); 8889 8890 if (data.url) { 8891 (0, _display_utils.addLinkAttributes)(link, { 8892 url: data.url, 8893 target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget, 8894 rel: linkService.externalLinkRel, 8895 enabled: linkService.externalLinkEnabled 8896 }); 8897 } else if (data.action) { 8898 this._bindNamedAction(link, data.action); 8899 } else if (data.dest) { 8900 this._bindLink(link, data.dest); 8901 } else if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { 8902 this._bindJSAction(link, data); 8903 } else { 8904 this._bindLink(link, ""); 8905 } 8906 8907 if (this.quadrilaterals) { 8908 return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => { 8909 const linkElement = index === 0 ? link : link.cloneNode(); 8910 quadrilateral.appendChild(linkElement); 8911 return quadrilateral; 8912 }); 8913 } 8914 8915 this.container.className = "linkAnnotation"; 8916 this.container.appendChild(link); 8917 return this.container; 8918 } 8919 8920 _bindLink(link, destination) { 8921 link.href = this.linkService.getDestinationHash(destination); 8922 8923 link.onclick = () => { 8924 if (destination) { 8925 this.linkService.goToDestination(destination); 8926 } 8927 8928 return false; 8929 }; 8930 8931 if (destination || destination === "") { 8932 link.className = "internalLink"; 8933 } 8934 } 8935 8936 _bindNamedAction(link, action) { 8937 link.href = this.linkService.getAnchorUrl(""); 8938 8939 link.onclick = () => { 8940 this.linkService.executeNamedAction(action); 8941 return false; 8942 }; 8943 8944 link.className = "internalLink"; 8945 } 8946 8947 _bindJSAction(link, data) { 8948 link.href = this.linkService.getAnchorUrl(""); 8949 const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); 8950 8951 for (const name of Object.keys(data.actions)) { 8952 const jsName = map.get(name); 8953 8954 if (!jsName) { 8955 continue; 8956 } 8957 8958 link[jsName] = () => { 8959 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 8960 source: this, 8961 detail: { 8962 id: data.id, 8963 name 8964 } 8965 }); 8966 return false; 8967 }; 8968 } 8969 8970 link.className = "internalLink"; 8971 } 8972 8973} 8974 8975class TextAnnotationElement extends AnnotationElement { 8976 constructor(parameters) { 8977 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 8978 super(parameters, { 8979 isRenderable 8980 }); 8981 } 8982 8983 render() { 8984 this.container.className = "textAnnotation"; 8985 const image = document.createElement("img"); 8986 image.style.height = this.container.style.height; 8987 image.style.width = this.container.style.width; 8988 image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; 8989 image.alt = "[{{type}} Annotation]"; 8990 image.dataset.l10nId = "text_annotation_type"; 8991 image.dataset.l10nArgs = JSON.stringify({ 8992 type: this.data.name 8993 }); 8994 8995 if (!this.data.hasPopup) { 8996 this._createPopup(image, this.data); 8997 } 8998 8999 this.container.appendChild(image); 9000 return this.container; 9001 } 9002 9003} 9004 9005class WidgetAnnotationElement extends AnnotationElement { 9006 render() { 9007 if (this.data.alternativeText) { 9008 this.container.title = this.data.alternativeText; 9009 } 9010 9011 return this.container; 9012 } 9013 9014 _getKeyModifier(event) { 9015 return navigator.platform.includes("Win") && event.ctrlKey || navigator.platform.includes("Mac") && event.metaKey; 9016 } 9017 9018 _setEventListener(element, baseName, eventName, valueGetter) { 9019 if (baseName.includes("mouse")) { 9020 element.addEventListener(baseName, event => { 9021 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 9022 source: this, 9023 detail: { 9024 id: this.data.id, 9025 name: eventName, 9026 value: valueGetter(event), 9027 shift: event.shiftKey, 9028 modifier: this._getKeyModifier(event) 9029 } 9030 }); 9031 }); 9032 } else { 9033 element.addEventListener(baseName, event => { 9034 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 9035 source: this, 9036 detail: { 9037 id: this.data.id, 9038 name: eventName, 9039 value: event.target.checked 9040 } 9041 }); 9042 }); 9043 } 9044 } 9045 9046 _setEventListeners(element, names, getter) { 9047 for (const [baseName, eventName] of names) { 9048 if (eventName === "Action" || this.data.actions?.[eventName]) { 9049 this._setEventListener(element, baseName, eventName, getter); 9050 } 9051 } 9052 } 9053 9054 _dispatchEventFromSandbox(actions, jsEvent) { 9055 const setColor = (jsName, styleName, event) => { 9056 const color = event.detail[jsName]; 9057 event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1)); 9058 }; 9059 9060 const commonActions = { 9061 display: event => { 9062 const hidden = event.detail.display % 2 === 1; 9063 event.target.style.visibility = hidden ? "hidden" : "visible"; 9064 this.annotationStorage.setValue(this.data.id, { 9065 hidden, 9066 print: event.detail.display === 0 || event.detail.display === 3 9067 }); 9068 }, 9069 print: event => { 9070 this.annotationStorage.setValue(this.data.id, { 9071 print: event.detail.print 9072 }); 9073 }, 9074 hidden: event => { 9075 event.target.style.visibility = event.detail.hidden ? "hidden" : "visible"; 9076 this.annotationStorage.setValue(this.data.id, { 9077 hidden: event.detail.hidden 9078 }); 9079 }, 9080 focus: event => { 9081 setTimeout(() =>
9081 event.target.focus({ 9082 preventScroll: false 9083 }), 0); 9084 }, 9085 userName: event => { 9086 event.target.title = event.detail.userName; 9087 }, 9088 readonly: event => { 9089 if (event.detail.readonly) { 9090 event.target.setAttribute("readonly", ""); 9091 } else { 9092 event.target.removeAttribute("readonly"); 9093 } 9094 }, 9095 required: event => { 9096 if (event.detail.required) { 9097 event.target.setAttribute("required", ""); 9098 } else { 9099 event.target.removeAttribute("required"); 9100 } 9101 }, 9102 bgColor: event => { 9103 setColor("bgColor", "backgroundColor", event); 9104 }, 9105 fillColor: event => { 9106 setColor("fillColor", "backgroundColor", event); 9107 }, 9108 fgColor: event => { 9109 setColor("fgColor", "color", event); 9110 }, 9111 textColor: event => { 9112 setColor("textColor", "color", event); 9113 }, 9114 borderColor: event => { 9115 setColor("borderColor", "borderColor", event); 9116 }, 9117 strokeColor: event => { 9118 setColor("strokeColor", "borderColor", event); 9119 } 9120 }; 9121 9122 for (const name of Object.keys(jsEvent.detail)) { 9123 const action = actions[name] || commonActions[name]; 9124 9125 if (action) { 9126 action(jsEvent); 9127 } 9128 } 9129 } 9130 9131} 9132 9133class TextWidgetAnnotationElement extends WidgetAnnotationElement { 9134 constructor(parameters) { 9135 const isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue; 9136 super(parameters, { 9137 isRenderable 9138 }); 9139 } 9140 9141 setPropertyOnSiblings(base, key, value, keyInStorage) { 9142 const storage = this.annotationStorage; 9143 9144 for (const element of document.getElementsByName(base.name)) { 9145 if (element !== base) { 9146 element[key] = value; 9147 const data = Object.create(null); 9148 data[keyInStorage] = value; 9149 storage.setValue(element.getAttribute("id"), data); 9150 } 9151 } 9152 } 9153 9154 render() { 9155 const storage = this.annotationStorage; 9156 const id = this.data.id; 9157 this.container.className = "textWidgetAnnotation"; 9158 let element = null; 9159 9160 if (this.renderInteractiveForms) { 9161 const storedData = storage.getValue(id, { 9162 value: this.data.fieldValue, 9163 valueAsString: this.data.fieldValue 9164 }); 9165 const textContent = storedData.valueAsString || storedData.value || ""; 9166 const elementData = { 9167 userValue: null, 9168 formattedValue: null, 9169 beforeInputSelectionRange: null, 9170 beforeInputValue: null 9171 }; 9172 9173 if (this.data.multiLine) { 9174 element = document.createElement("textarea"); 9175 element.textContent = textContent; 9176 } else { 9177 element = document.createElement("input"); 9178 element.type = "text"; 9179 element.setAttribute("value", textContent); 9180 } 9181 9182 elementData.userValue = textContent; 9183 element.setAttribute("id", id); 9184 element.addEventListener("input", event => { 9185 storage.setValue(id, { 9186 value: event.target.value 9187 }); 9188 this.setPropertyOnSiblings(element, "value", event.target.value, "value"); 9189 }); 9190 9191 let blurListener = event => { 9192 if (elementData.formattedValue) { 9193 event.target.value = elementData.formattedValue; 9194 } 9195 9196 event.target.scrollLeft = 0; 9197 elementData.beforeInputSelectionRange = null; 9198 }; 9199 9200 if (this.enableScripting && this.hasJSActions) { 9201 element.addEventListener("focus", event => { 9202 if (elementData.userValue) { 9203 event.target.value = elementData.userValue; 9204 } 9205 }); 9206 element.addEventListener("updatefromsandbox", jsEvent => { 9207 const actions = { 9208 value(event) { 9209 elementData.userValue = event.detail.value || ""; 9210 storage.setValue(id, { 9211 value: elementData.userValue.toString() 9212 }); 9213 9214 if (!elementData.formattedValue) { 9215 event.target.value = elementData.userValue; 9216 } 9217 }, 9218 9219 valueAsString(event) { 9220 elementData.formattedValue = event.detail.valueAsString || ""; 9221 9222 if (event.target !== document.activeElement) { 9223 event.target.value = elementData.formattedValue; 9224 } 9225 9226 storage.setValue(id, { 9227 formattedValue: elementData.formattedValue 9228 }); 9229 }, 9230 9231 selRange(event) { 9232 const [selStart, selEnd] = event.detail.selRange; 9233 9234 if (selStart >= 0 && selEnd < event.target.value.length) { 9235 event.target.setSelectionRange(selStart, selEnd); 9236 } 9237 } 9238 9239 }; 9240 9241 this._dispatchEventFromSandbox(actions, jsEvent); 9242 }); 9243 element.addEventListener("keydown", event => { 9244 elementData.beforeInputValue = event.target.value; 9245 let commitKey = -1; 9246 9247 if (event.key === "Escape") { 9248 commitKey = 0; 9249 } else if (event.key === "Enter") { 9250 commitKey = 2; 9251 } else if (event.key === "Tab") { 9252 commitKey = 3; 9253 } 9254 9255 if (commitKey === -1) { 9256 return; 9257 } 9258 9259 elementData.userValue = event.target.value; 9260 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 9261 source: this, 9262 detail: { 9263 id, 9264 name: "Keystroke", 9265 value: event.target.value, 9266 willCommit: true, 9267 commitKey, 9268 selStart: event.target.selectionStart, 9269 selEnd: event.target.selectionEnd 9270 } 9271 }); 9272 }); 9273 const _blurListener = blurListener; 9274 blurListener = null; 9275 element.addEventListener("blur", event => { 9276 if (this._mouseState.isDown) { 9277 elementData.userValue = event.target.value; 9278 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 9279 source: this, 9280 detail: { 9281 id, 9282 name: "Keystroke", 9283 value: event.target.value, 9284 willCommit: true, 9285 commitKey: 1, 9286 selStart: event.target.selectionStart, 9287 selEnd: event.target.selectionEnd 9288 } 9289 }); 9290 } 9291 9292 _blurListener(event); 9293 }); 9294 element.addEventListener("mousedown", event => { 9295 elementData.beforeInputValue = event.target.value; 9296 elementData.beforeInputSelectionRange = null; 9297 }); 9298 element.addEventListener("keyup", event => { 9299 if (event.target.selectionStart === event.target.selectionEnd) { 9300 elementData.beforeInputSelectionRange = null; 9301 } 9302 }); 9303 element.addEventListener("select", event => { 9304 elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd]; 9305 }); 9306 9307 if (this.data.actions?.Keystroke) { 9308 element.addEventListener("input", event => { 9309 let selStart = -1; 9310 let selEnd = -1; 9311 9312 if (elementData.beforeInputSelectionRange) { 9313 [selStart, selEnd] = elementData.beforeInputSelectionRange; 9314 } 9315 9316 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 9317 source: this, 9318 detail: { 9319 id, 9320 name: "Keystroke", 9321 value: elementData.beforeInputValue, 9322 change: event.data, 9323 willCommit: false, 9324 selStart, 9325 selEnd 9326 } 9327 }); 9328 }); 9329 } 9330 9331 this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value); 9332 } 9333 9334 if (blurListener) { 9335 element.addEventListener("blur", blurListener); 9336 } 9337 9338 element.disabled = this.data.readOnly; 9339 element.name = this.data.fieldName; 9340 9341 if (this.data.maxLen !== null) { 9342 element.maxLength = this.data.maxLen; 9343 } 9344 9345 if (this.data.comb) { 9346 const fieldWidth = this.data.rect[2] - this.data.rect[0]; 9347 const combWidth = fieldWidth / this.data.maxLen; 9348 element.classList.add("comb"); 9349 element.style.letterSpacing = `calc(${combWidth}px - 1ch)`; 9350 } 9351 } else { 9352 element = document.createElement("div"); 9353 element.textContent = this.data.fieldValue; 9354 element.style.verticalAlign = "middle"; 9355 element.style.display = "table-cell"; 9356 } 9357 9358 this._setTextStyle(element); 9359 9360 this.container.appendChild(element); 9361 return this.container; 9362 } 9363 9364 _setTextStyle(element) { 9365 const TEXT_ALIGNMENT = ["left", "center", "right"]; 9366 const { 9367 fontSize, 9368 fontColor 9369 } = this.data.defaultAppearanceData; 9370 const style = element.style; 9371 9372 if (fontSize) { 9373 style.fontSize = `${fontSize}px`; 9374 } 9375 9376 style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); 9377 9378 if (this.data.textAlignment !== null) { 9379 style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; 9380 } 9381 } 9382 9383} 9384 9385class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { 9386 constructor(parameters) { 9387 super(parameters, { 9388 isRenderable: parameters.renderInteractiveForms 9389 }); 9390 } 9391 9392 render() { 9393 const storage = this.annotationStorage; 9394 const data = this.data; 9395 const id = data.id; 9396 let value = storage.getValue(id, { 9397 value: data.fieldValue && (data.exportValue && data.exportValue === data.fieldValue || !data.exportValue && data.fieldValue !== "Off") 9398 }).value; 9399 9400 if (typeof value === "string") { 9401 value = value !== "Off"; 9402 storage.setValue(id, { 9403 value 9404 }); 9405 } 9406 9407 this.container.className = "buttonWidgetAnnotation checkBox"; 9408 const element = document.createElement("input"); 9409 element.disabled = data.readOnly; 9410 element.type = "checkbox"; 9411 element.name = this.data.fieldName; 9412 9413 if (value) { 9414 element.setAttribute("checked", true); 9415 } 9416 9417 element.setAttribute("id", id); 9418 element.addEventListener("change", function (event) { 9419 const name = event.target.name; 9420 9421 for (const checkbox of document.getElementsByName(name)) { 9422 if (checkbox !== event.target) { 9423 checkbox.checked = false;
9424 storage.setValue(checkbox.parentNode.getAttribute("data-annotation-id"), { 9425 value: false 9426 }); 9427 } 9428 } 9429 9430 storage.setValue(id, { 9431 value: event.target.checked 9432 }); 9433 }); 9434 9435 if (this.enableScripting && this.hasJSActions) { 9436 element.addEventListener("updatefromsandbox", jsEvent => { 9437 const actions = { 9438 value(event) { 9439 event.target.checked = event.detail.value !== "Off"; 9440 storage.setValue(id, { 9441 value: event.target.checked 9442 }); 9443 } 9444 9445 }; 9446 9447 this._dispatchEventFromSandbox(actions, jsEvent); 9448 }); 9449 9450 this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); 9451 } 9452 9453 this.container.appendChild(element); 9454 return this.container; 9455 } 9456 9457} 9458 9459class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement { 9460 constructor(parameters) { 9461 super(parameters, { 9462 isRenderable: parameters.renderInteractiveForms 9463 }); 9464 } 9465 9466 render() { 9467 this.container.className = "buttonWidgetAnnotation radioButton"; 9468 const storage = this.annotationStorage; 9469 const data = this.data; 9470 const id = data.id; 9471 let value = storage.getValue(id, { 9472 value: data.fieldValue === data.buttonValue 9473 }).value; 9474 9475 if (typeof value === "string") { 9476 value = value !== data.buttonValue; 9477 storage.setValue(id, { 9478 value 9479 }); 9480 } 9481 9482 const element = document.createElement("input"); 9483 element.disabled = data.readOnly; 9484 element.type = "radio"; 9485 element.name = data.fieldName; 9486 9487 if (value) { 9488 element.setAttribute("checked", true); 9489 } 9490 9491 element.setAttribute("id", id); 9492 element.addEventListener("change", function (event) { 9493 const { 9494 target 9495 } = event; 9496 9497 for (const radio of document.getElementsByName(target.name)) { 9498 if (radio !== target) { 9499 storage.setValue(radio.getAttribute("id"), { 9500 value: false 9501 }); 9502 } 9503 } 9504 9505 storage.setValue(id, { 9506 value: target.checked 9507 }); 9508 }); 9509 9510 if (this.enableScripting && this.hasJSActions) { 9511 const pdfButtonValue = data.buttonValue; 9512 element.addEventListener("updatefromsandbox", jsEvent => { 9513 const actions = { 9514 value(event) { 9515 const checked = pdfButtonValue === event.detail.value; 9516 9517 for (const radio of document.getElementsByName(event.target.name)) { 9518 const radioId = radio.getAttribute("id"); 9519 radio.checked = radioId === id && checked; 9520 storage.setValue(radioId, { 9521 value: radio.checked 9522 }); 9523 } 9524 } 9525 9526 }; 9527 9528 this._dispatchEventFromSandbox(actions, jsEvent); 9529 }); 9530 9531 this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); 9532 } 9533 9534 this.container.appendChild(element); 9535 return this.container; 9536 } 9537 9538} 9539 9540class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { 9541 render() { 9542 const container = super.render(); 9543 container.className = "buttonWidgetAnnotation pushButton"; 9544 9545 if (this.data.alternativeText) { 9546 container.title = this.data.alternativeText; 9547 } 9548 9549 return container; 9550 } 9551 9552} 9553 9554class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { 9555 constructor(parameters) { 9556 super(parameters, { 9557 isRenderable: parameters.renderInteractiveForms 9558 }); 9559 } 9560 9561 render() { 9562 this.container.className = "choiceWidgetAnnotation"; 9563 const storage = this.annotationStorage; 9564 const id = this.data.id; 9565 storage.getValue(id, { 9566 value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined 9567 }); 9568 const selectElement = document.createElement("select"); 9569 selectElement.disabled = this.data.readOnly; 9570 selectElement.name = this.data.fieldName; 9571 selectElement.setAttribute("id", id); 9572 9573 if (!this.data.combo) { 9574 selectElement.size = this.data.options.length; 9575 9576 if (this.data.multiSelect) { 9577 selectElement.multiple = true; 9578 } 9579 } 9580 9581 for (const option of this.data.options) { 9582 const optionElement = document.createElement("option"); 9583 optionElement.textContent = option.displayValue; 9584 optionElement.value = option.exportValue; 9585 9586 if (this.data.fieldValue.includes(option.exportValue)) { 9587 optionElement.setAttribute("selected", true); 9588 } 9589 9590 selectElement.appendChild(optionElement); 9591 } 9592 9593 const getValue = (event, isExport) => { 9594 const name = isExport ? "value" : "textContent"; 9595 const options = event.target.options; 9596 9597 if (!event.target.multiple) { 9598 return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; 9599 } 9600 9601 return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]); 9602 }; 9603 9604 const getItems = event => { 9605 const options = event.target.options; 9606 return Array.prototype.map.call(options, option => { 9607 return { 9608 displayValue: option.textContent, 9609 exportValue: option.value 9610 }; 9611 }); 9612 }; 9613 9614 if (this.enableScripting && this.hasJSActions) { 9615 selectElement.addEventListener("updatefromsandbox", jsEvent => { 9616 const actions = { 9617 value(event) { 9618 const options = selectElement.options; 9619 const value = event.detail.value; 9620 const values = new Set(Array.isArray(value) ? value : [value]); 9621 Array.prototype.forEach.call(options, option => { 9622 option.selected = values.has(option.value); 9623 }); 9624 storage.setValue(id, { 9625 value: getValue(event, true) 9626 }); 9627 }, 9628 9629 multipleSelection(event) { 9630 selectElement.multiple = true; 9631 }, 9632 9633 remove(event) { 9634 const options = selectElement.options; 9635 const index = event.detail.remove; 9636 options[index].selected = false;
9637 selectElement.remove(index); 9638 9639 if (options.length > 0) { 9640 const i = Array.prototype.findIndex.call(options, option => option.selected); 9641 9642 if (i === -1) { 9643 options[0].selected = true; 9644 } 9645 } 9646 9647 storage.setValue(id, { 9648 value: getValue(event, true), 9649 items: getItems(event) 9650 }); 9651 }, 9652 9653 clear(event) { 9654 while (selectElement.length !== 0) { 9655 selectElement.remove(0); 9656 } 9657 9658 storage.setValue(id, { 9659 value: null, 9660 items: [] 9661 }); 9662 }, 9663 9664 insert(event) { 9665 const { 9666 index, 9667 displayValue, 9668 exportValue 9669 } = event.detail.insert; 9670 const optionElement = document.createElement("option"); 9671 optionElement.textContent = displayValue; 9672 optionElement.value = exportValue; 9673 selectElement.insertBefore(optionElement, selectElement.children[index]); 9674 storage.setValue(id, { 9675 value: getValue(event, true), 9676 items: getItems(event) 9677 }); 9678 }, 9679 9680 items(event) { 9681 const { 9682 items 9683 } = event.detail; 9684 9685 while (selectElement.length !== 0) { 9686 selectElement.remove(0); 9687 } 9688 9689 for (const item of items) { 9690 const { 9691 displayValue, 9692 exportValue 9693 } = item; 9694 const optionElement = document.createElement("option"); 9695 optionElement.textContent = displayValue; 9696 optionElement.value = exportValue; 9697 selectElement.appendChild(optionElement); 9698 } 9699 9700 if (selectElement.options.length > 0) { 9701 selectElement.options[0].selected = true; 9702 } 9703 9704 storage.setValue(id, { 9705 value: getValue(event, true), 9706 items: getItems(event) 9707 }); 9708 }, 9709 9710 indices(event) { 9711 const indices = new Set(event.detail.indices); 9712 const options = event.target.options; 9713 Array.prototype.forEach.call(options, (option, i) => { 9714 option.selected = indices.has(i); 9715 }); 9716 storage.setValue(id, { 9717 value: getValue(event, true) 9718 }); 9719 }, 9720 9721 editable(event) { 9722 event.target.disabled = !event.detail.editable; 9723 } 9724 9725 }; 9726 9727 this._dispatchEventFromSandbox(actions, jsEvent); 9728 }); 9729 selectElement.addEventListener("input", event => { 9730 const exportValue = getValue(event, true); 9731 const value = getValue(event, false); 9732 storage.setValue(id, { 9733 value: exportValue 9734 }); 9735 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { 9736 source: this, 9737 detail: { 9738 id, 9739 name: "Keystroke", 9740 value, 9741 changeEx: exportValue, 9742 willCommit: true, 9743 commitKey: 1, 9744 keyDown: false 9745 } 9746 }); 9747 }); 9748 9749 this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"]], event => event.target.checked); 9750 } else { 9751 selectElement.addEventListener("input", function (event) { 9752 storage.setValue(id, { 9753 value: getValue(event) 9754 }); 9755 }); 9756 } 9757 9758 this.container.appendChild(selectElement); 9759 return this.container; 9760 } 9761 9762} 9763 9764class PopupAnnotationElement extends AnnotationElement { 9765 constructor(parameters) { 9766 const isRenderable = !!(parameters.data.title || parameters.data.contents); 9767 super(parameters, { 9768 isRenderable 9769 }); 9770 } 9771 9772 render() { 9773 const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]; 9774 this.container.className = "popupAnnotation"; 9775 9776 if (IGNORE_TYPES.includes(this.data.parentType)) { 9777 return this.container; 9778 } 9779 9780 const selector = `[data-annotation-id="${this.data.parentId}"]`; 9781 const parentElements = this.layer.querySelectorAll(selector); 9782 9783 if (parentElements.length === 0) { 9784 return this.container; 9785 } 9786 9787 const popup = new PopupElement({ 9788 container: this.container, 9789 trigger: Array.from(parentElements), 9790 color: this.data.color, 9791 title: this.data.title, 9792 modificationDate: this.data.modificationDate, 9793 contents: this.data.contents 9794 }); 9795 const page = this.page; 9796 9797 const rect = _util.Util.normalizeRect([this.data.parentRect[0], page.view[3] - this.data.parentRect[1] + page.view[1], this.data.parentRect[2], page.view[3] - this.data.parentRect[3] + page.view[1]]); 9798 9799 const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0]; 9800 const popupTop = rect[1]; 9801 this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}
9801px`; 9802 this.container.style.left = `${popupLeft}px`; 9803 this.container.style.top = `${popupTop}px`; 9804 this.container.appendChild(popup.render()); 9805 return this.container; 9806 } 9807 9808} 9809 9810class PopupElement { 9811 constructor(parameters) { 9812 this.container = parameters.container; 9813 this.trigger = parameters.trigger; 9814 this.color = parameters.color; 9815 this.title = parameters.title; 9816 this.modificationDate = parameters.modificationDate; 9817 this.contents = parameters.contents; 9818 this.hideWrapper = parameters.hideWrapper || false; 9819 this.pinned = false; 9820 } 9821 9822 render() { 9823 const BACKGROUND_ENLIGHT = 0.7; 9824 const wrapper = document.createElement("div"); 9825 wrapper.className = "popupWrapper"; 9826 this.hideElement = this.hideWrapper ? wrapper : this.container; 9827 this.hideElement.hidden = true; 9828 const popup = document.createElement("div"); 9829 popup.className = "popup"; 9830 const color = this.color; 9831 9832 if (color) { 9833 const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; 9834 const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; 9835 const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; 9836 popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0); 9837 } 9838 9839 const title = document.createElement("h1"); 9840 title.textContent = this.title; 9841 popup.appendChild(title); 9842 9843 const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate); 9844 9845 if (dateObject) { 9846 const modificationDate = document.createElement("span"); 9847 modificationDate.textContent = "{{date}}, {{time}}"; 9848 modificationDate.dataset.l10nId = "annotation_date_string"; 9849 modificationDate.dataset.l10nArgs = JSON.stringify({ 9850 date: dateObject.toLocaleDateString(), 9851 time: dateObject.toLocaleTimeString() 9852 }); 9853 popup.appendChild(modificationDate); 9854 } 9855 9856 const contents = this._formatContents(this.contents); 9857 9858 popup.appendChild(contents); 9859 9860 if (!Array.isArray(this.trigger)) { 9861 this.trigger = [this.trigger]; 9862 } 9863 9864 for (const element of this.trigger) { 9865 element.addEventListener("click", this._toggle.bind(this)); 9866 element.addEventListener("mouseover", this._show.bind(this, false)); 9867 element.addEventListener("mouseout", this._hide.bind(this, false)); 9868 } 9869 9870 popup.addEventListener("click", this._hide.bind(this, true)); 9871 wrapper.appendChild(popup); 9872 return wrapper; 9873 } 9874 9875 _formatContents(contents) { 9876 const p = document.createElement("p"); 9877 const lines = contents.split(/(?:\r\n?|\n)/); 9878 9879 for (let i = 0, ii = lines.length; i < ii; ++i) { 9880 const line = lines[i]; 9881 p.appendChild(document.createTextNode(line)); 9882 9883 if (i < ii - 1) { 9884 p.appendChild(document.createElement("br")); 9885 } 9886 } 9887 9888 return p; 9889 } 9890 9891 _toggle() { 9892 if (this.pinned) { 9893 this._hide(true); 9894 } else { 9895 this._show(true); 9896 } 9897 } 9898 9899 _show(pin = false) { 9900 if (pin) { 9901 this.pinned = true; 9902 } 9903 9904 if (this.hideElement.hidden) { 9905 this.hideElement.hidden = false; 9906 this.container.style.zIndex += 1; 9907 } 9908 } 9909 9910 _hide(unpin = true) { 9911 if (unpin) { 9912 this.pinned = false; 9913 } 9914 9915 if (!this.hideElement.hidden && !this.pinned) { 9916 this.hideElement.hidden = true; 9917 this.container.style.zIndex -= 1; 9918 } 9919 } 9920 9921} 9922 9923class FreeTextAnnotationElement extends AnnotationElement { 9924 constructor(parameters) { 9925 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 9926 super(parameters, { 9927 isRenderable, 9928 ignoreBorder: true 9929 }); 9930 } 9931 9932 render() { 9933 this.container.className = "freeTextAnnotation"; 9934 9935 if (!this.data.hasPopup) { 9936 this._createPopup(null, this.data); 9937 } 9938 9939 return this.container; 9940 } 9941 9942} 9943 9944class LineAnnotationElement extends AnnotationElement { 9945 constructor(parameters) { 9946 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 9947 super(parameters, { 9948 isRenderable, 9949 ignoreBorder: true 9950 }); 9951 } 9952 9953 render() { 9954 this.container.className = "lineAnnotation"; 9955 const data = this.data; 9956 const width = data.rect[2] - data.rect[0]; 9957 const height = data.rect[3] - data.rect[1]; 9958 const svg = this.svgFactory.create(width, height); 9959 const line = this.svgFactory.createElement("svg:line"); 9960 line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); 9961 line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); 9962 line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); 9963 line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); 9964 line.setAttribute("stroke-width", data.borderStyle.width || 1); 9965 line.setAttribute("stroke", "transparent"); 9966 svg.appendChild(line); 9967 this.container.append(svg); 9968 9969 this._createPopup(line, data); 9970 9971 return this.container; 9972 } 9973 9974} 9975 9976class SquareAnnotationElement extends AnnotationElement { 9977 constructor(parameters) { 9978 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 9979 super(parameters, { 9980 isRenderable, 9981 ignoreBorder: true 9982 }); 9983 } 9984 9985 render() { 9986 this.container.className = "squareAnnotation"; 9987 const data = this.data; 9988 const width = data.rect[2] - data.rect[0]; 9989 const height = data.rect[3] - data.rect[1]; 9990 const svg = this.svgFactory.create(width, height); 9991 const borderWidth = data.borderStyle.width; 9992 const square = this.svgFactory.createElement("svg:rect"); 9993 square.setAttribute("x", borderWidth / 2); 9994 square.setAttribute("y", borderWidth / 2); 9995 square.setAttribute("width", width - borderWidth); 9996 square.setAttribute("height", height - borderWidth); 9997 square.setAttribute("stroke-width", borderWidth || 1); 9998 square.setAttribute("stroke", "transparent"); 9999 square.setAttribute("fill", "none"); 10000 svg.appendChild(square); 10001 this.container.append(svg); 10002 10003 this._createPopup(square, data); 10004 10005 return this.container; 10006 } 10007 10008} 10009 10010class CircleAnnotationElement extends AnnotationElement { 10011 constructor(parameters) { 10012 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10013 super(parameters, { 10014 isRenderable, 10015 ignoreBorder: true 10016 }); 10017 } 10018 10019 render() { 10020 this.container.className = "circleAnnotation"; 10021 const data = this.data; 10022 const width = data.rect[2] - data.rect[0]; 10023 const height = data.rect[3] - data.rect[1]; 10024 const svg = this.svgFactory.create(width, height); 10025 const borderWidth = data.borderStyle.width; 10026 const circle = this.svgFactory.createElement("svg:ellipse"); 10027 circle.setAttribute("cx", width / 2); 10028 circle.setAttribute("cy", height / 2); 10029 circle.setAttribute("rx", width / 2 - borderWidth / 2); 10030 circle.setAttribute("ry", height / 2 - borderWidth / 2); 10031 circle.setAttribute("stroke-width", borderWidth || 1); 10032 circle.setAttribute("stroke", "transparent"); 10033 circle.setAttribute("fill", "none"); 10034 svg.appendChild(circle); 10035 this.container.append(svg); 10036 10037 this._createPopup(circle, data); 10038 10039 return this.container; 10040 } 10041 10042} 10043 10044class PolylineAnnotationElement extends AnnotationElement { 10045 constructor(parameters) { 10046 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10047 super(parameters, { 10048 isRenderable, 10049 ignoreBorder: true 10050 }); 10051 this.containerClassName = "polylineAnnotation"; 10052 this.svgElementName = "svg:polyline"; 10053 } 10054 10055 render() { 10056 this.container.className = this.containerClassName; 10057 const data = this.data; 10058 const width = data.rect[2] - data.rect[0]; 10059 const height = data.rect[3] - data.rect[1]; 10060 const svg = this.svgFactory.create(width, height); 10061 let points = []; 10062 10063 for (const coordinate of data.vertices) { 10064 const x = coordinate.x - data.rect[0];
10065 const y = data.rect[3] - coordinate.y; 10066 points.push(x + "," + y); 10067 } 10068 10069 points = points.join(" "); 10070 const polyline = this.svgFactory.createElement(this.svgElementName); 10071 polyline.setAttribute("points", points); 10072 polyline.setAttribute("stroke-width", data.borderStyle.width || 1); 10073 polyline.setAttribute("stroke", "transparent"); 10074 polyline.setAttribute("fill", "none"); 10075 svg.appendChild(polyline); 10076 this.container.append(svg); 10077 10078 this._createPopup(polyline, data); 10079 10080 return this.container; 10081 } 10082 10083} 10084 10085class PolygonAnnotationElement extends PolylineAnnotationElement { 10086 constructor(parameters) { 10087 super(parameters); 10088 this.containerClassName = "polygonAnnotation"; 10089 this.svgElementName = "svg:polygon"; 10090 } 10091 10092} 10093 10094class CaretAnnotationElement extends AnnotationElement { 10095 constructor(parameters) { 10096 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10097 super(parameters, { 10098 isRenderable, 10099 ignoreBorder: true 10100 }); 10101 } 10102 10103 render() { 10104 this.container.className = "caretAnnotation"; 10105 10106 if (!this.data.hasPopup) { 10107 this._createPopup(null, this.data); 10108 } 10109 10110 return this.container; 10111 } 10112 10113} 10114 10115class InkAnnotationElement extends AnnotationElement { 10116 constructor(parameters) { 10117 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10118 super(parameters, { 10119 isRenderable, 10120 ignoreBorder: true 10121 }); 10122 this.containerClassName = "inkAnnotation"; 10123 this.svgElementName = "svg:polyline"; 10124 } 10125 10126 render() { 10127 this.container.className = this.containerClassName; 10128 const data = this.data; 10129 const width = data.rect[2] - data.rect[0]; 10130 const height = data.rect[3] - data.rect[1]; 10131 const svg = this.svgFactory.create(width, height); 10132 10133 for (const inkList of data.inkLists) { 10134 let points = []; 10135 10136 for (const coordinate of inkList) { 10137 const x = coordinate.x - data.rect[0]; 10138 const y = data.rect[3] - coordinate.y; 10139 points.push(`${x},${y}`); 10140 } 10141 10142 points = points.join(" "); 10143 const polyline = this.svgFactory.createElement(this.svgElementName); 10144 polyline.setAttribute("points", points); 10145 polyline.setAttribute("stroke-width", data.borderStyle.width || 1); 10146 polyline.setAttribute("stroke", "transparent"); 10147 polyline.setAttribute("fill", "none"); 10148 10149 this._createPopup(polyline, data); 10150 10151 svg.appendChild(polyline); 10152 } 10153 10154 this.container.append(svg); 10155 return this.container; 10156 } 10157 10158} 10159 10160class HighlightAnnotationElement extends AnnotationElement { 10161 constructor(parameters) { 10162 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10163 super(parameters, { 10164 isRenderable, 10165 ignoreBorder: true, 10166 createQuadrilaterals: true 10167 }); 10168 } 10169 10170 render() { 10171 if (!this.data.hasPopup) { 10172 this._createPopup(null, this.data); 10173 } 10174 10175 if (this.quadrilaterals) { 10176 return this._renderQuadrilaterals("highlightAnnotation"); 10177 } 10178 10179 this.container.className = "highlightAnnotation"; 10180 return this.container; 10181 } 10182 10183} 10184 10185class UnderlineAnnotationElement extends AnnotationElement { 10186 constructor(parameters) { 10187 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10188 super(parameters, { 10189 isRenderable, 10190 ignoreBorder: true, 10191 createQuadrilaterals: true 10192 }); 10193 } 10194 10195 render() { 10196 if (!this.data.hasPopup) { 10197 this._createPopup(null, this.data); 10198 } 10199 10200 if (this.quadrilaterals) { 10201 return this._renderQuadrilaterals("underlineAnnotation"); 10202 } 10203 10204 this.container.className = "underlineAnnotation"; 10205 return this.container; 10206 } 10207 10208} 10209 10210class SquigglyAnnotationElement extends AnnotationElement { 10211 constructor(parameters) { 10212 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10213 super(parameters, { 10214 isRenderable, 10215 ignoreBorder: true, 10216 createQuadrilaterals: true 10217 }); 10218 } 10219 10220 render() { 10221 if (!this.data.hasPopup) { 10222 this._createPopup(null, this.data); 10223 } 10224 10225 if (this.quadrilaterals) { 10226 return this._renderQuadrilaterals("squigglyAnnotation"); 10227 } 10228 10229 this.container.className = "squigglyAnnotation"; 10230 return this.container; 10231 } 10232 10233} 10234 10235class StrikeOutAnnotationElement extends AnnotationElement { 10236 constructor(parameters) { 10237 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10238 super(parameters, { 10239 isRenderable, 10240 ignoreBorder: true, 10241 createQuadrilaterals: true 10242 }); 10243 } 10244 10245 render() { 10246 if (!this.data.hasPopup) { 10247 this._createPopup(null, this.data); 10248 } 10249 10250 if (this.quadrilaterals) { 10251 return this._renderQuadrilaterals("strikeoutAnnotation"); 10252 } 10253 10254 this.container.className = "strikeoutAnnotation"; 10255 return this.container; 10256 } 10257 10258} 10259 10260class StampAnnotationElement extends AnnotationElement { 10261 constructor(parameters) { 10262 const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); 10263 super(parameters, { 10264 isRenderable, 10265 ignoreBorder: true 10266 }); 10267 } 10268 10269 render() { 10270 this.container.className = "stampAnnotation"; 10271 10272 if (!this.data.hasPopup) { 10273 this._createPopup(null, this.data); 10274 } 10275 10276 return this.container; 10277 } 10278 10279} 10280 10281class FileAttachmentAnnotationElement extends AnnotationElement { 10282 constructor(parameters) { 10283 super(parameters, { 10284 isRenderable: true 10285 }); 10286 const { 10287 filename, 10288 content 10289 } = this.data.file; 10290 this.filename = (0, _display_utils.getFilenameFromUrl)(filename); 10291 this.content = content; 10292 this.linkService.eventBus?.dispatch("fileattachmentannotation", { 10293 source: this, 10294 id: (0, _util.stringToPDFString)(filename), 10295 filename, 10296 content 10297 }); 10298 } 10299 10300 render() { 10301 this.container.className = "fileAttachmentAnnotation"; 10302 const trigger = document.createElement("div"); 10303 trigger.style.height = this.container.style.height; 10304 trigger.style.width = this.container.style.width; 10305 trigger.addEventListener("dblclick", this._download.bind(this)); 10306 10307 if (!this.data.hasPopup && (this.data.title || this.data.contents)) { 10308 this._createPopup(trigger, this.data); 10309 } 10310 10311 this.container.appendChild(trigger); 10312 return this.container; 10313 } 10314 10315 _download() { 10316 this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename); 10317 } 10318 10319} 10320 10321class AnnotationLayer { 10322 static render(parameters) { 10323 const sortedAnnotations = [], 10324 popupAnnotations = []; 10325 10326 for (const data of parameters.annotations) { 10327 if (!data) { 10328 continue; 10329 } 10330 10331 if (data.annotationType === _util.AnnotationType.POPUP) { 10332 popupAnnotations.push(data); 10333 continue; 10334 } 10335 10336 sortedAnnotations.push(data); 10337 } 10338 10339 if (popupAnnotations.length) { 10340 sortedAnnotations.push(...popupAnnotations); 10341 } 10342 10343 for (const data of sortedAnnotations) { 10344 const element = AnnotationElementFactory.create({ 10345 data, 10346 layer: parameters.div, 10347 page: parameters.page, 10348 viewport: parameters.viewport, 10349 linkService: parameters.linkService, 10350 downloadManager: parameters.downloadManager, 10351 imageResourcesPath: parameters.imageResourcesPath || "", 10352 renderInteractiveForms: parameters.renderInteractiveForms !== false, 10353 svgFactory: new _display_utils.DOMSVGFactory(), 10354 annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(), 10355 enableScripting: parameters.enableScripting, 10356 hasJSActions: parameters.hasJSActions, 10357 mouseState: parameters.mouseState || { 10358 isDown: false 10359 } 10360 }); 10361 10362 if (element.isRenderable) { 10363 const rendered = element.render(); 10364 10365 if (data.hidden) { 10366 rendered.style.visibility = "hidden"; 10367 } 10368 10369 if (Array.isArray(rendered)) { 10370 for (const renderedElement of rendered) { 10371 parameters.div.appendChild(renderedElement); 10372 } 10373 } else { 10374 if (element instanceof PopupAnnotationElement) { 10375 parameters.div.prepend(rendered); 10376 } else { 10377 parameters.div.appendChild(rendered); 10378 } 10379 } 10380 } 10381 } 10382 } 10383 10384 static update(parameters) { 10385 const transform = `matrix(${parameters.viewport.transform.join(",")})`; 10386 10387 for (const data of parameters.annotations) { 10388 const elements = parameters.div.querySelectorAll(`[data-annotation-id="${data.id}"]`); 10389 10390 if (elements) { 10391 for (const element of elements) { 10392 element.style.transform = transform; 10393 } 10394 } 10395 } 10396 10397 parameters.div.hidden = false;
10398 } 10399 10400} 10401 10402exports.AnnotationLayer = AnnotationLayer; 10403 10404/***/ }), 10405/* 18 */ 10406/***/ ((__unused_webpack_module, exports) => { 10407 10408 10409 10410Object.defineProperty(exports, "__esModule", ({ 10411 value: true 10412})); 10413exports.ColorConverters = void 0; 10414 10415function makeColorComp(n) { 10416 return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0"); 10417} 10418 10419class ColorConverters { 10420 static CMYK_G([c, y, m, k]) { 10421 return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)]; 10422 } 10423 10424 static G_CMYK([g]) { 10425 return ["CMYK", 0, 0, 0, 1 - g]; 10426 } 10427 10428 static G_RGB([g]) { 10429 return ["RGB", g, g, g]; 10430 } 10431 10432 static G_HTML([g]) { 10433 const G = makeColorComp(g); 10434 return `#${G}${G}${G}`; 10435 } 10436 10437 static RGB_G([r, g, b]) { 10438 return ["G", 0.3 * r + 0.59 * g + 0.11 * b]; 10439 } 10440 10441 static RGB_HTML([r, g, b]) { 10442 const R = makeColorComp(r); 10443 const G = makeColorComp(g); 10444 const B = makeColorComp(b); 10445 return `#${R}${G}${B}`; 10446 } 10447 10448 static T_HTML() { 10449 return "#00000000"; 10450 } 10451 10452 static CMYK_RGB([c, y, m, k]) { 10453 return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)]; 10454 } 10455 10456 static CMYK_HTML(components) { 10457 return this.RGB_HTML(this.CMYK_RGB(components)); 10458 } 10459 10460 static RGB_CMYK([r, g, b]) { 10461 const c = 1 - r; 10462 const m = 1 - g; 10463 const y = 1 - b; 10464 const k = Math.min(c, m, y); 10465 return ["CMYK", c, m, y, k]; 10466 } 10467 10468} 10469 10470exports.ColorConverters = ColorConverters; 10471 10472/***/ }), 10473/* 19 */ 10474/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 10475 10476 10477 10478Object.defineProperty(exports, "__esModule", ({ 10479 value: true 10480})); 10481exports.renderTextLayer = renderTextLayer; 10482 10483var _util = __w_pdfjs_require__(2); 10484 10485const MAX_TEXT_DIVS_TO_RENDER = 100000; 10486const DEFAULT_FONT_SIZE = 30; 10487const DEFAULT_FONT_ASCENT = 0.8; 10488const ascentCache = new Map(); 10489const AllWhitespaceRegexp = /^\s+$/g; 10490 10491function getAscent(fontFamily, ctx) { 10492 const cachedAscent = ascentCache.get(fontFamily); 10493 10494 if (cachedAscent) { 10495 return cachedAscent; 10496 } 10497 10498 ctx.save(); 10499 ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`; 10500 const metrics = ctx.measureText(""); 10501 let ascent = metrics.fontBoundingBoxAscent; 10502 let descent = Math.abs(metrics.fontBoundingBoxDescent); 10503 10504 if (ascent) { 10505 ctx.restore(); 10506 const ratio = ascent / (ascent + descent); 10507 ascentCache.set(fontFamily, ratio); 10508 return ratio; 10509 } 10510 10511 ctx.strokeStyle = "red"; 10512 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); 10513 ctx.strokeText("g", 0, 0); 10514 let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; 10515 descent = 0; 10516 10517 for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) { 10518 if (pixels[i] > 0) { 10519 descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE); 10520 break; 10521 } 10522 } 10523 10524 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); 10525 ctx.strokeText("A", 0, DEFAULT_FONT_SIZE); 10526 pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; 10527 ascent = 0; 10528 10529 for (let i = 0, ii = pixels.length; i < ii; i += 4) { 10530 if (pixels[i] > 0) { 10531 ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE); 10532 break; 10533 } 10534 } 10535 10536 ctx.restore(); 10537 10538 if (ascent) { 10539 const ratio = ascent / (ascent + descent); 10540 ascentCache.set(fontFamily, ratio); 10541 return ratio; 10542 } 10543 10544 ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT); 10545 return DEFAULT_FONT_ASCENT; 10546} 10547 10548function appendText(task, geom, styles, ctx) { 10549 const textDiv = document.createElement("span"); 10550 const textDivProperties = { 10551 angle: 0, 10552 canvasWidth: 0, 10553 hasText: geom.str !== "", 10554 hasEOL: geom.hasEOL, 10555 originalTransform: null, 10556 paddingBottom: 0, 10557 paddingLeft: 0, 10558 paddingRight: 0, 10559 paddingTop: 0, 10560 scale: 1 10561 }; 10562 10563 task._textDivs.push(textDiv); 10564 10565 const tx = _util.Util.transform(task._viewport.transform, geom.transform); 10566 10567 let angle = Math.atan2(tx[1], tx[0]); 10568 const style = styles[geom.fontName]; 10569 10570 if (style.vertical) { 10571 angle += Math.PI / 2; 10572 } 10573 10574 const fontHeight = Math.hypot(tx[2], tx[3]); 10575 const fontAscent = fontHeight * getAscent(style.fontFamily, ctx); 10576 let left, top; 10577 10578 if (angle === 0) { 10579 left = tx[4]; 10580 top = tx[5] - fontAscent; 10581 } else { 10582 left = tx[4] + fontAscent * Math.sin(angle); 10583 top = tx[5] - fontAscent * Math.cos(angle); 10584 } 10585 10586 textDiv.style.left = `${left}px`; 10587 textDiv.style.top = `${top}px`; 10588 textDiv.style.fontSize = `${fontHeight}px`; 10589 textDiv.style.fontFamily = style.fontFamily; 10590 textDiv.setAttribute("role", "presentation"); 10591 textDiv.textContent = geom.str; 10592 textDiv.dir = geom.dir; 10593 10594 if (task._fontInspectorEnabled) { 10595 textDiv.dataset.fontName = geom.fontName; 10596 } 10597 10598 if (angle !== 0) { 10599 textDivProperties.angle = angle * (180 / Math.PI); 10600 } 10601 10602 let shouldScaleText = false;
10603 10604 if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) { 10605 shouldScaleText = true; 10606 } else if (geom.transform[0] !== geom.transform[3]) { 10607 const absScaleX = Math.abs(geom.transform[0]), 10608 absScaleY = Math.abs(geom.transform[3]); 10609 10610 if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { 10611 shouldScaleText = true; 10612 } 10613 } 10614 10615 if (shouldScaleText) { 10616 if (style.vertical) { 10617 textDivProperties.canvasWidth = geom.height * task._viewport.scale; 10618 } else { 10619 textDivProperties.canvasWidth = geom.width * task._viewport.scale; 10620 } 10621 } 10622 10623 task._textDivProperties.set(textDiv, textDivProperties); 10624 10625 if (task._textContentStream) { 10626 task._layoutText(textDiv); 10627 } 10628 10629 if (task._enhanceTextSelection && textDivProperties.hasText) { 10630 let angleCos = 1, 10631 angleSin = 0; 10632 10633 if (angle !== 0) { 10634 angleCos = Math.cos(angle); 10635 angleSin = Math.sin(angle); 10636 } 10637 10638 const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale; 10639 const divHeight = fontHeight; 10640 let m, b; 10641 10642 if (angle !== 0) { 10643 m = [angleCos, angleSin, -angleSin, angleCos, left, top]; 10644 b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m); 10645 } else { 10646 b = [left, top, left + divWidth, top + divHeight]; 10647 } 10648 10649 task._bounds.push({ 10650 left: b[0], 10651 top: b[1], 10652 right: b[2], 10653 bottom: b[3], 10654 div: textDiv, 10655 size: [divWidth, divHeight], 10656 m 10657 }); 10658 } 10659} 10660 10661function render(task) { 10662 if (task._canceled) { 10663 return; 10664 } 10665 10666 const textDivs = task._textDivs; 10667 const capability = task._capability; 10668 const textDivsLength = textDivs.length; 10669 10670 if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { 10671 task._renderingDone = true; 10672 capability.resolve(); 10673 return; 10674 } 10675 10676 if (!task._textContentStream) { 10677 for (let i = 0; i < textDivsLength; i++) { 10678 task._layoutText(textDivs[i]); 10679 } 10680 } 10681 10682 task._renderingDone = true; 10683 capability.resolve(); 10684} 10685 10686function findPositiveMin(ts, offset, count) { 10687 let result = 0; 10688 10689 for (let i = 0; i < count; i++) { 10690 const t = ts[offset++]; 10691 10692 if (t > 0) { 10693 result = result ? Math.min(t, result) : t; 10694 } 10695 } 10696 10697 return result; 10698} 10699 10700function expand(task) { 10701 const bounds = task._bounds; 10702 const viewport = task._viewport; 10703 const expanded = expandBounds(viewport.width, viewport.height, bounds); 10704 10705 for (let i = 0; i < expanded.length; i++) { 10706 const div = bounds[i].div; 10707 10708 const divProperties = task._textDivProperties.get(div); 10709 10710 if (divProperties.angle === 0) { 10711 divProperties.paddingLeft = bounds[i].left - expanded[i].left; 10712 divProperties.paddingTop = bounds[i].top - expanded[i].top; 10713 divProperties.paddingRight = expanded[i].right - bounds[i].right; 10714 divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom; 10715 10716 task._textDivProperties.set(div, divProperties); 10717 10718 continue; 10719 } 10720 10721 const e = expanded[i], 10722 b = bounds[i]; 10723 const m = b.m, 10724 c = m[0], 10725 s = m[1]; 10726 const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size]; 10727 const ts = new Float64Array(64); 10728 10729 for (let j = 0, jj = points.length; j < jj; j++) { 10730 const t = _util.Util.applyTransform(points[j], m); 10731 10732 ts[j + 0] = c && (e.left - t[0]) / c; 10733 ts[j + 4] = s && (e.top - t[1]) / s; 10734 ts[j + 8] = c && (e.right - t[0]) / c; 10735 ts[j + 12] = s && (e.bottom - t[1]) / s; 10736 ts[j + 16] = s && (e.left - t[0]) / -s; 10737 ts[j + 20] = c && (e.top - t[1]) / c; 10738 ts[j + 24] = s && (e.right - t[0]) / -s; 10739 ts[j + 28] = c && (e.bottom - t[1]) / c; 10740 ts[j + 32] = c && (e.left - t[0]) / -c; 10741 ts[j + 36] = s && (e.top - t[1]) / -s; 10742 ts[j + 40] = c && (e.right - t[0]) / -c; 10743 ts[j + 44] = s && (e.bottom - t[1]) / -s; 10744 ts[j + 48] = s && (e.left - t[0]) / s; 10745 ts[j + 52] = c && (e.top - t[1]) / -c; 10746 ts[j + 56] = s && (e.right - t[0]) / s; 10747 ts[j + 60] = c && (e.bottom - t[1]) / -c; 10748 } 10749 10750 const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
10751 divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale; 10752 divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale; 10753 divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale; 10754 divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale; 10755 10756 task._textDivProperties.set(div, divProperties); 10757 } 10758} 10759 10760function expandBounds(width, height, boxes) { 10761 const bounds = boxes.map(function (box, i) { 10762 return { 10763 x1: box.left, 10764 y1: box.top, 10765 x2: box.right, 10766 y2: box.bottom, 10767 index: i, 10768 x1New: undefined, 10769 x2New: undefined 10770 }; 10771 }); 10772 expandBoundsLTR(width, bounds); 10773 const expanded = new Array(boxes.length); 10774 10775 for (const b of bounds) { 10776 const i = b.index; 10777 expanded[i] = { 10778 left: b.x1New, 10779 top: 0, 10780 right: b.x2New, 10781 bottom: 0 10782 }; 10783 } 10784 10785 boxes.map(function (box, i) { 10786 const e = expanded[i], 10787 b = bounds[i]; 10788 b.x1 = box.top; 10789 b.y1 = width - e.right; 10790 b.x2 = box.bottom; 10791 b.y2 = width - e.left; 10792 b.index = i; 10793 b.x1New = undefined; 10794 b.x2New = undefined; 10795 }); 10796 expandBoundsLTR(height, bounds); 10797 10798 for (const b of bounds) { 10799 const i = b.index; 10800 expanded[i].top = b.x1New; 10801 expanded[i].bottom = b.x2New; 10802 } 10803 10804 return expanded; 10805} 10806 10807function expandBoundsLTR(width, bounds) { 10808 bounds.sort(function (a, b) { 10809 return a.x1 - b.x1 || a.index - b.index; 10810 }); 10811 const fakeBoundary = { 10812 x1: -Infinity, 10813 y1: -Infinity, 10814 x2: 0, 10815 y2: Infinity, 10816 index: -1, 10817 x1New: 0, 10818 x2New: 0 10819 }; 10820 const horizon = [{ 10821 start: -Infinity, 10822 end: Infinity, 10823 boundary: fakeBoundary 10824 }]; 10825 10826 for (const boundary of bounds) { 10827 let i = 0; 10828 10829 while (i < horizon.length && horizon[i].end <= boundary.y1) { 10830 i++; 10831 } 10832 10833 let j = horizon.length - 1; 10834 10835 while (j >= 0 && horizon[j].start >= boundary.y2) { 10836 j--; 10837 } 10838 10839 let horizonPart, affectedBoundary; 10840 let q, 10841 k, 10842 maxXNew = -Infinity; 10843 10844 for (q = i; q <= j; q++) { 10845 horizonPart = horizon[q]; 10846 affectedBoundary = horizonPart.boundary; 10847 let xNew; 10848 10849 if (affectedBoundary.x2 > boundary.x1) { 10850 xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1; 10851 } else if (affectedBoundary.x2New === undefined) { 10852 xNew = (affectedBoundary.x2 + boundary.x1) / 2; 10853 } else { 10854 xNew = affectedBoundary.x2New; 10855 } 10856 10857 if (xNew > maxXNew) { 10858 maxXNew = xNew; 10859 } 10860 } 10861 10862 boundary.x1New = maxXNew; 10863 10864 for (q = i; q <= j; q++) { 10865 horizonPart = horizon[q]; 10866 affectedBoundary = horizonPart.boundary; 10867 10868 if (affectedBoundary.x2New === undefined) { 10869 if (affectedBoundary.x2 > boundary.x1) { 10870 if (affectedBoundary.index > boundary.index) { 10871 affectedBoundary.x2New = affectedBoundary.x2; 10872 } 10873 } else { 10874 affectedBoundary.x2New = maxXNew; 10875 } 10876 } else if (affectedBoundary.x2New > maxXNew) { 10877 affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2); 10878 } 10879 } 10880 10881 const changedHorizon = []; 10882 let lastBoundary = null; 10883 10884 for (q = i; q <= j; q++) { 10885 horizonPart = horizon[q]; 10886 affectedBoundary = horizonPart.boundary; 10887 const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary; 10888 10889 if (lastBoundary === useBoundary) { 10890 changedHorizon[changedHorizon.length - 1].end = horizonPart.end; 10891 } else { 10892 changedHorizon.push({ 10893 start: horizonPart.start, 10894 end: horizonPart.end, 10895 boundary: useBoundary 10896 }); 10897 lastBoundary = useBoundary; 10898 } 10899 } 10900 10901 if (horizon[i].start < boundary.y1) { 10902 changedHorizon[0].start = boundary.y1; 10903 changedHorizon.unshift({ 10904 start: horizon[i].start, 10905 end: boundary.y1, 10906 boundary: horizon[i].boundary 10907 }); 10908 } 10909 10910 if (boundary.y2 < horizon[j].end) { 10911 changedHorizon[changedHorizon.length - 1].end = boundary.y2; 10912 changedHorizon.push({ 10913 start: boundary.y2, 10914 end: horizon[j].end, 10915 boundary: horizon[j].boundary 10916 }); 10917 } 10918 10919 for (q = i; q <= j; q++) { 10920 horizonPart = horizon[q]; 10921 affectedBoundary = horizonPart.boundary; 10922 10923 if (affectedBoundary.x2New !== undefined) { 10924 continue; 10925 } 10926 10927 let used = false;
10928 10929 for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) { 10930 used = horizon[k].boundary === affectedBoundary; 10931 } 10932 10933 for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) { 10934 used = horizon[k].boundary === affectedBoundary; 10935 } 10936 10937 for (k = 0; !used && k < changedHorizon.length; k++) { 10938 used = changedHorizon[k].boundary === affectedBoundary; 10939 } 10940 10941 if (!used) { 10942 affectedBoundary.x2New = maxXNew; 10943 } 10944 } 10945 10946 Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon)); 10947 } 10948 10949 for (const horizonPart of horizon) { 10950 const affectedBoundary = horizonPart.boundary; 10951 10952 if (affectedBoundary.x2New === undefined) { 10953 affectedBoundary.x2New = Math.max(width, affectedBoundary.x2); 10954 } 10955 } 10956} 10957 10958class TextLayerRenderTask { 10959 constructor({ 10960 textContent, 10961 textContentStream, 10962 container, 10963 viewport, 10964 textDivs, 10965 textContentItemsStr, 10966 enhanceTextSelection 10967 }) { 10968 this._textContent = textContent; 10969 this._textContentStream = textContentStream; 10970 this._container = container; 10971 this._document = container.ownerDocument; 10972 this._viewport = viewport; 10973 this._textDivs = textDivs || []; 10974 this._textContentItemsStr = textContentItemsStr || []; 10975 this._enhanceTextSelection = !!enhanceTextSelection; 10976 this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled; 10977 this._reader = null; 10978 this._layoutTextLastFontSize = null; 10979 this._layoutTextLastFontFamily = null; 10980 this._layoutTextCtx = null; 10981 this._textDivProperties = new WeakMap(); 10982 this._renderingDone = false; 10983 this._canceled = false; 10984 this._capability = (0, _util.createPromiseCapability)(); 10985 this._renderTimer = null; 10986 this._bounds = []; 10987 10988 this._capability.promise.finally(() => { 10989 if (this._layoutTextCtx) { 10990 this._layoutTextCtx.canvas.width = 0; 10991 this._layoutTextCtx.canvas.height = 0; 10992 this._layoutTextCtx = null; 10993 } 10994 }).catch(() => {}); 10995 } 10996 10997 get promise() { 10998 return this._capability.promise; 10999 } 11000 11001 cancel() { 11002 this._canceled = true; 11003 11004 if (this._reader) { 11005 this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")); 11006 11007 this._reader = null; 11008 } 11009 11010 if (this._renderTimer !== null) { 11011 clearTimeout(this._renderTimer); 11012 this._renderTimer = null; 11013 } 11014 11015 this._capability.reject(new Error("TextLayer task cancelled.")); 11016 } 11017 11018 _processItems(items, styleCache) { 11019 for (let i = 0, len = items.length; i < len; i++) { 11020 if (items[i].str === undefined) { 11021 if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") { 11022 const parent = this._container; 11023 this._container = document.createElement("span"); 11024 11025 this._container.classList.add("markedContent"); 11026 11027 if (items[i].id !== null) { 11028 this._container.setAttribute("id", `${items[i].id}`); 11029 } 11030 11031 parent.appendChild(this._container); 11032 } else if (items[i].type === "endMarkedContent") { 11033 this._container = this._container.parentNode; 11034 } 11035 11036 continue; 11037 } 11038 11039 this._textContentItemsStr.push(items[i].str); 11040 11041 appendText(this, items[i], styleCache, this._layoutTextCtx); 11042 } 11043 } 11044 11045 _layoutText(textDiv) { 11046 const textDivProperties = this._textDivProperties.get(textDiv); 11047 11048 let transform = ""; 11049 11050 if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) { 11051 const { 11052 fontSize, 11053 fontFamily 11054 } = textDiv.style; 11055 11056 if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) { 11057 this._layoutTextCtx.font = `${fontSize} ${fontFamily}`; 11058 this._layoutTextLastFontSize = fontSize; 11059 this._layoutTextLastFontFamily = fontFamily; 11060 } 11061 11062 const { 11063 width 11064 } = this._layoutTextCtx.measureText(textDiv.textContent); 11065 11066 if (width > 0) { 11067 textDivProperties.scale = textDivProperties.canvasWidth / width; 11068 transform = `scaleX(${textDivProperties.scale})`; 11069 } 11070 } 11071 11072 if (textDivProperties.angle !== 0) { 11073 transform = `rotate(${textDivProperties.angle}deg) ${transform}`; 11074 } 11075 11076 if (transform.length > 0) { 11077 if (this._enhanceTextSelection) { 11078 textDivProperties.originalTransform = transform; 11079 } 11080 11081 textDiv.style.transform = transform; 11082 } 11083 11084 if (textDivProperties.hasText) { 11085 this._container.appendChild(textDiv); 11086 } 11087 11088 if (textDivProperties.hasEOL) { 11089 const br = document.createElement("br"); 11090 br.setAttribute("role", "presentation"); 11091 11092 this._container.appendChild(br); 11093 } 11094 } 11095 11096 _render(timeout = 0) { 11097 const capability = (0, _util.createPromiseCapability)(); 11098 let styleCache = Object.create(null); 11099 11100 const canvas = this._document.createElement("canvas"); 11101 11102 canvas.height = canvas.width = DEFAULT_FONT_SIZE; 11103 canvas.mozOpaque = true; 11104 this._layoutTextCtx = canvas.getContext("2d", { 11105 alpha: false 11106 }); 11107 11108 if (this._textContent) { 11109 const textItems = this._textContent.items; 11110 const textStyles = this._textContent.styles; 11111 11112 this._processItems(textItems, textStyles); 11113 11114 capability.resolve(); 11115 } else if (this._textContentStream) { 11116 const pump = () => { 11117 this._reader.read().then(({ 11118 value, 11119 done 11120 }) => { 11121 if (done) { 11122 capability.resolve(); 11123 return; 11124 } 11125 11126 Object.assign(styleCache, value.styles); 11127 11128 this._processItems(value.items, styleCache); 11129 11130 pump(); 11131 }, capability.reject); 11132 }; 11133 11134 this._reader = this._textContentStream.getReader(); 11135 pump(); 11136 } else { 11137 throw new Error('Neither "textContent" nor "textContentStream"' + " parameters specified."); 11138 } 11139 11140 capability.promise.then(() => { 11141 styleCache = null; 11142 11143 if (!timeout) { 11144 render(this); 11145 } else { 11146 this._renderTimer = setTimeout(() => { 11147 render(this); 11148 this._renderTimer = null; 11149 }, timeout); 11150 } 11151 }, this._capability.reject); 11152 } 11153
11154 expandTextDivs(expandDivs = false) { 11155 if (!this._enhanceTextSelection || !this._renderingDone) { 11156 return; 11157 } 11158 11159 if (this._bounds !== null) { 11160 expand(this); 11161 this._bounds = null; 11162 } 11163 11164 const transformBuf = [], 11165 paddingBuf = []; 11166 11167 for (let i = 0, ii = this._textDivs.length; i < ii; i++) { 11168 const div = this._textDivs[i]; 11169 11170 const divProps = this._textDivProperties.get(div); 11171 11172 if (!divProps.hasText) { 11173 continue; 11174 } 11175 11176 if (expandDivs) { 11177 transformBuf.length = 0; 11178 paddingBuf.length = 0; 11179 11180 if (divProps.originalTransform) { 11181 transformBuf.push(divProps.originalTransform); 11182 } 11183 11184 if (divProps.paddingTop > 0) { 11185 paddingBuf.push(`${divProps.paddingTop}px`); 11186 transformBuf.push(`translateY(${-divProps.paddingTop}px)`); 11187 } else { 11188 paddingBuf.push(0); 11189 } 11190 11191 if (divProps.paddingRight > 0) { 11192 paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`); 11193 } else { 11194 paddingBuf.push(0); 11195 } 11196 11197 if (divProps.paddingBottom > 0) { 11198 paddingBuf.push(`${divProps.paddingBottom}px`); 11199 } else { 11200 paddingBuf.push(0); 11201 } 11202 11203 if (divProps.paddingLeft > 0) { 11204 paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`); 11205 transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`); 11206 } else { 11207 paddingBuf.push(0); 11208 } 11209 11210 div.style.padding = paddingBuf.join(" "); 11211 11212 if (transformBuf.length) { 11213 div.style.transform = transformBuf.join(" "); 11214 } 11215 } else { 11216 div.style.padding = null; 11217 div.style.transform = divProps.originalTransform; 11218 } 11219 } 11220 } 11221 11222} 11223 11224function renderTextLayer(renderParameters) { 11225 const task = new TextLayerRenderTask({ 11226 textContent: renderParameters.textContent, 11227 textContentStream: renderParameters.textContentStream, 11228 container: renderParameters.container, 11229 viewport: renderParameters.viewport, 11230 textDivs: renderParameters.textDivs, 11231 textContentItemsStr: renderParameters.textContentItemsStr, 11232 enhanceTextSelection: renderParameters.enhanceTextSelection 11233 }); 11234 11235 task._render(renderParameters.timeout); 11236 11237 return task; 11238} 11239 11240/***/ }), 11241/* 20 */ 11242/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 11243 11244 11245 11246Object.defineProperty(exports, "__esModule", ({ 11247 value: true 11248})); 11249exports.SVGGraphics = void 0; 11250 11251var _util = __w_pdfjs_require__(2); 11252 11253var _display_utils = __w_pdfjs_require__(1); 11254 11255var _is_node = __w_pdfjs_require__(4); 11256 11257let SVGGraphics = class { 11258 constructor() { 11259 (0, _util.unreachable)("Not implemented: SVGGraphics"); 11260 } 11261 11262}; 11263exports.SVGGraphics = SVGGraphics; 11264{ 11265 const SVG_DEFAULTS = { 11266 fontStyle: "normal", 11267 fontWeight: "normal", 11268 fillColor: "#000000" 11269 }; 11270 const XML_NS = "http://www.w3.org/XML/1998/namespace"; 11271 const XLINK_NS = "http://www.w3.org/1999/xlink"; 11272 const LINE_CAP_STYLES = ["butt", "round", "square"]; 11273 const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; 11274 11275 const convertImgDataToPng = function () { 11276 const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); 11277 const CHUNK_WRAPPER_SIZE = 12; 11278 const crcTable = new Int32Array(256); 11279 11280 for (let i = 0; i < 256; i++) { 11281 let c = i; 11282 11283 for (let h = 0; h < 8; h++) { 11284 if (c & 1) { 11285 c = 0xedb88320 ^ c >> 1 & 0x7fffffff; 11286 } else { 11287 c = c >> 1 & 0x7fffffff; 11288 } 11289 } 11290 11291 crcTable[i] = c; 11292 } 11293 11294 function crc32(data, start, end) { 11295 let crc = -1; 11296 11297 for (let i = start; i < end; i++) { 11298 const a = (crc ^ data[i]) & 0xff; 11299 const b = crcTable[a]; 11300 crc = crc >>> 8 ^ b; 11301 } 11302 11303 return crc ^ -1; 11304 } 11305 11306 function writePngChunk(type, body, data, offset) { 11307 let p = offset; 11308 const len = body.length; 11309 data[p] = len >> 24 & 0xff; 11310 data[p + 1] = len >> 16 & 0xff; 11311 data[p + 2] = len >> 8 & 0xff; 11312 data[p + 3] = len & 0xff; 11313 p += 4; 11314 data[p] = type.charCodeAt(0) & 0xff; 11315 data[p + 1] = type.charCodeAt(1) & 0xff;
11316 data[p + 2] = type.charCodeAt(2) & 0xff; 11317 data[p + 3] = type.charCodeAt(3) & 0xff; 11318 p += 4; 11319 data.set(body, p); 11320 p += body.length; 11321 const crc = crc32(data, offset + 4, p); 11322 data[p] = crc >> 24 & 0xff; 11323 data[p + 1] = crc >> 16 & 0xff; 11324 data[p + 2] = crc >> 8 & 0xff; 11325 data[p + 3] = crc & 0xff; 11326 } 11327 11328 function adler32(data, start, end) { 11329 let a = 1; 11330 let b = 0; 11331 11332 for (let i = start; i < end; ++i) { 11333 a = (a + (data[i] & 0xff)) % 65521; 11334 b = (b + a) % 65521; 11335 } 11336 11337 return b << 16 | a; 11338 } 11339 11340 function deflateSync(literals) { 11341 if (!_is_node.isNodeJS) { 11342 return deflateSyncUncompressed(literals); 11343 } 11344 11345 try { 11346 let input; 11347 11348 if (parseInt(process.versions.node) >= 8) { 11349 input = literals; 11350 } else { 11351 input = Buffer.from(literals); 11352 } 11353 11354 const output = require("zlib").deflateSync(input, { 11355 level: 9 11356 }); 11357 11358 return output instanceof Uint8Array ? output : new Uint8Array(output); 11359 } catch (e) { 11360 (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e); 11361 } 11362 11363 return deflateSyncUncompressed(literals); 11364 } 11365 11366 function deflateSyncUncompressed(literals) { 11367 let len = literals.length; 11368 const maxBlockLength = 0xffff; 11369 const deflateBlocks = Math.ceil(len / maxBlockLength); 11370 const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); 11371 let pi = 0; 11372 idat[pi++] = 0x78; 11373 idat[pi++] = 0x9c; 11374 let pos = 0; 11375 11376 while (len > maxBlockLength) { 11377 idat[pi++] = 0x00; 11378 idat[pi++] = 0xff; 11379 idat[pi++] = 0xff; 11380 idat[pi++] = 0x00; 11381 idat[pi++] = 0x00; 11382 idat.set(literals.subarray(pos, pos + maxBlockLength), pi); 11383 pi += maxBlockLength; 11384 pos += maxBlockLength; 11385 len -= maxBlockLength; 11386 } 11387 11388 idat[pi++] = 0x01; 11389 idat[pi++] = len & 0xff; 11390 idat[pi++] = len >> 8 & 0xff; 11391 idat[pi++] = ~len & 0xffff & 0xff; 11392 idat[pi++] = (~len & 0xffff) >> 8 & 0xff; 11393 idat.set(literals.subarray(pos), pi); 11394 pi += literals.length - pos; 11395 const adler = adler32(literals, 0, literals.length); 11396 idat[pi++] = adler >> 24 & 0xff; 11397 idat[pi++] = adler >> 16 & 0xff; 11398 idat[pi++] = adler >> 8 & 0xff; 11399 idat[pi++] = adler & 0xff; 11400 return idat; 11401 } 11402 11403 function encode(imgData, kind, forceDataSchema, isMask) { 11404 const width = imgData.width; 11405 const height = imgData.height; 11406 let bitDepth, colorType, lineSize; 11407 const bytes = imgData.data; 11408 11409 switch (kind) { 11410 case _util.ImageKind.GRAYSCALE_1BPP: 11411 colorType = 0; 11412 bitDepth = 1; 11413 lineSize = width + 7 >> 3; 11414 break; 11415 11416 case _util.ImageKind.RGB_24BPP: 11417 colorType = 2; 11418 bitDepth = 8; 11419 lineSize = width * 3; 11420 break; 11421 11422 case _util.ImageKind.RGBA_32BPP: 11423 colorType = 6; 11424 bitDepth = 8; 11425 lineSize = width * 4; 11426 break; 11427 11428 default: 11429 throw new Error("invalid format"); 11430 } 11431 11432 const literals = new Uint8Array((1 + lineSize) * height); 11433 let offsetLiterals = 0, 11434 offsetBytes = 0; 11435 11436 for (let y = 0; y < height; ++y) { 11437 literals[offsetLiterals++] = 0; 11438 literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); 11439 offsetBytes += lineSize; 11440 offsetLiterals += lineSize; 11441 } 11442 11443 if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) { 11444 offsetLiterals = 0; 11445 11446 for (let y = 0; y < height; y++) { 11447 offsetLiterals++; 11448 11449 for (let i = 0; i < lineSize; i++) { 11450 literals[offsetLiterals++] ^= 0xff; 11451 } 11452 } 11453 } 11454 11455 const 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]); 11456 const idat = deflateSync(literals); 11457 const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length; 11458 const data = new Uint8Array(pngLength); 11459 let offset = 0; 11460 data.set(PNG_HEADER, offset); 11461 offset += PNG_HEADER.length; 11462 writePngChunk("IHDR", ihdr, data, offset); 11463 offset += CHUNK_WRAPPER_SIZE + ihdr.length; 11464 writePngChunk("IDATA", idat, data, offset); 11465 offset += CHUNK_WRAPPER_SIZE + idat.length; 11466 writePngChunk("IEND", new Uint8Array(0), data, offset); 11467 return (0, _util.createObjectURL)(data, "image/png", forceDataSchema); 11468 } 11469 11470 return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
11471 const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind; 11472 return encode(imgData, kind, forceDataSchema, isMask); 11473 }; 11474 }(); 11475 11476 class SVGExtraState { 11477 constructor() { 11478 this.fontSizeScale = 1; 11479 this.fontWeight = SVG_DEFAULTS.fontWeight; 11480 this.fontSize = 0; 11481 this.textMatrix = _util.IDENTITY_MATRIX; 11482 this.fontMatrix = _util.FONT_IDENTITY_MATRIX; 11483 this.leading = 0; 11484 this.textRenderingMode = _util.TextRenderingMode.FILL; 11485 this.textMatrixScale = 1; 11486 this.x = 0; 11487 this.y = 0; 11488 this.lineX = 0; 11489 this.lineY = 0; 11490 this.charSpacing = 0; 11491 this.wordSpacing = 0; 11492 this.textHScale = 1; 11493 this.textRise = 0; 11494 this.fillColor = SVG_DEFAULTS.fillColor; 11495 this.strokeColor = "#000000"; 11496 this.fillAlpha = 1; 11497 this.strokeAlpha = 1; 11498 this.lineWidth = 1; 11499 this.lineJoin = ""; 11500 this.lineCap = ""; 11501 this.miterLimit = 0; 11502 this.dashArray = []; 11503 this.dashPhase = 0; 11504 this.dependencies = []; 11505 this.activeClipUrl = null; 11506 this.clipGroup = null; 11507 this.maskId = ""; 11508 } 11509 11510 clone() { 11511 return Object.create(this); 11512 } 11513 11514 setCurrentPoint(x, y) { 11515 this.x = x; 11516 this.y = y; 11517 } 11518 11519 } 11520 11521 function opListToTree(opList) { 11522 let opTree = []; 11523 const tmp = []; 11524 11525 for (const opListElement of opList) { 11526 if (opListElement.fn === "save") { 11527 opTree.push({ 11528 fnId: 92, 11529 fn: "group", 11530 items: [] 11531 }); 11532 tmp.push(opTree); 11533 opTree = opTree[opTree.length - 1].items; 11534 continue; 11535 } 11536 11537 if (opListElement.fn === "restore") { 11538 opTree = tmp.pop(); 11539 } else { 11540 opTree.push(opListElement); 11541 } 11542 } 11543 11544 return opTree; 11545 } 11546 11547 function pf(value) { 11548 if (Number.isInteger(value)) { 11549 return value.toString(); 11550 } 11551 11552 const s = value.toFixed(10); 11553 let i = s.length - 1; 11554 11555 if (s[i] !== "0") { 11556 return s; 11557 } 11558 11559 do { 11560 i--; 11561 } while (s[i] === "0"); 11562 11563 return s.substring(0, s[i] === "." ? i : i + 1); 11564 } 11565 11566 function pm(m) { 11567 if (m[4] === 0 && m[5] === 0) { 11568 if (m[1] === 0 && m[2] === 0) { 11569 if (m[0] === 1 && m[3] === 1) { 11570 return ""; 11571 } 11572 11573 return `scale(${pf(m[0])} ${pf(m[3])})`; 11574 } 11575 11576 if (m[0] === m[3] && m[1] === -m[2]) { 11577 const a = Math.acos(m[0]) * 180 / Math.PI; 11578 return `rotate(${pf(a)})`; 11579 } 11580 } else { 11581 if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { 11582 return `translate(${pf(m[4])} ${pf(m[5])})`; 11583 } 11584 } 11585 11586 return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`; 11587 } 11588 11589 let clipCount = 0; 11590 let maskCount = 0; 11591 let shadingCount = 0; 11592 exports.SVGGraphics = SVGGraphics = class { 11593 constructor(commonObjs, objs, forceDataSchema = false) { 11594 this.svgFactory = new _display_utils.DOMSVGFactory(); 11595 this.current = new SVGExtraState(); 11596 this.transformMatrix = _util.IDENTITY_MATRIX; 11597 this.transformStack = []; 11598 this.extraStack = []; 11599 this.commonObjs = commonObjs; 11600 this.objs = objs; 11601 this.pendingClip = null; 11602 this.pendingEOFill = false; 11603 this.embedFonts = false; 11604 this.embeddedFonts = Object.create(null); 11605 this.cssStyle = null; 11606 this.forceDataSchema = !!forceDataSchema; 11607 this._operatorIdMapping = []; 11608 11609 for (const op in _util.OPS) { 11610 this._operatorIdMapping[_util.OPS[op]] = op; 11611 } 11612 } 11613 11614 save() { 11615 this.transformStack.push(this.transformMatrix); 11616 const old = this.current; 11617 this.extraStack.push(old); 11618 this.current = old.clone(); 11619 } 11620 11621 restore() { 11622 this.transformMatrix = this.transformStack.pop(); 11623 this.current = this.extraStack.pop(); 11624 this.pendingClip = null; 11625 this.tgrp = null; 11626 } 11627 11628 group(items) { 11629 this.save(); 11630 this.executeOpTree(items); 11631 this.restore(); 11632 } 11633 11634 loadDependencies(operatorList) { 11635 const fnArray = operatorList.fnArray; 11636 const argsArray = operatorList.argsArray; 11637 11638 for (let i = 0, ii = fnArray.length; i < ii; i++) { 11639 if (fnArray[i] !== _util.OPS.dependency) { 11640 continue; 11641 } 11642 11643 for (const obj of argsArray[i]) { 11644 const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs; 11645 const promise = new Promise(resolve => { 11646 objsPool.get(obj, resolve); 11647 }); 11648 this.current.dependencies.push(promise); 11649 } 11650 } 11651 11652 return Promise.all(this.current.dependencies); 11653 } 11654 11655 transform(a, b, c, d, e, f) { 11656 const transformMatrix = [a, b, c, d, e, f]; 11657 this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix); 11658 this.tgrp = null; 11659 } 11660 11661 getSVG(operatorList, viewport) { 11662 this.viewport = viewport; 11663 11664 const svgElement = this._initialize(viewport); 11665 11666 return this.loadDependencies(operatorList).then(() => { 11667 this.transformMatrix = _util.IDENTITY_MATRIX; 11668 this.executeOpTree(this.convertOpList(operatorList)); 11669 return svgElement; 11670 }); 11671 } 11672 11673 convertOpList(operatorList) { 11674 const operatorIdMapping = this._operatorIdMapping; 11675 const argsArray = operatorList.argsArray; 11676 const fnArray = operatorList.fnArray; 11677 const opList = []; 11678 11679 for (let i = 0, ii = fnArray.length; i < ii; i++) { 11680 const fnId = fnArray[i]; 11681 opList.push({ 11682 fnId, 11683 fn: operatorIdMapping[fnId], 11684 args: argsArray[i] 11685 }); 11686 } 11687 11688 return opListToTree(opList); 11689 } 11690 11691 executeOpTree(opTree) { 11692 for (const opTreeElement of opTree) { 11693 const fn = opTreeElement.fn; 11694 const fnId = opTreeElement.fnId; 11695 const args = opTreeElement.args; 11696
11697 switch (fnId | 0) { 11698 case _util.OPS.beginText: 11699 this.beginText(); 11700 break; 11701 11702 case _util.OPS.dependency: 11703 break; 11704 11705 case _util.OPS.setLeading: 11706 this.setLeading(args); 11707 break; 11708 11709 case _util.OPS.setLeadingMoveText: 11710 this.setLeadingMoveText(args[0], args[1]); 11711 break; 11712 11713 case _util.OPS.setFont: 11714 this.setFont(args); 11715 break; 11716 11717 case _util.OPS.showText: 11718 this.showText(args[0]); 11719 break; 11720 11721 case _util.OPS.showSpacedText: 11722 this.showText(args[0]); 11723 break; 11724 11725 case _util.OPS.endText: 11726 this.endText(); 11727 break; 11728 11729 case _util.OPS.moveText: 11730 this.moveText(args[0], args[1]); 11731 break; 11732 11733 case _util.OPS.setCharSpacing: 11734 this.setCharSpacing(args[0]); 11735 break; 11736 11737 case _util.OPS.setWordSpacing: 11738 this.setWordSpacing(args[0]); 11739 break; 11740 11741 case _util.OPS.setHScale: 11742 this.setHScale(args[0]); 11743 break; 11744 11745 case _util.OPS.setTextMatrix: 11746 this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); 11747 break; 11748 11749 case _util.OPS.setTextRise: 11750 this.setTextRise(args[0]); 11751 break; 11752 11753 case _util.OPS.setTextRenderingMode: 11754 this.setTextRenderingMode(args[0]); 11755 break; 11756 11757 case _util.OPS.setLineWidth: 11758 this.setLineWidth(args[0]); 11759 break; 11760 11761 case _util.OPS.setLineJoin: 11762 this.setLineJoin(args[0]); 11763 break; 11764 11765 case _util.OPS.setLineCap: 11766 this.setLineCap(args[0]); 11767 break; 11768 11769 case _util.OPS.setMiterLimit: 11770 this.setMiterLimit(args[0]); 11771 break; 11772 11773 case _util.OPS.setFillRGBColor: 11774 this.setFillRGBColor(args[0], args[1], args[2]); 11775 break; 11776 11777 case _util.OPS.setStrokeRGBColor: 11778 this.setStrokeRGBColor(args[0], args[1], args[2]); 11779 break; 11780 11781 case _util.OPS.setStrokeColorN: 11782 this.setStrokeColorN(args); 11783 break; 11784 11785 case _util.OPS.setFillColorN: 11786 this.setFillColorN(args); 11787 break; 11788 11789 case _util.OPS.shadingFill: 11790 this.shadingFill(args[0]); 11791 break; 11792 11793 case _util.OPS.setDash: 11794 this.setDash(args[0], args[1]); 11795 break; 11796 11797 case _util.OPS.setRenderingIntent: 11798 this.setRenderingIntent(args[0]); 11799 break; 11800 11801 case _util.OPS.setFlatness: 11802 this.setFlatness(args[0]); 11803 break; 11804 11805 case _util.OPS.setGState: 11806 this.setGState(args[0]); 11807 break; 11808 11809 case _util.OPS.fill: 11810 this.fill(); 11811 break; 11812 11813 case _util.OPS.eoFill: 11814 this.eoFill(); 11815 break; 11816 11817 case _util.OPS.stroke: 11818 this.stroke(); 11819 break; 11820 11821 case _util.OPS.fillStroke: 11822 this.fillStroke(); 11823 break; 11824 11825 case _util.OPS.eoFillStroke: 11826 this.eoFillStroke(); 11827 break; 11828 11829 case _util.OPS.clip: 11830 this.clip("nonzero"); 11831 break; 11832 11833 case _util.OPS.eoClip: 11834 this.clip("evenodd"); 11835 break; 11836 11837 case _util.OPS.paintSolidColorImageMask: 11838 this.paintSolidColorImageMask(); 11839 break; 11840 11841 case _util.OPS.paintImageXObject: 11842 this.paintImageXObject(args[0]); 11843 break; 11844 11845 case _util.OPS.paintInlineImageXObject: 11846 this.paintInlineImageXObject(args[0]); 11847 break; 11848 11849 case _util.OPS.paintImageMaskXObject: 11850 this.paintImageMaskXObject(args[0]); 11851 break; 11852 11853 case _util.OPS.paintFormXObjectBegin: 11854 this.paintFormXObjectBegin(args[0], args[1]); 11855 break; 11856 11857 case _util.OPS.paintFormXObjectEnd: 11858 this.paintFormXObjectEnd(); 11859 break; 11860 11861 case _util.OPS.closePath: 11862 this.closePath(); 11863 break; 11864 11865 case _util.OPS.closeStroke: 11866 this.closeStroke(); 11867 break; 11868 11869 case _util.OPS.closeFillStroke: 11870 this.closeFillStroke(); 11871 break; 11872 11873 case _util.OPS.closeEOFillStroke: 11874 this.closeEOFillStroke(); 11875 break; 11876 11877 case _util.OPS.nextLine: 11878 this.nextLine(); 11879 break; 11880 11881 case _util.OPS.transform: 11882 this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); 11883 break; 11884 11885 case _util.OPS.constructPath: 11886 this.constructPath(args[0], args[1]); 11887 break; 11888 11889 case _util.OPS.endPath: 11890 this.endPath(); 11891 break; 11892 11893 case 92: 11894 this.group(opTreeElement.items); 11895 break; 11896 11897 default: 11898 (0, _util.warn)(`Unimplemented operator ${fn}`); 11899 break; 11900 } 11901 } 11902 } 11903 11904 setWordSpacing(wordSpacing) { 11905 this.current.wordSpacing = wordSpacing; 11906 } 11907 11908 setCharSpacing(charSpacing) { 11909 this.current.charSpacing = charSpacing; 11910 } 11911 11912 nextLine() { 11913 this.moveText(0, this.current.leading); 11914 } 11915 11916 setTextMatrix(a, b, c, d, e, f) { 11917 const current = this.current; 11918 current.textMatrix = current.lineMatrix = [a, b, c, d, e, f]; 11919 current.textMatrixScale = Math.hypot(a, b); 11920 current.x = current.lineX = 0; 11921 current.y = current.lineY = 0; 11922 current.xcoords = []; 11923 current.ycoords = []; 11924 current.tspan = this.svgFactory.createElement("svg:tspan"); 11925 current.tspan.setAttributeNS(null, "font-family", current.fontFamily); 11926 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`); 11927 current.tspan.setAttributeNS(null, "y", pf(-current.y)); 11928 current.txtElement = this.svgFactory.createElement("svg:text"); 11929 current.txtElement.appendChild(current.tspan); 11930 } 11931 11932 beginText() { 11933 const current = this.current; 11934 current.x = current.lineX = 0; 11935 current.y = current.lineY = 0; 11936 current.textMatrix = _util.IDENTITY_MATRIX; 11937 current.lineMatrix = _util.IDENTITY_MATRIX; 11938 current.textMatrixScale = 1; 11939 current.tspan = this.svgFactory.createElement("svg:tspan"); 11940 current.txtElement = this.svgFactory.createElement("svg:text"); 11941 current.txtgrp = this.svgFactory.createElement("svg:g"); 11942 current.xcoords = []; 11943 current.ycoords = []; 11944 } 11945 11946 moveText(x, y) { 11947 const current = this.current; 11948 current.x = current.lineX += x; 11949 current.y = current.lineY += y; 11950 current.xcoords = []; 11951 current.ycoords = []; 11952 current.tspan = this.svgFactory.createElement("svg:tspan"); 11953 current.tspan.setAttributeNS(null, "font-family", current.fontFamily); 11954 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`); 11955 current.tspan.setAttributeNS(null, "y", pf(-current.y)); 11956 } 11957 11958 showText(glyphs) { 11959 const current = this.current; 11960 const font = current.font; 11961 const fontSize = current.fontSize; 11962 11963 if (fontSize === 0) { 11964 return; 11965 } 11966 11967 const fontSizeScale = current.fontSizeScale; 11968 const charSpacing = current.charSpacing; 11969 const wordSpacing = current.wordSpacing; 11970 const fontDirection = current.fontDirection; 11971 const textHScale = current.textHScale * fontDirection; 11972 const vertical = font.vertical; 11973 const spacingDir = vertical ? 1 : -1; 11974 const defaultVMetrics = font.defaultVMetrics; 11975 const widthAdvanceScale = fontSize * current.fontMatrix[0]; 11976 let x = 0; 11977 11978 for (const glyph of glyphs) { 11979 if (glyph === null) { 11980 x += fontDirection * wordSpacing; 11981 continue; 11982 }
11982 else if ((0, _util.isNum)(glyph)) { 11983 x += spacingDir * glyph * fontSize / 1000; 11984 continue; 11985 } 11986 11987 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; 11988 const character = glyph.fontChar; 11989 let scaledX, scaledY; 11990 let width = glyph.width; 11991 11992 if (vertical) { 11993 let vx; 11994 const vmetric = glyph.vmetric || defaultVMetrics; 11995 vx = glyph.vmetric ? vmetric[1] : width * 0.5; 11996 vx = -vx * widthAdvanceScale; 11997 const vy = vmetric[2] * widthAdvanceScale; 11998 width = vmetric ? -vmetric[0] : width; 11999 scaledX = vx / fontSizeScale; 12000 scaledY = (x + vy) / fontSizeScale; 12001 } else { 12002 scaledX = x / fontSizeScale; 12003 scaledY = 0; 12004 } 12005 12006 if (glyph.isInFont || font.missingFile) { 12007 current.xcoords.push(current.x + scaledX); 12008 12009 if (vertical) { 12010 current.ycoords.push(-current.y + scaledY); 12011 } 12012 12013 current.tspan.textContent += character; 12014 } else {} 12015 12016 let charWidth; 12017 12018 if (vertical) { 12019 charWidth = width * widthAdvanceScale - spacing * fontDirection; 12020 } else { 12021 charWidth = width * widthAdvanceScale + spacing * fontDirection; 12022 } 12023 12024 x += charWidth; 12025 } 12026 12027 current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" ")); 12028 12029 if (vertical) { 12030 current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" ")); 12031 } else { 12032 current.tspan.setAttributeNS(null, "y", pf(-current.y)); 12033 } 12034 12035 if (vertical) { 12036 current.y -= x; 12037 } else { 12038 current.x += x * textHScale; 12039 } 12040 12041 current.tspan.setAttributeNS(null, "font-family", current.fontFamily); 12042 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`); 12043 12044 if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { 12045 current.tspan.setAttributeNS(null, "font-style", current.fontStyle); 12046 } 12047 12048 if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { 12049 current.tspan.setAttributeNS(null, "font-weight", current.fontWeight); 12050 } 12051 12052 const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; 12053 12054 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { 12055 if (current.fillColor !== SVG_DEFAULTS.fillColor) { 12056 current.tspan.setAttributeNS(null, "fill", current.fillColor); 12057 } 12058 12059 if (current.fillAlpha < 1) { 12060 current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha); 12061 } 12062 } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) { 12063 current.tspan.setAttributeNS(null, "fill", "transparent"); 12064 } else { 12065 current.tspan.setAttributeNS(null, "fill", "none"); 12066 } 12067 12068 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { 12069 const lineWidthScale = 1 / (current.textMatrixScale || 1); 12070 12071 this._setStrokeAttributes(current.tspan, lineWidthScale); 12072 } 12073 12074 let textMatrix = current.textMatrix; 12075 12076 if (current.textRise !== 0) { 12077 textMatrix = textMatrix.slice(); 12078 textMatrix[5] += current.textRise; 12079 } 12080 12081 current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`); 12082 current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve"); 12083 current.txtElement.appendChild(current.tspan); 12084 current.txtgrp.appendChild(current.txtElement); 12085 12086 this._ensureTransformGroup().appendChild(current.txtElement); 12087 } 12088 12089 setLeadingMoveText(x, y) { 12090 this.setLeading(-y); 12091 this.moveText(x, y); 12092 } 12093 12094 addFontStyle(fontObj) { 12095 if (!fontObj.data) { 12096 throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.'); 12097 } 12098 12099 if (!this.cssStyle) { 12100 this.cssStyle = this.svgFactory.createElement("svg:style"); 12101 this.cssStyle.setAttributeNS(null, "type", "text/css"); 12102 this.defs.appendChild(this.cssStyle); 12103 } 12104 12105 const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema); 12106 this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`; 12107 } 12108 12109 setFont(details) { 12110 const current = this.current; 12111 const fontObj = this.commonObjs.get(details[0]); 12112 let size = details[1]; 12113 current.font = fontObj; 12114 12115 if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) { 12116 this.addFontStyle(fontObj); 12117 this.embeddedFonts[fontObj.loadedName] = fontObj; 12118 } 12119 12120 current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX; 12121 let bold = "normal"; 12122 12123 if (fontObj.black) { 12124 bold = "900"; 12125 } else if (fontObj.bold) { 12126 bold = "bold"; 12127 } 12128 12129 const italic = fontObj.italic ? "italic" : "normal"; 12130 12131 if (size < 0) { 12132 size = -size; 12133 current.fontDirection = -1; 12134 } else { 12135 current.fontDirection = 1; 12136 } 12137 12138 current.fontSize = size; 12139 current.fontFamily = fontObj.loadedName; 12140 current.fontWeight = bold; 12141 current.fontStyle = italic; 12142 current.tspan = this.svgFactory.createElement("svg:tspan"); 12143 current.tspan.setAttributeNS(null, "y", pf(-current.y)); 12144 current.xcoords = []; 12145 current.ycoords = []; 12146 } 12147 12148 endText() { 12149 const current = this.current; 12150 12151 if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) { 12152 current.element = current.txtElement; 12153 this.clip("nonzero"); 12154 this.endPath(); 12155 } 12156 } 12157 12158 setLineWidth(width) { 12159 if (width > 0) { 12160 this.current.lineWidth = width; 12161 } 12162 } 12163 12164 setLineCap(style) { 12165 this.current.lineCap = LINE_CAP_STYLES[style]; 12166 } 12167 12168 setLineJoin(style) { 12169 this.current.lineJoin = LINE_JOIN_STYLES[style]; 12170 } 12171 12172 setMiterLimit(limit) { 12173 this.current.miterLimit = limit; 12174 } 12175 12176 setStrokeAlpha(strokeAlpha) { 12177 this.current.strokeAlpha = strokeAlpha; 12178 } 12179 12180 setStrokeRGBColor(r, g, b) { 12181 this.current.strokeColor = _util.Util.makeHexColor(r, g, b); 12182 } 12183 12184 setFillAlpha(fillAlpha) { 12185 this.current.fillAlpha = fillAlpha; 12186 } 12187 12188 setFillRGBColor(r, g, b) { 12189 this.current.fillColor = _util.Util.makeHexColor(r, g, b); 12190 this.current.tspan = this.svgFactory.createElement("svg:tspan"); 12191 this.current.xcoords = []; 12192 this.current.ycoords = []; 12193 } 12194 12195 setStrokeColorN(args) { 12196 this.current.strokeColor = this._makeColorN_Pattern(args); 12197 } 12198 12199 setFillColorN(args) { 12200 this.current.fillColor = this._makeColorN_Pattern(args); 12201 } 12202 12203 shadingFill(args) { 12204 const width = this.viewport.width; 12205 const height = this.viewport.height; 12206 12207 const inv = _util.Util.inverseTransform(this.transformMatrix); 12208 12209 const bl = _util.Util.applyTransform([0, 0], inv); 12210 12211 const br = _util.Util.applyTransform([0, height], inv); 12212 12213 const ul = _util.Util.applyTransform([width, 0], inv); 12214 12215 const ur = _util.Util.applyTransform([width, height], inv); 12216 12217 const x0 = Math.min(bl[0], br[0], ul[0], ur[0]); 12218 const y0 = Math.min(bl[1], br[1], ul[1], ur[1]); 12219 const x1 = Math.max(bl[0], br[0], ul[0], ur[0]); 12220 const y1 = Math.max(bl[1], br[1], ul[1], ur[1]); 12221 const rect = this.svgFactory.createElement("svg:rect"); 12222 rect.setAttributeNS(null, "x", x0); 12223 rect.setAttributeNS(null, "y", y0); 12224 rect.setAttributeNS(null, "width", x1 - x0); 12225 rect.setAttributeNS(null, "height", y1 - y0); 12226 rect.setAttributeNS(null, "fill", this._makeShadingPattern(args)); 12227 12228 if (this.current.fillAlpha < 1) { 12229 rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha); 12230 } 12231 12232 this._ensureTransformGroup().appendChild(rect); 12233 } 12234 12235 _makeColorN_Pattern(args) { 12236 if (args[0] === "TilingPattern") { 12237 return this._makeTilingPattern(args); 12238 } 12239 12240 return this._makeShadingPattern(args); 12241 } 12242 12243 _makeTilingPattern(args) { 12244 const color = args[1]; 12245 const operatorList = args[2]; 12246 const matrix = args[3] || _util.IDENTITY_MATRIX; 12247 const [x0, y0, x1, y1] = args[4]; 12248 const xstep = args[5]; 12249 const ystep = args[6]; 12250 const paintType = args[7]; 12251 const tilingId = `shading${shadingCount++}`; 12252 12253 const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0
12253], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]); 12254 12255 const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix); 12256 12257 const txstep = xstep * xscale; 12258 const tystep = ystep * yscale; 12259 const tiling = this.svgFactory.createElement("svg:pattern"); 12260 tiling.setAttributeNS(null, "id", tilingId); 12261 tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse"); 12262 tiling.setAttributeNS(null, "width", txstep); 12263 tiling.setAttributeNS(null, "height", tystep); 12264 tiling.setAttributeNS(null, "x", `${tx0}`); 12265 tiling.setAttributeNS(null, "y", `${ty0}`); 12266 const svg = this.svg; 12267 const transformMatrix = this.transformMatrix; 12268 const fillColor = this.current.fillColor; 12269 const strokeColor = this.current.strokeColor; 12270 const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0); 12271 this.svg = bbox; 12272 this.transformMatrix = matrix; 12273 12274 if (paintType === 2) { 12275 const cssColor = _util.Util.makeHexColor(...color); 12276 12277 this.current.fillColor = cssColor; 12278 this.current.strokeColor = cssColor; 12279 } 12280 12281 this.executeOpTree(this.convertOpList(operatorList)); 12282 this.svg = svg; 12283 this.transformMatrix = transformMatrix; 12284 this.current.fillColor = fillColor; 12285 this.current.strokeColor = strokeColor; 12286 tiling.appendChild(bbox.childNodes[0]); 12287 this.defs.appendChild(tiling); 12288 return `url(#${tilingId})`; 12289 } 12290 12291 _makeShadingPattern(args) { 12292 switch (args[0]) { 12293 case "RadialAxial": 12294 const shadingId = `shading${shadingCount++}`; 12295 const colorStops = args[3]; 12296 let gradient; 12297 12298 switch (args[1]) { 12299 case "axial": 12300 const point0 = args[4]; 12301 const point1 = args[5]; 12302 gradient = this.svgFactory.createElement("svg:linearGradient"); 12303 gradient.setAttributeNS(null, "id", shadingId); 12304 gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse"); 12305 gradient.setAttributeNS(null, "x1", point0[0]); 12306 gradient.setAttributeNS(null, "y1", point0[1]); 12307 gradient.setAttributeNS(null, "x2", point1[0]); 12308 gradient.setAttributeNS(null, "y2", point1[1]); 12309 break; 12310 12311 case "radial": 12312 const focalPoint = args[4]; 12313 const circlePoint = args[5]; 12314 const focalRadius = args[6]; 12315 const circleRadius = args[7]; 12316 gradient = this.svgFactory.createElement("svg:radialGradient"); 12317 gradient.setAttributeNS(null, "id", shadingId); 12318 gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse"); 12319 gradient.setAttributeNS(null, "cx", circlePoint[0]); 12320 gradient.setAttributeNS(null, "cy", circlePoint[1]); 12321 gradient.setAttributeNS(null, "r", circleRadius); 12322 gradient.setAttributeNS(null, "fx", focalPoint[0]); 12323 gradient.setAttributeNS(null, "fy", focalPoint[1]); 12324 gradient.setAttributeNS(null, "fr", focalRadius); 12325 break; 12326 12327 default: 12328 throw new Error(`Unknown RadialAxial type: ${args[1]}`); 12329 } 12330 12331 for (const colorStop of colorStops) { 12332 const stop = this.svgFactory.createElement("svg:stop"); 12333 stop.setAttributeNS(null, "offset", colorStop[0]); 12334 stop.setAttributeNS(null, "stop-color", colorStop[1]); 12335 gradient.appendChild(stop); 12336 } 12337 12338 this.defs.appendChild(gradient); 12339 return `url(#${shadingId})`; 12340 12341 case "Mesh": 12342 (0, _util.warn)("Unimplemented pattern Mesh"); 12343 return null; 12344 12345 case "Dummy": 12346 return "hotpink"; 12347 12348 default: 12349 throw new Error(`Unknown IR type: ${args[0]}`); 12350 } 12351 } 12352 12353 setDash(dashArray, dashPhase) { 12354 this.current.dashArray = dashArray; 12355 this.current.dashPhase = dashPhase; 12356 } 12357 12358 constructPath(ops, args) { 12359 const current = this.current; 12360 let x = current.x, 12361 y = current.y; 12362 let d = []; 12363 let j = 0; 12364 12365 for (const op of ops) { 12366 switch (op | 0) { 12367 case _util.OPS.rectangle: 12368 x = args[j++]; 12369 y = args[j++]; 12370 const width = args[j++]; 12371 const height = args[j++]; 12372 const xw = x + width; 12373 const yh = y + height; 12374 d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z"); 12375 break; 12376 12377 case _util.OPS.moveTo: 12378 x = args[j++]; 12379 y = args[j++]; 12380 d.push("M", pf(x), pf(y)); 12381 break; 12382 12383 case _util.OPS.lineTo: 12384 x = args[j++]; 12385 y = args[j++]; 12386 d.push("L", pf(x), pf(y)); 12387 break; 12388 12389 case _util.OPS.curveTo: 12390 x = args[j + 4]; 12391 y = args[j + 5]; 12392 d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); 12393 j += 6; 12394 break; 12395 12396 case _util.OPS.curveTo2: 12397 d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); 12398 x = args[j + 2]; 12399 y = args[j + 3]; 12400 j += 4; 12401 break; 12402 12403 case _util.OPS.curveTo3: 12404 x = args[j + 2]; 12405 y = args[j + 3]; 12406 d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); 12407 j += 4; 12408 break; 12409 12410 case _util.OPS.closePath: 12411 d.push("Z"); 12412 break; 12413 } 12414 } 12415 12416 d = d.join(" "); 12417 12418 if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) { 12419 d = current.path.getAttributeNS(null, "d") + d; 12420 } else { 12421 current.path = this.svgFactory.createElement("svg:path"); 12422 12423 this._ensureTransformGroup().appendChild(current.path); 12424 } 12425 12426 current.path.setAttributeNS(null, "d", d); 12427 current.path.setAttributeNS(null, "fill", "none"); 12428 current.element = current.path; 12429 current.setCurrentPoint(x, y); 12430 } 12431 12432 endPath() { 12433 const current = this.current; 12434 current.path = null; 12435 12436 if (!this.pendingClip) { 12437 return; 12438 } 12439 12440 if (!current.element) { 12441 this.pendingClip = null; 12442 return; 12443 } 12444 12445 const clipId = `clippath${clipCount++}`; 12446 const clipPath = this.svgFactory.createElement("svg:clipPath"); 12447 clipPath.setAttributeNS(null, "id", clipId); 12448 clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix)); 12449 const clipElement = current.element.cloneNode(true); 12450 12451 if (this.pendingClip === "evenodd") { 12452 clipElement.setAttributeNS(null, "clip-rule", "evenodd"); 12453 } else { 12454 clipElement.setAttributeNS(null, "clip-rule", "nonzero"); 12455 } 12456 12457 this.pendingClip = null; 12458 clipPath.appendChild(clipElement); 12459 this.defs.appendChild(clipPath); 12460 12461 if (current.activeClipUrl) { 12462 current.clipGroup = null; 12463 12464 for (const prev of this.extraStack) { 12465 prev.clipGroup = null; 12466 } 12467 12468 clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl); 12469 } 12470 12471 current.activeClipUrl = `url(#${clipId})`; 12472 this.tgrp = null; 12473 } 12474 12475 clip(type) { 12476 this.pendingClip = type; 12477 } 12478 12479 closePath() { 12480 const current = this.current; 12481 12482 if (current.path) { 12483 const d = `${current.path.getAttributeNS(null, "d")}Z`; 12484 current.path.setAttributeNS(null, "d", d); 12485 } 12486 } 12487 12488 setLeading(leading) { 12489 this.current.leading = -leading; 12490 } 12491 12492 setTextRise(textRise) { 12493 this.current.textRise = textRise; 12494 } 12495 12496 setTextRenderingMode(textRenderingMode) { 12497 this.current.textRenderingMode = textRenderingMode; 12498 } 12499 12500 setHScale(scale) { 12501 this.current.textHScale = scale / 100; 12502 } 12503
12504 setRenderingIntent(intent) {} 12505 12506 setFlatness(flatness) {} 12507 12508 setGState(states) { 12509 for (const [key, value] of states) { 12510 switch (key) { 12511 case "LW": 12512 this.setLineWidth(value); 12513 break; 12514 12515 case "LC": 12516 this.setLineCap(value); 12517 break; 12518 12519 case "LJ": 12520 this.setLineJoin(value); 12521 break; 12522 12523 case "ML": 12524 this.setMiterLimit(value); 12525 break; 12526 12527 case "D": 12528 this.setDash(value[0], value[1]); 12529 break; 12530 12531 case "RI": 12532 this.setRenderingIntent(value); 12533 break; 12534 12535 case "FL": 12536 this.setFlatness(value); 12537 break; 12538 12539 case "Font": 12540 this.setFont(value); 12541 break; 12542 12543 case "CA": 12544 this.setStrokeAlpha(value); 12545 break; 12546 12547 case "ca": 12548 this.setFillAlpha(value); 12549 break; 12550 12551 default: 12552 (0, _util.warn)(`Unimplemented graphic state operator ${key}`); 12553 break; 12554 } 12555 } 12556 } 12557 12558 fill() { 12559 const current = this.current; 12560 12561 if (current.element) { 12562 current.element.setAttributeNS(null, "fill", current.fillColor); 12563 current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha); 12564 this.endPath(); 12565 } 12566 } 12567 12568 stroke() { 12569 const current = this.current; 12570 12571 if (current.element) { 12572 this._setStrokeAttributes(current.element); 12573 12574 current.element.setAttributeNS(null, "fill", "none"); 12575 this.endPath(); 12576 } 12577 } 12578 12579 _setStrokeAttributes(element, lineWidthScale = 1) { 12580 const current = this.current; 12581 let dashArray = current.dashArray; 12582 12583 if (lineWidthScale !== 1 && dashArray.length > 0) { 12584 dashArray = dashArray.map(function (value) { 12585 return lineWidthScale * value; 12586 }); 12587 } 12588 12589 element.setAttributeNS(null, "stroke", current.strokeColor); 12590 element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha); 12591 element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit)); 12592 element.setAttributeNS(null, "stroke-linecap", current.lineCap); 12593 element.setAttributeNS(null, "stroke-linejoin", current.lineJoin); 12594 element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px"); 12595 element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" ")); 12596 element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px"); 12597 } 12598 12599 eoFill() { 12600 if (this.current.element) { 12601 this.current.element.setAttributeNS(null, "fill-rule", "evenodd"); 12602 } 12603 12604 this.fill(); 12605 } 12606 12607 fillStroke() { 12608 this.stroke(); 12609 this.fill(); 12610 } 12611 12612 eoFillStroke() { 12613 if (this.current.element) { 12614 this.current.element.setAttributeNS(null, "fill-rule", "evenodd"); 12615 } 12616 12617 this.fillStroke(); 12618 } 12619 12620 closeStroke() { 12621 this.closePath(); 12622 this.stroke(); 12623 } 12624 12625 closeFillStroke() { 12626 this.closePath(); 12627 this.fillStroke(); 12628 } 12629 12630 closeEOFillStroke() { 12631 this.closePath(); 12632 this.eoFillStroke(); 12633 } 12634 12635 paintSolidColorImageMask() { 12636 const rect = this.svgFactory.createElement("svg:rect"); 12637 rect.setAttributeNS(null, "x", "0"); 12638 rect.setAttributeNS(null, "y", "0"); 12639 rect.setAttributeNS(null, "width", "1px"); 12640 rect.setAttributeNS(null, "height", "1px"); 12641 rect.setAttributeNS(null, "fill", this.current.fillColor); 12642 12643 this._ensureTransformGroup().appendChild(rect); 12644 } 12645 12646 paintImageXObject(objId) { 12647 const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId); 12648 12649 if (!imgData) { 12650 (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`); 12651 return; 12652 } 12653 12654 this.paintInlineImageXObject(imgData); 12655 } 12656 12657 paintInlineImageXObject(imgData, mask) { 12658 const width = imgData.width; 12659 const height = imgData.height; 12660 const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask); 12661 const cliprect = this.svgFactory.createElement("svg:rect"); 12662 cliprect.setAttributeNS(null, "x", "0"); 12663 cliprect.setAttributeNS(null, "y", "0"); 12664 cliprect.setAttributeNS(null, "width", pf(width)); 12665 cliprect.setAttributeNS(null, "height", pf(height)); 12666 this.current.element = cliprect; 12667 this.clip("nonzero"); 12668 const imgEl = this.svgFactory.createElement("svg:image"); 12669 imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc); 12670 imgEl.setAttributeNS(null, "x", "0"); 12671 imgEl.setAttributeNS(null, "y", pf(-height)); 12672 imgEl.setAttributeNS(null, "width", pf(width) + "px"); 12673 imgEl.setAttributeNS(null, "height", pf(height) + "px"); 12674 imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`); 12675 12676 if (mask) { 12677 mask.appendChild(imgEl); 12678 } else { 12679 this._ensureTransformGroup().appendChild(imgEl); 12680 } 12681 } 12682 12683 paintImageMaskXObject(imgData) { 12684 const current = this.current; 12685 const width = imgData.width; 12686 const height = imgData.height; 12687 const fillColor = current.fillColor; 12688 current.maskId = `mask${maskCount++}`; 12689 const mask = this.svgFactory.createElement("svg:mask"); 12690 mask.setAttributeNS(null, "id", current.maskId); 12691 const rect = this.svgFactory.createElement("svg:rect"); 12692 rect.setAttributeNS(null, "x", "0"); 12693 rect.setAttributeNS(null, "y", "0"); 12694 rect.setAttributeNS(null, "width", pf(width)); 12695 rect.setAttributeNS(null, "height", pf(height)); 12696 rect.setAttributeNS(null, "fill", fillColor); 12697 rect.setAttributeNS(null, "mask", `url(#${current.maskId})`); 12698 this.defs.appendChild(mask); 12699 12700 this._ensureTransformGroup().appendChild(rect); 12701 12702 this.paintInlineImageXObject(imgData, mask); 12703 } 12704 12705 paintFormXObjectBegin(matrix, bbox) { 12706 if (Array.isArray(matrix) && matrix.length === 6) {
12707 this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); 12708 } 12709 12710 if (bbox) { 12711 const width = bbox[2] - bbox[0]; 12712 const height = bbox[3] - bbox[1]; 12713 const cliprect = this.svgFactory.createElement("svg:rect"); 12714 cliprect.setAttributeNS(null, "x", bbox[0]); 12715 cliprect.setAttributeNS(null, "y", bbox[1]); 12716 cliprect.setAttributeNS(null, "width", pf(width)); 12717 cliprect.setAttributeNS(null, "height", pf(height)); 12718 this.current.element = cliprect; 12719 this.clip("nonzero"); 12720 this.endPath(); 12721 } 12722 } 12723 12724 paintFormXObjectEnd() {} 12725 12726 _initialize(viewport) { 12727 const svg = this.svgFactory.create(viewport.width, viewport.height); 12728 const definitions = this.svgFactory.createElement("svg:defs"); 12729 svg.appendChild(definitions); 12730 this.defs = definitions; 12731 const rootGroup = this.svgFactory.createElement("svg:g"); 12732 rootGroup.setAttributeNS(null, "transform", pm(viewport.transform)); 12733 svg.appendChild(rootGroup); 12734 this.svg = rootGroup; 12735 return svg; 12736 } 12737 12738 _ensureClipGroup() { 12739 if (!this.current.clipGroup) { 12740 const clipGroup = this.svgFactory.createElement("svg:g"); 12741 clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl); 12742 this.svg.appendChild(clipGroup); 12743 this.current.clipGroup = clipGroup; 12744 } 12745 12746 return this.current.clipGroup; 12747 } 12748 12749 _ensureTransformGroup() { 12750 if (!this.tgrp) { 12751 this.tgrp = this.svgFactory.createElement("svg:g"); 12752 this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix)); 12753 12754 if (this.current.activeClipUrl) { 12755 this._ensureClipGroup().appendChild(this.tgrp); 12756 } else { 12757 this.svg.appendChild(this.tgrp); 12758 } 12759 } 12760 12761 return this.tgrp; 12762 } 12763 12764 }; 12765} 12766 12767/***/ }), 12768/* 21 */ 12769/***/ ((__unused_webpack_module, exports) => { 12770 12771 12772 12773Object.defineProperty(exports, "__esModule", ({ 12774 value: true 12775})); 12776exports.XfaLayer = void 0; 12777 12778class XfaLayer { 12779 static setupStorage(html, id, element, storage, intent) { 12780 const storedData = storage.getValue(id, { 12781 value: null 12782 }); 12783 12784 switch (element.name) { 12785 case "textarea": 12786 if (storedData.value !== null) { 12787 html.textContent = storedData.value; 12788 } 12789 12790 if (intent === "print") { 12791 break; 12792 } 12793 12794 html.addEventListener("input", event => { 12795 storage.setValue(id, { 12796 value: event.target.value 12797 }); 12798 }); 12799 break; 12800 12801 case "input": 12802 if (element.attributes.type === "radio" || element.attributes.type === "checkbox") { 12803 if (storedData.value === element.attributes.xfaOn) { 12804 html.setAttribute("checked", true); 12805 } 12806 12807 if (intent === "print") { 12808 break; 12809 } 12810 12811 html.addEventListener("change", event => { 12812 storage.setValue(id, { 12813 value: event.target.getAttribute("xfaOn") 12814 }); 12815 }); 12816 } else { 12817 if (storedData.value !== null) { 12818 html.setAttribute("value", storedData.value); 12819 } 12820 12821 if (intent === "print") { 12822 break; 12823 } 12824 12825 html.addEventListener("input", event => { 12826 storage.setValue(id, { 12827 value: event.target.value 12828 }); 12829 }); 12830 } 12831 12832 break; 12833 12834 case "select": 12835 if (storedData.value !== null) { 12836 for (const option of element.children) { 12837 if (option.attributes.value === storedData.value) { 12838 option.attributes.selected = true; 12839 } 12840 } 12841 } 12842 12843 html.addEventListener("input", event => { 12844 const options = event.target.options; 12845 const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; 12846 storage.setValue(id, { 12847 value 12848 }); 12849 }); 12850 break; 12851 } 12852 } 12853 12854 static setAttributes(html, element, storage, intent) { 12855 const { 12856 attributes 12857 } = element; 12858 12859 if (attributes.type === "radio") { 12860 attributes.name = `${attributes.name}-${intent}`; 12861 } 12862 12863 for (const [key, value] of Object.entries(attributes)) { 12864 if (value === null || value === undefined || key === "dataId") { 12865 continue; 12866 } 12867 12868 if (key !== "style") { 12869 if (key === "textContent") { 12870 html.textContent = value; 12871 } else if (key === "class") { 12872 html.setAttribute(key, value.join(" ")); 12873 } else { 12874 html.setAttribute(key, value); 12875 } 12876 } else { 12877 Object.assign(html.style, value); 12878 } 12879 } 12880 12881 if (storage && attributes.dataId) { 12882 this.setupStorage(html, attributes.dataId, element, storage); 12883 } 12884 } 12885 12886 static render(parameters) { 12887 const storage = parameters.annotationStorage; 12888 const root = parameters.xfa; 12889 const intent = parameters.intent || "display"; 12890 const rootHtml = document.createElement(root.name); 12891 12892 if (root.attributes) { 12893 this.setAttributes(rootHtml, root); 12894 } 12895 12896 const stack = [[root, -1, rootHtml]]; 12897 const rootDiv = parameters.div; 12898 rootDiv.appendChild(rootHtml); 12899 const transform = `matrix(${parameters.viewport.transform.join(",")})`; 12900 rootDiv.style.transform = transform; 12901 rootDiv.setAttribute("class", "xfaLayer xfaFont"); 12902 12903 while (stack.length > 0) { 12904 const [parent, i, html] = stack[stack.length - 1]; 12905 12906 if (i + 1 === parent.children.length) { 12907 stack.pop(); 12908 continue; 12909 } 12910 12911 const child = parent.children[++stack[stack.length - 1][1]]; 12912 12913 if (child === null) { 12914 continue; 12915 } 12916 12917 const { 12918 name 12919 } = child; 12920 12921 if (name === "#text") { 12922 html.appendChild(document.createTextNode(child.value)); 12923 continue; 12924 } 12925 12926 let childHtml; 12927 12928 if (child?.attributes?.xmlns) { 12929 childHtml = document.createElementNS(child.attributes.xmlns, name); 12930 } else { 12931 childHtml = document.createElement(name); 12932 } 12933 12934 html.appendChild(childHtml); 12935 12936 if (child.attributes) { 12937 this.setAttributes(childHtml, child, storage, intent); 12938 } 12939 12940 if (child.children && child.children.length > 0) { 12941 stack.push([child, -1, childHtml]); 12942 } else if (child.value) { 12943 childHtml.appendChild(document.createTextNode(child.value)); 12944 } 12945 } 12946 12947 for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { 12948 el.setAttribute("readOnly", true); 12949 } 12950 } 12951 12952 static update(parameters) { 12953 const transform = `matrix(${parameters.viewport.transform.join(",")})`; 12954 parameters.div.style.transform = transform; 12955 parameters.div.hidden = false;
12956 } 12957 12958} 12959 12960exports.XfaLayer = XfaLayer; 12961 12962/***/ }), 12963/* 22 */ 12964/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 12965 12966 12967 12968Object.defineProperty(exports, "__esModule", ({ 12969 value: true 12970})); 12971exports.PDFNodeStream = void 0; 12972 12973var _util = __w_pdfjs_require__(2); 12974 12975var _network_utils = __w_pdfjs_require__(23); 12976 12977; 12978 12979const fs = require("fs"); 12980 12981const http = require("http"); 12982 12983const https = require("https"); 12984 12985const url = require("url"); 12986 12987const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//; 12988 12989function parseUrl(sourceUrl) { 12990 const parsedUrl = url.parse(sourceUrl); 12991 12992 if (parsedUrl.protocol === "file:" || parsedUrl.host) { 12993 return parsedUrl; 12994 } 12995 12996 if (/^[a-z]:[/\\]/i.test(sourceUrl)) { 12997 return url.parse(`file:///${sourceUrl}`); 12998 } 12999 13000 if (!parsedUrl.host) { 13001 parsedUrl.protocol = "file:"; 13002 } 13003 13004 return parsedUrl; 13005} 13006 13007class PDFNodeStream { 13008 constructor(source) { 13009 this.source = source; 13010 this.url = parseUrl(source.url); 13011 this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:"; 13012 this.isFsUrl = this.url.protocol === "file:"; 13013 this.httpHeaders = this.isHttp && source.httpHeaders || {}; 13014 this._fullRequestReader = null; 13015 this._rangeRequestReaders = []; 13016 } 13017 13018 get _progressiveDataLength() { 13019 return this._fullRequestReader?._loaded ?? 0; 13020 } 13021 13022 getFullReader() { 13023 (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once."); 13024 this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this); 13025 return this._fullRequestReader; 13026 } 13027 13028 getRangeReader(start, end) { 13029 if (end <= this._progressiveDataLength) { 13030 return null; 13031 } 13032 13033 const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end); 13034 13035 this._rangeRequestReaders.push(rangeReader); 13036 13037 return rangeReader; 13038 } 13039 13040 cancelAllRequests(reason) { 13041 if (this._fullRequestReader) { 13042 this._fullRequestReader.cancel(reason); 13043 } 13044 13045 for (const reader of this._rangeRequestReaders.slice(0)) { 13046 reader.cancel(reason); 13047 } 13048 } 13049 13050} 13051 13052exports.PDFNodeStream = PDFNodeStream; 13053 13054class BaseFullReader { 13055 constructor(stream) { 13056 this._url = stream.url; 13057 this._done = false; 13058 this._storedError = null; 13059 this.onProgress = null; 13060 const source = stream.source; 13061 this._contentLength = source.length; 13062 this._loaded = 0; 13063 this._filename = null; 13064 this._disableRange = source.disableRange || false; 13065 this._rangeChunkSize = source.rangeChunkSize; 13066 13067 if (!this._rangeChunkSize && !this._disableRange) { 13068 this._disableRange = true; 13069 } 13070 13071 this._isStreamingSupported = !source.disableStream; 13072 this._isRangeSupported = !source.disableRange; 13073 this._readableStream = null; 13074 this._readCapability = (0, _util.createPromiseCapability)(); 13075 this._headersCapability = (0, _util.createPromiseCapability)(); 13076 } 13077 13078 get headersReady() { 13079 return this._headersCapability.promise; 13080 } 13081 13082 get filename() { 13083 return this._filename; 13084 } 13085 13086 get contentLength() { 13087 return this._contentLength; 13088 } 13089 13090 get isRangeSupported() { 13091 return this._isRangeSupported; 13092 } 13093 13094 get isStreamingSupported() { 13095 return this._isStreamingSupported; 13096 } 13097 13098 async read() { 13099 await this._readCapability.promise; 13100 13101 if (this._done) { 13102 return { 13103 value: undefined, 13104 done: true 13105 }; 13106 } 13107 13108 if (this._storedError) { 13109 throw this._storedError; 13110 } 13111 13112 const chunk = this._readableStream.read(); 13113 13114 if (chunk === null) { 13115 this._readCapability = (0, _util.createPromiseCapability)(); 13116 return this.read(); 13117 } 13118 13119 this._loaded += chunk.length; 13120 13121 if (this.onProgress) { 13122 this.onProgress({ 13123 loaded: this._loaded, 13124 total: this._contentLength 13125 }); 13126 } 13127 13128 const buffer = new Uint8Array(chunk).buffer; 13129 return { 13130 value: buffer, 13131 done: false 13132 }; 13133 } 13134 13135 cancel(reason) { 13136 if (!this._readableStream) { 13137 this._error(reason); 13138 13139 return; 13140 } 13141 13142 this._readableStream.destroy(reason); 13143 } 13144 13145 _error(reason) { 13146 this._storedError = reason; 13147 13148 this._readCapability.resolve(); 13149 } 13150 13151 _setReadableStream(readableStream) { 13152 this._readableStream = readableStream; 13153 readableStream.on("readable", () => { 13154 this._readCapability.resolve(); 13155 }); 13156 readableStream.on("end", () => { 13157 readableStream.destroy(); 13158 this._done = true; 13159 13160 this._readCapability.resolve(); 13161 }); 13162 readableStream.on("error", reason => { 13163 this._error(reason); 13164 }); 13165 13166 if (!this._isStreamingSupported && this._isRangeSupported) { 13167 this._error(new _util.AbortException("streaming is disabled")); 13168 } 13169 13170 if (this._storedError) { 13171 this._readableStream.destroy(this._storedError); 13172 } 13173 } 13174 13175} 13176 13177class BaseRangeReader { 13178 constructor(stream) { 13179 this._url = stream.url; 13180 this._done = false;
13181 this._storedError = null; 13182 this.onProgress = null; 13183 this._loaded = 0; 13184 this._readableStream = null; 13185 this._readCapability = (0, _util.createPromiseCapability)(); 13186 const source = stream.source; 13187 this._isStreamingSupported = !source.disableStream; 13188 } 13189 13190 get isStreamingSupported() { 13191 return this._isStreamingSupported; 13192 } 13193 13194 async read() { 13195 await this._readCapability.promise; 13196 13197 if (this._done) { 13198 return { 13199 value: undefined, 13200 done: true 13201 }; 13202 } 13203 13204 if (this._storedError) { 13205 throw this._storedError; 13206 } 13207 13208 const chunk = this._readableStream.read(); 13209 13210 if (chunk === null) { 13211 this._readCapability = (0, _util.createPromiseCapability)(); 13212 return this.read(); 13213 } 13214 13215 this._loaded += chunk.length; 13216 13217 if (this.onProgress) { 13218 this.onProgress({ 13219 loaded: this._loaded 13220 }); 13221 } 13222 13223 const buffer = new Uint8Array(chunk).buffer; 13224 return { 13225 value: buffer, 13226 done: false 13227 }; 13228 } 13229 13230 cancel(reason) { 13231 if (!this._readableStream) { 13232 this._error(reason); 13233 13234 return; 13235 } 13236 13237 this._readableStream.destroy(reason); 13238 } 13239 13240 _error(reason) { 13241 this._storedError = reason; 13242 13243 this._readCapability.resolve(); 13244 } 13245 13246 _setReadableStream(readableStream) { 13247 this._readableStream = readableStream; 13248 readableStream.on("readable", () => { 13249 this._readCapability.resolve(); 13250 }); 13251 readableStream.on("end", () => { 13252 readableStream.destroy(); 13253 this._done = true; 13254 13255 this._readCapability.resolve(); 13256 }); 13257 readableStream.on("error", reason => { 13258 this._error(reason); 13259 }); 13260 13261 if (this._storedError) { 13262 this._readableStream.destroy(this._storedError); 13263 } 13264 } 13265 13266} 13267 13268function createRequestOptions(parsedUrl, headers) { 13269 return { 13270 protocol: parsedUrl.protocol, 13271 auth: parsedUrl.auth, 13272 host: parsedUrl.hostname, 13273 port: parsedUrl.port, 13274 path: parsedUrl.path, 13275 method: "GET", 13276 headers 13277 }; 13278} 13279 13280class PDFNodeStreamFullReader extends BaseFullReader { 13281 constructor(stream) { 13282 super(stream); 13283 13284 const handleResponse = response => { 13285 if (response.statusCode === 404) { 13286 const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`); 13287 this._storedError = error; 13288 13289 this._headersCapability.reject(error); 13290 13291 return; 13292 } 13293 13294 this._headersCapability.resolve(); 13295 13296 this._setReadableStream(response); 13297 13298 const getResponseHeader = name => { 13299 return this._readableStream.headers[name.toLowerCase()]; 13300 }; 13301 13302 const { 13303 allowRangeRequests, 13304 suggestedLength 13305 } = (0, _network_utils.validateRangeRequestCapabilities)({ 13306 getResponseHeader, 13307 isHttp: stream.isHttp, 13308 rangeChunkSize: this._rangeChunkSize, 13309 disableRange: this._disableRange 13310 }); 13311 this._isRangeSupported = allowRangeRequests; 13312 this._contentLength = suggestedLength || this._contentLength; 13313 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader); 13314 }; 13315 13316 this._request = null; 13317 13318 if (this._url.protocol === "http:") { 13319 this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse); 13320 } else { 13321 this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse); 13322 } 13323 13324 this._request.on("error", reason => { 13325 this._storedError = reason; 13326 13327 this._headersCapability.reject(reason); 13328 }); 13329 13330 this._request.end(); 13331 } 13332 13333} 13334 13335class PDFNodeStreamRangeReader extends BaseRangeReader { 13336 constructor(stream, start, end) { 13337 super(stream); 13338 this._httpHeaders = {}; 13339 13340 for (const property in stream.httpHeaders) { 13341 const value = stream.httpHeaders[property]; 13342 13343 if (typeof value === "undefined") { 13344 continue; 13345 } 13346 13347 this._httpHeaders[property] = value; 13348 } 13349 13350 this._httpHeaders.Range = `bytes=${start}-${end - 1}`; 13351 13352 const handleResponse = response => { 13353 if (response.statusCode === 404) { 13354 const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`); 13355 this._storedError = error; 13356 return; 13357 } 13358 13359 this._setReadableStream(response); 13360 }; 13361 13362 this._request = null; 13363 13364 if (this._url.protocol === "http:") { 13365 this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse); 13366 } else { 13367 this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse); 13368 } 13369 13370 this._request.on("error", reason => { 13371 this._storedError = reason; 13372 }); 13373 13374 this._request.end(); 13375 } 13376 13377} 13378 13379class PDFNodeStreamFsFullReader extends BaseFullReader { 13380 constructor(stream) { 13381 super(stream); 13382 let path = decodeURIComponent(this._url.path); 13383 13384 if (fileUriRegex.test(this._url.href)) { 13385 path = path.replace(/^\//, ""); 13386 } 13387 13388 fs.lstat(path, (error, stat) => { 13389 if (error) { 13390 if (error.code === "ENOENT") { 13391 error = new _util.MissingPDFException(`Missing PDF "${path}".`); 13392 } 13393 13394 this._storedError = error; 13395 13396 this._headersCapability.reject(error); 13397 13398 return; 13399 } 13400 13401 this._contentLength = stat.size; 13402 13403 this._setReadableStream(fs.createReadStream(path)); 13404 13405 this._headersCapability.resolve(); 13406 }); 13407 } 13408 13409} 13410 13411class PDFNodeStreamFsRangeReader extends BaseRangeReader { 13412 constructor(stream, start, end) { 13413 super(stream); 13414 let path = decodeURIComponent(this._url.path); 13415 13416 if (fileUriRegex.test(this._url.href)) { 13417 path = path.replace(/^\//, ""); 13418 } 13419 13420 this._setReadableStream(fs.createReadStream(path, { 13421 start, 13422 end: end - 1 13423 })); 13424 } 13425 13426} 13427 13428/***/ }), 13429/* 23 */ 13430/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 13431 13432 13433 13434Object.defineProperty(exports, "__esModule", ({ 13435 value: true 13436})); 13437exports.createResponseStatusError = createResponseStatusError; 13438exports.extractFilenameFromHeader = extractFilenameFromHeader; 13439exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities; 13440exports.validateResponseStatus = validateResponseStatus; 13441 13442var _util = __w_pdfjs_require__(2); 13443 13444var _content_disposition = __w_pdfjs_require__(24); 13445 13446var _display_utils = __w_pdfjs_require__(1); 13447 13448function validateRangeRequestCapabilities({ 13449 getResponseHeader, 13450 isHttp, 13451 rangeChunkSize, 13452 disableRange 13453}) { 13454 (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero"); 13455 const returnValues = { 13456 allowRangeRequests: false, 13457 suggestedLength: undefined 13458 }; 13459 const length = parseInt(getResponseHeader("Content-Length"), 10); 13460 13461 if (!Number.isInteger(length)) { 13462 return returnValues; 13463 } 13464 13465 returnValues.suggestedLength = length; 13466 13467 if (length <= 2 * rangeChunkSize) { 13468 return returnValues; 13469 } 13470 13471 if (disableRange || !isHttp) { 13472 return returnValues; 13473 } 13474 13475 if (getResponseHeader("Accept-Ranges") !== "bytes") { 13476 return returnValues; 13477 } 13478 13479 const contentEncoding = getResponseHeader("Content-Encoding") || "identity"; 13480 13481 if (contentEncoding !== "identity") { 13482 return returnValues; 13483 } 13484 13485 returnValues.allowRangeRequests = true; 13486 return returnValues; 13487} 13488 13489function extractFilenameFromHeader(getResponseHeader) { 13490 const contentDisposition = getResponseHeader("Content-Disposition"); 13491 13492 if (contentDisposition) { 13493 let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition); 13494 13495 if (filename.includes("%")) {
13496 try { 13497 filename = decodeURIComponent(filename); 13498 } catch (ex) {} 13499 } 13500 13501 if ((0, _display_utils.isPdfFile)(filename)) { 13502 return filename; 13503 } 13504 } 13505 13506 return null; 13507} 13508 13509function createResponseStatusError(status, url) { 13510 if (status === 404 || status === 0 && url.startsWith("file:")) { 13511 return new _util.MissingPDFException('Missing PDF "' + url + '".'); 13512 } 13513 13514 return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status); 13515} 13516 13517function validateResponseStatus(status) { 13518 return status === 200 || status === 206; 13519} 13520 13521/***/ }), 13522/* 24 */ 13523/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 13524 13525 13526 13527Object.defineProperty(exports, "__esModule", ({ 13528 value: true 13529})); 13530exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader; 13531 13532var _util = __w_pdfjs_require__(2); 13533 13534function getFilenameFromContentDispositionHeader(contentDisposition) { 13535 let needsEncodingFixup = true; 13536 let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); 13537 13538 if (tmp) { 13539 tmp = tmp[1]; 13540 let filename = rfc2616unquote(tmp); 13541 filename = unescape(filename); 13542 filename = rfc5987decode(filename); 13543 filename = rfc2047decode(filename); 13544 return fixupEncoding(filename); 13545 } 13546 13547 tmp = rfc2231getparam(contentDisposition); 13548 13549 if (tmp) { 13550 const filename = rfc2047decode(tmp); 13551 return fixupEncoding(filename); 13552 } 13553 13554 tmp = toParamRegExp("filename", "i").exec(contentDisposition); 13555 13556 if (tmp) { 13557 tmp = tmp[1]; 13558 let filename = rfc2616unquote(tmp); 13559 filename = rfc2047decode(filename); 13560 return fixupEncoding(filename); 13561 } 13562 13563 function toParamRegExp(attributePattern, flags) { 13564 return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags); 13565 } 13566 13567 function textdecode(encoding, value) { 13568 if (encoding) { 13569 if (!/^[\x00-\xFF]+$/.test(value)) { 13570 return value; 13571 } 13572 13573 try { 13574 const decoder = new TextDecoder(encoding, { 13575 fatal: true 13576 }); 13577 const buffer = (0, _util.stringToBytes)(value); 13578 value = decoder.decode(buffer); 13579 needsEncodingFixup = false; 13580 } catch (e) { 13581 if (/^utf-?8$/i.test(encoding)) { 13582 try { 13583 value = decodeURIComponent(escape(value)); 13584 needsEncodingFixup = false; 13585 } catch (err) {} 13586 } 13587 } 13588 } 13589 13590 return value; 13591 } 13592 13593 function fixupEncoding(value) { 13594 if (needsEncodingFixup && /[\x80-\xff]/.test(value)) { 13595 value = textdecode("utf-8", value); 13596 13597 if (needsEncodingFixup) { 13598 value = textdecode("iso-8859-1", value); 13599 } 13600 } 13601 13602 return value; 13603 } 13604 13605 function rfc2231getparam(contentDispositionStr) { 13606 const matches = []; 13607 let match; 13608 const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig"); 13609 13610 while ((match = iter.exec(contentDispositionStr)) !== null) { 13611 let [, n, quot, part] = match; 13612 n = parseInt(n, 10); 13613 13614 if (n in matches) { 13615 if (n === 0) { 13616 break; 13617 } 13618 13619 continue; 13620 } 13621 13622 matches[n] = [quot, part]; 13623 } 13624 13625 const parts = []; 13626 13627 for (let n = 0; n < matches.length; ++n) { 13628 if (!(n in matches)) { 13629 break; 13630 } 13631 13632 let [quot, part] = matches[n]; 13633 part = rfc2616unquote(part); 13634 13635 if (quot) { 13636 part = unescape(part); 13637 13638 if (n === 0) { 13639 part = rfc5987decode(part); 13640 } 13641 } 13642 13643 parts.push(part); 13644 } 13645 13646 return parts.join(""); 13647 } 13648 13649 function rfc2616unquote(value) { 13650 if (value.startsWith('"')) { 13651 const parts = value.slice(1).split('\\"'); 13652 13653 for (let i = 0; i < parts.length; ++i) { 13654 const quotindex = parts[i].indexOf('"'); 13655 13656 if (quotindex !== -1) { 13657 parts[i] = parts[i].slice(0, quotindex); 13658 parts.length = i + 1; 13659 } 13660 13661 parts[i] = parts[i].replace(/\\(.)/g, "$1"); 13662 } 13663 13664 value = parts.join('"'); 13665 } 13666 13667 return value; 13668 } 13669 13670 function rfc5987decode(extvalue) { 13671 const encodingend = extvalue.indexOf("'"); 13672 13673 if (encodingend === -1) { 13674 return extvalue; 13675 } 13676 13677 const encoding = extvalue.slice(0, encodingend); 13678 const langvalue = extvalue.slice(encodingend + 1); 13679 const value = langvalue.replace(/^[^']*'/, ""); 13680 return textdecode(encoding, value); 13681 } 13682 13683 function rfc2047decode(value) { 13684 if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) { 13685 return value; 13686 } 13687 13688 return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) { 13689 if (encoding === "q" || encoding === "Q") { 13690 text = text.replace(/_/g, " "); 13691 text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) { 13692 return String.fromCharCode(parseInt(hex, 16)); 13693 }); 13694 return textdecode(charset, text); 13695 } 13696
13697 try { 13698 text = atob(text); 13699 } catch (e) {} 13700 13701 return textdecode(charset, text); 13702 }); 13703 } 13704 13705 return ""; 13706} 13707 13708/***/ }), 13709/* 25 */ 13710/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 13711 13712 13713 13714Object.defineProperty(exports, "__esModule", ({ 13715 value: true 13716})); 13717exports.PDFNetworkStream = void 0; 13718 13719var _util = __w_pdfjs_require__(2); 13720 13721var _network_utils = __w_pdfjs_require__(23); 13722 13723; 13724const OK_RESPONSE = 200; 13725const PARTIAL_CONTENT_RESPONSE = 206; 13726 13727function getArrayBuffer(xhr) { 13728 const data = xhr.response; 13729 13730 if (typeof data !== "string") { 13731 return data; 13732 } 13733 13734 const array = (0, _util.stringToBytes)(data); 13735 return array.buffer; 13736} 13737 13738class NetworkManager { 13739 constructor(url, args) { 13740 this.url = url; 13741 args = args || {}; 13742 this.isHttp = /^https?:/i.test(url); 13743 this.httpHeaders = this.isHttp && args.httpHeaders || {}; 13744 this.withCredentials = args.withCredentials || false; 13745 13746 this.getXhr = args.getXhr || function NetworkManager_getXhr() { 13747 return new XMLHttpRequest(); 13748 }; 13749 13750 this.currXhrId = 0; 13751 this.pendingRequests = Object.create(null); 13752 } 13753 13754 requestRange(begin, end, listeners) { 13755 const args = { 13756 begin, 13757 end 13758 }; 13759 13760 for (const prop in listeners) { 13761 args[prop] = listeners[prop]; 13762 } 13763 13764 return this.request(args); 13765 } 13766 13767 requestFull(listeners) { 13768 return this.request(listeners); 13769 } 13770 13771 request(args) { 13772 const xhr = this.getXhr(); 13773 const xhrId = this.currXhrId++; 13774 const pendingRequest = this.pendingRequests[xhrId] = { 13775 xhr 13776 }; 13777 xhr.open("GET", this.url); 13778 xhr.withCredentials = this.withCredentials; 13779 13780 for (const property in this.httpHeaders) { 13781 const value = this.httpHeaders[property]; 13782 13783 if (typeof value === "undefined") { 13784 continue; 13785 } 13786 13787 xhr.setRequestHeader(property, value); 13788 } 13789 13790 if (this.isHttp && "begin" in args && "end" in args) { 13791 xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`); 13792 pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE; 13793 } else { 13794 pendingRequest.expectedStatus = OK_RESPONSE; 13795 } 13796 13797 xhr.responseType = "arraybuffer"; 13798 13799 if (args.onError) { 13800 xhr.onerror = function (evt) { 13801 args.onError(xhr.status); 13802 }; 13803 } 13804 13805 xhr.onreadystatechange = this.onStateChange.bind(this, xhrId); 13806 xhr.onprogress = this.onProgress.bind(this, xhrId); 13807 pendingRequest.onHeadersReceived = args.onHeadersReceived; 13808 pendingRequest.onDone = args.onDone; 13809 pendingRequest.onError = args.onError; 13810 pendingRequest.onProgress = args.onProgress; 13811 xhr.send(null); 13812 return xhrId; 13813 } 13814 13815 onProgress(xhrId, evt) { 13816 const pendingRequest = this.pendingRequests[xhrId]; 13817 13818 if (!pendingRequest) { 13819 return; 13820 } 13821 13822 if (pendingRequest.onProgress) { 13823 pendingRequest.onProgress(evt); 13824 } 13825 } 13826 13827 onStateChange(xhrId, evt) { 13828 const pendingRequest = this.pendingRequests[xhrId]; 13829 13830 if (!pendingRequest) { 13831 return; 13832 } 13833 13834 const xhr = pendingRequest.xhr; 13835 13836 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { 13837 pendingRequest.onHeadersReceived(); 13838 delete pendingRequest.onHeadersReceived; 13839 } 13840 13841 if (xhr.readyState !== 4) { 13842 return; 13843 } 13844 13845 if (!(xhrId in this.pendingRequests)) { 13846 return; 13847 } 13848 13849 delete this.pendingRequests[xhrId]; 13850 13851 if (xhr.status === 0 && this.isHttp) { 13852 if (pendingRequest.onError) { 13853 pendingRequest.onError(xhr.status); 13854 } 13855 13856 return; 13857 } 13858 13859 const xhrStatus = xhr.status || OK_RESPONSE; 13860 const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE; 13861 13862 if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) { 13863 if (pendingRequest.onError) { 13864 pendingRequest.onError(xhr.status); 13865 } 13866 13867 return; 13868 } 13869 13870 const chunk = getArrayBuffer(xhr); 13871 13872 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { 13873 const rangeHeader = xhr.getResponseHeader("Content-Range"); 13874 const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader); 13875 pendingRequest.onDone({ 13876 begin: parseInt(matches[1], 10), 13877 chunk 13878 }); 13879 } else if (chunk) { 13880 pendingRequest.onDone({ 13881 begin: 0, 13882 chunk 13883 }); 13884 } else if (pendingRequest.onError) { 13885 pendingRequest.onError(xhr.status); 13886 } 13887 } 13888 13889 getRequestXhr(xhrId) { 13890 return this.pendingRequests[xhrId].xhr; 13891 } 13892 13893 isPendingRequest(xhrId) { 13894 return xhrId in this.pendingRequests; 13895 } 13896
13897 abortRequest(xhrId) { 13898 const xhr = this.pendingRequests[xhrId].xhr; 13899 delete this.pendingRequests[xhrId]; 13900 xhr.abort(); 13901 } 13902 13903} 13904 13905class PDFNetworkStream { 13906 constructor(source) { 13907 this._source = source; 13908 this._manager = new NetworkManager(source.url, { 13909 httpHeaders: source.httpHeaders, 13910 withCredentials: source.withCredentials 13911 }); 13912 this._rangeChunkSize = source.rangeChunkSize; 13913 this._fullRequestReader = null; 13914 this._rangeRequestReaders = []; 13915 } 13916 13917 _onRangeRequestReaderClosed(reader) { 13918 const i = this._rangeRequestReaders.indexOf(reader); 13919 13920 if (i >= 0) { 13921 this._rangeRequestReaders.splice(i, 1); 13922 } 13923 } 13924 13925 getFullReader() { 13926 (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once."); 13927 this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source); 13928 return this._fullRequestReader; 13929 } 13930 13931 getRangeReader(begin, end) { 13932 const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end); 13933 reader.onClosed = this._onRangeRequestReaderClosed.bind(this); 13934 13935 this._rangeRequestReaders.push(reader); 13936 13937 return reader; 13938 } 13939 13940 cancelAllRequests(reason) { 13941 if (this._fullRequestReader) { 13942 this._fullRequestReader.cancel(reason); 13943 } 13944 13945 for (const reader of this._rangeRequestReaders.slice(0)) { 13946 reader.cancel(reason); 13947 } 13948 } 13949 13950} 13951 13952exports.PDFNetworkStream = PDFNetworkStream; 13953 13954class PDFNetworkStreamFullRequestReader { 13955 constructor(manager, source) { 13956 this._manager = manager; 13957 const args = { 13958 onHeadersReceived: this._onHeadersReceived.bind(this), 13959 onDone: this._onDone.bind(this), 13960 onError: this._onError.bind(this), 13961 onProgress: this._onProgress.bind(this) 13962 }; 13963 this._url = source.url; 13964 this._fullRequestId = manager.requestFull(args); 13965 this._headersReceivedCapability = (0, _util.createPromiseCapability)(); 13966 this._disableRange = source.disableRange || false; 13967 this._contentLength = source.length; 13968 this._rangeChunkSize = source.rangeChunkSize; 13969 13970 if (!this._rangeChunkSize && !this._disableRange) { 13971 this._disableRange = true; 13972 } 13973 13974 this._isStreamingSupported = false; 13975 this._isRangeSupported = false; 13976 this._cachedChunks = []; 13977 this._requests = []; 13978 this._done = false; 13979 this._storedError = undefined; 13980 this._filename = null; 13981 this.onProgress = null; 13982 } 13983 13984 _onHeadersReceived() { 13985 const fullRequestXhrId = this._fullRequestId; 13986 13987 const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); 13988 13989 const getResponseHeader = name => { 13990 return fullRequestXhr.getResponseHeader(name); 13991 }; 13992 13993 const { 13994 allowRangeRequests, 13995 suggestedLength 13996 } = (0, _network_utils.validateRangeRequestCapabilities)({ 13997 getResponseHeader, 13998 isHttp: this._manager.isHttp, 13999 rangeChunkSize: this._rangeChunkSize, 14000 disableRange: this._disableRange 14001 }); 14002 14003 if (allowRangeRequests) { 14004 this._isRangeSupported = true; 14005 } 14006 14007 this._contentLength = suggestedLength || this._contentLength; 14008 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader); 14009 14010 if (this._isRangeSupported) { 14011 this._manager.abortRequest(fullRequestXhrId); 14012 } 14013 14014 this._headersReceivedCapability.resolve(); 14015 } 14016 14017 _onDone(args) { 14018 if (args) { 14019 if (this._requests.length > 0) { 14020 const requestCapability = this._requests.shift(); 14021 14022 requestCapability.resolve({ 14023 value: args.chunk, 14024 done: false 14025 }); 14026 } else { 14027 this._cachedChunks.push(args.chunk); 14028 } 14029 } 14030 14031 this._done = true; 14032 14033 if (this._cachedChunks.length > 0) { 14034 return; 14035 } 14036 14037 for (const requestCapability of this._requests) { 14038 requestCapability.resolve({ 14039 value: undefined, 14040 done: true 14041 }); 14042 } 14043 14044 this._requests.length = 0; 14045 } 14046 14047 _onError(status) { 14048 const url = this._url; 14049 const exception = (0, _network_utils.createResponseStatusError)(status, url); 14050 this._storedError = exception; 14051 14052 this._headersReceivedCapability.reject(exception); 14053 14054 for (const requestCapability of this._requests) { 14055 requestCapability.reject(exception); 14056 } 14057 14058 this._requests.length = 0; 14059 this._cachedChunks.length = 0; 14060 } 14061 14062 _onProgress(data) { 14063 if (this.onProgress) { 14064 this.onProgress({ 14065 loaded: data.loaded, 14066 total: data.lengthComputable ? data.total : this._contentLength 14067 }); 14068 } 14069 } 14070 14071 get filename() { 14072 return this._filename; 14073 } 14074 14075 get isRangeSupported() { 14076 return this._isRangeSupported; 14077 } 14078 14079 get isStreamingSupported() { 14080 return this._isStreamingSupported; 14081 } 14082 14083 get contentLength() { 14084 return this._contentLength; 14085 } 14086 14087 get headersReady() { 14088 return this._headersReceivedCapability.promise; 14089 } 14090 14091 async read() { 14092 if (this._storedError) { 14093 throw this._storedError; 14094 } 14095 14096 if (this._cachedChunks.length > 0) { 14097 const chunk = this._cachedChunks.shift(); 14098 14099 return { 14100 value: chunk, 14101 done: false 14102 }; 14103 } 14104 14105 if (this._done) { 14106 return { 14107 value: undefined, 14108 done: true 14109 }; 14110 } 14111 14112 const requestCapability = (0, _util.createPromiseCapability)(); 14113 14114 this._requests.push(requestCapability); 14115 14116 return requestCapability.promise; 14117 } 14118 14119 cancel(reason) { 14120 this._done = true; 14121 14122 this._headersReceivedCapability.reject(reason); 14123 14124 for (const requestCapability of this._requests) { 14125 requestCapability.resolve({ 14126 value: undefined, 14127 done: true 14128 }); 14129 } 14130 14131 this._requests.length = 0; 14132 14133 if (this._manager.isPendingRequest(this._fullRequestId)) {
14134 this._manager.abortRequest(this._fullRequestId); 14135 } 14136 14137 this._fullRequestReader = null; 14138 } 14139 14140} 14141 14142class PDFNetworkStreamRangeRequestReader { 14143 constructor(manager, begin, end) { 14144 this._manager = manager; 14145 const args = { 14146 onDone: this._onDone.bind(this), 14147 onProgress: this._onProgress.bind(this) 14148 }; 14149 this._requestId = manager.requestRange(begin, end, args); 14150 this._requests = []; 14151 this._queuedChunk = null; 14152 this._done = false; 14153 this.onProgress = null; 14154 this.onClosed = null; 14155 } 14156 14157 _close() { 14158 if (this.onClosed) { 14159 this.onClosed(this); 14160 } 14161 } 14162 14163 _onDone(data) { 14164 const chunk = data.chunk; 14165 14166 if (this._requests.length > 0) { 14167 const requestCapability = this._requests.shift(); 14168 14169 requestCapability.resolve({ 14170 value: chunk, 14171 done: false 14172 }); 14173 } else { 14174 this._queuedChunk = chunk; 14175 } 14176 14177 this._done = true; 14178 14179 for (const requestCapability of this._requests) { 14180 requestCapability.resolve({ 14181 value: undefined, 14182 done: true 14183 }); 14184 } 14185 14186 this._requests.length = 0; 14187 14188 this._close(); 14189 } 14190 14191 _onProgress(evt) { 14192 if (!this.isStreamingSupported && this.onProgress) { 14193 this.onProgress({ 14194 loaded: evt.loaded 14195 }); 14196 } 14197 } 14198 14199 get isStreamingSupported() { 14200 return false; 14201 } 14202 14203 async read() { 14204 if (this._queuedChunk !== null) { 14205 const chunk = this._queuedChunk; 14206 this._queuedChunk = null; 14207 return { 14208 value: chunk, 14209 done: false 14210 }; 14211 } 14212 14213 if (this._done) { 14214 return { 14215 value: undefined, 14216 done: true 14217 }; 14218 } 14219 14220 const requestCapability = (0, _util.createPromiseCapability)(); 14221 14222 this._requests.push(requestCapability); 14223 14224 return requestCapability.promise; 14225 } 14226 14227 cancel(reason) { 14228 this._done = true; 14229 14230 for (const requestCapability of this._requests) { 14231 requestCapability.resolve({ 14232 value: undefined, 14233 done: true 14234 }); 14235 } 14236 14237 this._requests.length = 0; 14238 14239 if (this._manager.isPendingRequest(this._requestId)) { 14240 this._manager.abortRequest(this._requestId); 14241 } 14242 14243 this._close(); 14244 } 14245 14246} 14247 14248/***/ }), 14249/* 26 */ 14250/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { 14251 14252 14253 14254Object.defineProperty(exports, "__esModule", ({ 14255 value: true 14256})); 14257exports.PDFFetchStream = void 0; 14258 14259var _util = __w_pdfjs_require__(2); 14260 14261var _network_utils = __w_pdfjs_require__(23); 14262 14263; 14264 14265function createFetchOptions(headers, withCredentials, abortController) { 14266 return { 14267 method: "GET", 14268 headers, 14269 signal: abortController?.signal, 14270 mode: "cors", 14271 credentials: withCredentials ? "include" : "same-origin", 14272 redirect: "follow" 14273 }; 14274} 14275 14276function createHeaders(httpHeaders) { 14277 const headers = new Headers(); 14278 14279 for (const property in httpHeaders) { 14280 const value = httpHeaders[property]; 14281 14282 if (typeof value === "undefined") { 14283 continue; 14284 } 14285 14286 headers.append(property, value); 14287 } 14288 14289 return headers; 14290} 14291 14292class PDFFetchStream { 14293 constructor(source) { 14294 this.source = source; 14295 this.isHttp = /^https?:/i.test(source.url); 14296 this.httpHeaders = this.isHttp && source.httpHeaders || {}; 14297 this._fullRequestReader = null; 14298 this._rangeRequestReaders = []; 14299 } 14300 14301 get _progressiveDataLength() { 14302 return this._fullRequestReader?._loaded ?? 0; 14303 } 14304 14305 getFullReader() { 14306 (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once."); 14307 this._fullRequestReader = new PDFFetchStreamReader(this); 14308 return this._fullRequestReader; 14309 } 14310 14311 getRangeReader(begin, end) { 14312 if (end <= this._progressiveDataLength) { 14313 return null; 14314 } 14315 14316 const reader = new PDFFetchStreamRangeReader(this, begin, end); 14317 14318 this._rangeRequestReaders.push(reader); 14319 14320 return reader; 14321 } 14322 14323 cancelAllRequests(reason) { 14324 if (this._fullRequestReader) { 14325 this._fullRequestReader.cancel(reason); 14326 } 14327 14328 for (const reader of this._rangeRequestReaders.slice(0)) { 14329 reader.cancel(reason); 14330 } 14331 } 14332 14333} 14334 14335exports.PDFFetchStream = PDFFetchStream; 14336 14337class PDFFetchStreamReader { 14338 constructor(stream) { 14339 this._stream = stream; 14340 this._reader = null; 14341 this._loaded = 0; 14342 this._filename = null; 14343 const source = stream.source; 14344 this._withCredentials = source.withCredentials || false; 14345 this._contentLength = source.length; 14346 this._headersCapability = (0, _util.createPromiseCapability)();
14347 this._disableRange = source.disableRange || false; 14348 this._rangeChunkSize = source.rangeChunkSize; 14349 14350 if (!this._rangeChunkSize && !this._disableRange) { 14351 this._disableRange = true; 14352 } 14353 14354 if (typeof AbortController !== "undefined") { 14355 this._abortController = new AbortController(); 14356 } 14357 14358 this._isStreamingSupported = !source.disableStream; 14359 this._isRangeSupported = !source.disableRange; 14360 this._headers = createHeaders(this._stream.httpHeaders); 14361 const url = source.url; 14362 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => { 14363 if (!(0, _network_utils.validateResponseStatus)(response.status)) { 14364 throw (0, _network_utils.createResponseStatusError)(response.status, url); 14365 } 14366 14367 this._reader = response.body.getReader(); 14368 14369 this._headersCapability.resolve(); 14370 14371 const getResponseHeader = name => { 14372 return response.headers.get(name); 14373 }; 14374 14375 const { 14376 allowRangeRequests, 14377 suggestedLength 14378 } = (0, _network_utils.validateRangeRequestCapabilities)({ 14379 getResponseHeader, 14380 isHttp: this._stream.isHttp, 14381 rangeChunkSize: this._rangeChunkSize, 14382 disableRange: this._disableRange 14383 }); 14384 this._isRangeSupported = allowRangeRequests; 14385 this._contentLength = suggestedLength || this._contentLength; 14386 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader); 14387 14388 if (!this._isStreamingSupported && this._isRangeSupported) { 14389 this.cancel(new _util.AbortException("Streaming is disabled.")); 14390 } 14391 }).catch(this._headersCapability.reject); 14392 this.onProgress = null; 14393 } 14394 14395 get headersReady() { 14396 return this._headersCapability.promise; 14397 } 14398 14399 get filename() { 14400 return this._filename; 14401 } 14402 14403 get contentLength() { 14404 return this._contentLength; 14405 } 14406 14407 get isRangeSupported() { 14408 return this._isRangeSupported; 14409 } 14410 14411 get isStreamingSupported() { 14412 return this._isStreamingSupported; 14413 } 14414 14415 async read() { 14416 await this._headersCapability.promise; 14417 const { 14418 value, 14419 done 14420 } = await this._reader.read(); 14421 14422 if (done) { 14423 return { 14424 value, 14425 done 14426 }; 14427 } 14428 14429 this._loaded += value.byteLength; 14430 14431 if (this.onProgress) { 14432 this.onProgress({ 14433 loaded: this._loaded, 14434 total: this._contentLength 14435 }); 14436 } 14437 14438 const buffer = new Uint8Array(value).buffer; 14439 return { 14440 value: buffer, 14441 done: false 14442 }; 14443 } 14444 14445 cancel(reason) { 14446 if (this._reader) { 14447 this._reader.cancel(reason); 14448 } 14449 14450 if (this._abortController) { 14451 this._abortController.abort(); 14452 } 14453 } 14454 14455} 14456 14457class PDFFetchStreamRangeReader { 14458 constructor(stream, begin, end) { 14459 this._stream = stream; 14460 this._reader = null; 14461 this._loaded = 0; 14462 const source = stream.source; 14463 this._withCredentials = source.withCredentials || false; 14464 this._readCapability = (0, _util.createPromiseCapability)(); 14465 this._isStreamingSupported = !source.disableStream; 14466 14467 if (typeof AbortController !== "undefined") { 14468 this._abortController = new AbortController(); 14469 } 14470 14471 this._headers = createHeaders(this._stream.httpHeaders); 14472 14473 this._headers.append("Range", `bytes=${begin}-${end - 1}`); 14474 14475 const url = source.url; 14476 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => { 14477 if (!(0, _network_utils.validateResponseStatus)(response.status)) { 14478 throw (0, _network_utils.createResponseStatusError)(response.status, url); 14479 } 14480 14481 this._readCapability.resolve(); 14482 14483 this._reader = response.body.getReader(); 14484 }).catch(reason => { 14485 if (reason?.name === "AbortError") { 14486 return; 14487 } 14488 14489 throw reason; 14490 }); 14491 this.onProgress = null; 14492 } 14493 14494 get isStreamingSupported() { 14495 return this._isStreamingSupported; 14496 } 14497 14498 async read() { 14499 await this._readCapability.promise; 14500 const { 14501 value, 14502 done 14503 } = await this._reader.read(); 14504 14505 if (done) { 14506 return { 14507 value, 14508 done 14509 }; 14510 } 14511 14512 this._loaded += value.byteLength; 14513 14514 if (this.onProgress) { 14515 this.onProgress({ 14516 loaded: this._loaded 14517 }); 14518 } 14519 14520 const buffer = new Uint8Array(value).buffer; 14521 return { 14522 value: buffer, 14523 done: false 14524 }; 14525 } 14526 14527 cancel(reason) { 14528 if (this._reader) { 14529 this._reader.cancel(reason); 14530 } 14531 14532 if (this._abortController) { 14533 this._abortController.abort(); 14534 } 14535 } 14536 14537} 14538 14539/***/ }) 14540/******/ ]); 14541/************************************************************************/ 14542/******/ // The module cache 14543/******/ var __webpack_module_cache__ = {}; 14544/******/ 14545/******/ // The require function 14546/******/ function __w_pdfjs_require__(moduleId) { 14547/******/ // Check if module is in cache 14548/******/ var cachedModule = __webpack_module_cache__[moduleId]; 14549/******/ if (cachedModule !== undefined) { 14550/******/ return cachedModule.exports; 14551/******/ } 14552/******/ // Create a new module (and put it into the cache) 14553/******/ var module = __webpack_module_cache__[moduleId] = { 14554/******/ // no module.id needed 14555/******/ // no module.loaded needed 14556/******/ exports: {} 14557/******/ }; 14558/******/ 14559/******/ // Execute the module function 14560/******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__); 14561/******/ 14562/******/ // Return the exports of the module 14563/******/ return module.exports; 14564/******/ } 14565/******/ 14566/************************************************************************/ 14567var __webpack_exports__ = {}; 14568// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. 14569(() => { 14570var exports = __webpack_exports__; 14571 14572 14573Object.defineProperty(exports, "__esModule", ({ 14574 value: true 14575})); 14576Object.defineProperty(exports, "addLinkAttributes", ({ 14577 enumerable: true, 14578 get: function () { 14579 return _display_utils.addLinkAttributes; 14580 } 14581})); 14582Object.defineProperty(exports, "getFilenameFromUrl", ({ 14583 enumerable: true, 14584 get: function () { 14585 return _display_utils.getFilenameFromUrl; 14586 } 14587})); 14588Object.defineProperty(exports, "getPdfFilenameFromUrl", ({ 14589 enumerable: true, 14590 get: function () { 14591 return _display_utils.getPdfFilenameFromUrl; 14592 } 14593})); 14594Object.defineProperty(exports, "getXfaPageViewport", ({ 14595 enumerable: true, 14596 get: function () { 14597 return _display_utils.getXfaPageViewport; 14598 } 14599})); 14600Object.defineProperty(exports, "isPdfFile", ({ 14601 enumerable: true, 14602 get: function () { 14603 return _display_utils.isPdfFile; 14604 } 14605})); 14606Object.defineProperty(exports, "LinkTarget", ({ 14607 enumerable: true, 14608 get: function () { 14609 return _display_utils.LinkTarget; 14610 } 14611})); 14612Object.defineProperty(exports, "loadScript", ({ 14613 enumerable: true, 14614 get: function () { 14615 return _display_utils.loadScript; 14616 } 14617})); 14618Object.defineProperty(exports, "PDFDateString", ({ 14619 enumerable: true, 14620 get: function () { 14621 return _display_utils.PDFDateString; 14622 } 14623})); 14624Object.defineProperty(exports, "RenderingCancelledException", ({ 14625 enumerable: true, 14626 get: function () { 14627 return _display_utils.RenderingCancelledException; 14628 } 14629}));
14630Object.defineProperty(exports, "build", ({ 14631 enumerable: true, 14632 get: function () { 14633 return _api.build; 14634 } 14635})); 14636Object.defineProperty(exports, "getDocument", ({ 14637 enumerable: true, 14638 get: function () { 14639 return _api.getDocument; 14640 } 14641})); 14642Object.defineProperty(exports, "LoopbackPort", ({ 14643 enumerable: true, 14644 get: function () { 14645 return _api.LoopbackPort; 14646 } 14647})); 14648Object.defineProperty(exports, "PDFDataRangeTransport", ({ 14649 enumerable: true, 14650 get: function () { 14651 return _api.PDFDataRangeTransport; 14652 } 14653})); 14654Object.defineProperty(exports, "PDFWorker", ({ 14655 enumerable: true, 14656 get: function () { 14657 return _api.PDFWorker; 14658 } 14659})); 14660Object.defineProperty(exports, "version", ({ 14661 enumerable: true, 14662 get: function () { 14663 return _api.version; 14664 } 14665})); 14666Object.defineProperty(exports, "CMapCompressionType", ({ 14667 enumerable: true, 14668 get: function () { 14669 return _util.CMapCompressionType; 14670 } 14671})); 14672Object.defineProperty(exports, "createObjectURL", ({ 14673 enumerable: true, 14674 get: function () { 14675 return _util.createObjectURL; 14676 } 14677})); 14678Object.defineProperty(exports, "createPromiseCapability", ({ 14679 enumerable: true, 14680 get: function () { 14681 return _util.createPromiseCapability; 14682 } 14683})); 14684Object.defineProperty(exports, "createValidAbsoluteUrl", ({ 14685 enumerable: true, 14686 get: function () { 14687 return _util.createValidAbsoluteUrl; 14688 } 14689})); 14690Object.defineProperty(exports, "InvalidPDFException", ({ 14691 enumerable: true, 14692 get: function () { 14693 return _util.InvalidPDFException; 14694 } 14695})); 14696Object.defineProperty(exports, "MissingPDFException", ({ 14697 enumerable: true, 14698 get: function () { 14699 return _util.MissingPDFException; 14700 } 14701})); 14702Object.defineProperty(exports, "OPS", ({ 14703 enumerable: true, 14704 get: function () { 14705 return _util.OPS; 14706 } 14707})); 14708Object.defineProperty(exports, "PasswordResponses", ({ 14709 enumerable: true, 14710 get: function () { 14711 return _util.PasswordResponses; 14712 } 14713})); 14714Object.defineProperty(exports, "PermissionFlag", ({ 14715 enumerable: true, 14716 get: function () { 14717 return _util.PermissionFlag; 14718 } 14719})); 14720Object.defineProperty(exports, "removeNullCharacters", ({ 14721 enumerable: true, 14722 get: function () { 14723 return _util.removeNullCharacters; 14724 } 14725})); 14726Object.defineProperty(exports, "shadow", ({ 14727 enumerable: true, 14728 get: function () { 14729 return _util.shadow; 14730 } 14731})); 14732Object.defineProperty(exports, "UnexpectedResponseException", ({ 14733 enumerable: true, 14734 get: function () { 14735 return _util.UnexpectedResponseException; 14736 } 14737})); 14738Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({ 14739 enumerable: true, 14740 get: function () { 14741 return _util.UNSUPPORTED_FEATURES; 14742 } 14743})); 14744Object.defineProperty(exports, "Util", ({ 14745 enumerable: true, 14746 get: function () { 14747 return _util.Util; 14748 } 14749})); 14750Object.defineProperty(exports, "VerbosityLevel", ({ 14751 enumerable: true, 14752 get: function () { 14753 return _util.VerbosityLevel; 14754 } 14755})); 14756Object.defineProperty(exports, "AnnotationLayer", ({ 14757 enumerable: true, 14758 get: function () { 14759 return _annotation_layer.AnnotationLayer; 14760 } 14761})); 14762Object.defineProperty(exports, "GlobalWorkerOptions", ({ 14763 enumerable: true, 14764 get: function () { 14765 return _worker_options.GlobalWorkerOptions; 14766 } 14767})); 14768Object.defineProperty(exports, "renderTextLayer", ({ 14769 enumerable: true, 14770 get: function () { 14771 return _text_layer.renderTextLayer; 14772 } 14773})); 14774Object.defineProperty(exports, "SVGGraphics", ({ 14775 enumerable: true, 14776 get: function () { 14777 return _svg.SVGGraphics; 14778 } 14779})); 14780Object.defineProperty(exports, "XfaLayer", ({ 14781 enumerable: true, 14782 get: function () { 14783 return _xfa_layer.XfaLayer; 14784 } 14785})); 14786 14787var _display_utils = __w_pdfjs_require__(1); 14788 14789var _api = __w_pdfjs_require__(6); 14790 14791var _util = __w_pdfjs_require__(2); 14792 14793var _annotation_layer = __w_pdfjs_require__(17); 14794 14795var _worker_options = __w_pdfjs_require__(12); 14796 14797var _is_node = __w_pdfjs_require__(4); 14798 14799var _text_layer = __w_pdfjs_require__(19); 14800 14801var _svg = __w_pdfjs_require__(20); 14802 14803var _xfa_layer = __w_pdfjs_require__(21); 14804 14805const pdfjsVersion = '2.10.377'; 14806const pdfjsBuild = '156762c48'; 14807{ 14808 if (_is_node.isNodeJS) { 14809 const { 14810 PDFNodeStream 14811 } = __w_pdfjs_require__(22); 14812 14813 (0, _api.setPDFNetworkStreamFactory)(params => { 14814 return new PDFNodeStream(params); 14815 }); 14816 } else { 14817 const { 14818 PDFNetworkStream 14819 } = __w_pdfjs_require__(25); 14820 14821 const { 14822 PDFFetchStream 14823 } = __w_pdfjs_require__(26); 14824 14825 (0, _api.setPDFNetworkStreamFactory)(params => { 14826 if ((0, _display_utils.isValidFetchUrl)(params.url)) { 14827 return new PDFFetchStream(params); 14828 } 14829 14830 return new PDFNetworkStream(params); 14831 }); 14832 } 14833} 14834})(); 14835 14836/******/ return __webpack_exports__; 14837/******/ })() 14838; 14839});
vendor: 32 bytes, lines 14839-14840
14839 14840//# sourceMappingURL=pdf.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.