UNPKG

508 kBJavaScriptView Raw
1window.ngxZone.runOutsideAngular(() => {
2/**
3 * @licstart The following is the entire license notice for the
4 * JavaScript code in this page
5 *
6 * Copyright 2023 Mozilla Foundation
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 *
20 * @licend The above is the entire license notice for the
21 * JavaScript code in this page
22 */
23
24(function webpackUniversalModuleDefinition(root, factory) {
25 if(typeof exports === 'object' && typeof module === 'object')
26 root["pdfjs-dist/build/pdf"] = module.exports = factory();
27 else if(typeof define === 'function' && define.amd)
28 {
29 define("pdfjs-dist/build/pdf", [], factory);
30 root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
31 }
32 else if(typeof exports === 'object')
33 root["pdfjs-dist/build/pdf"] = exports["pdfjs-dist/build/pdf"] = factory();
34 else
35 root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
36})(globalThis, () => {
37return /******/ (() => { // webpackBootstrap
38/******/ "use strict";
39/******/ var __webpack_modules__ = ([
40/* 0 */,
41/* 1 */
42/***/ ((__unused_webpack_module, exports) => {
43
44
45
46Object.defineProperty(exports, "__esModule", ({
47 value: true
48}));
49exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
50exports.assert = assert;
51exports.bytesToString = bytesToString;
52exports.createPromiseCapability = createPromiseCapability;
53exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
54exports.getModificationDate = getModificationDate;
55exports.getVerbosityLevel = getVerbosityLevel;
56exports.info = info;
57exports.isArrayBuffer = isArrayBuffer;
58exports.isArrayEqual = isArrayEqual;
59exports.objectFromMap = objectFromMap;
60exports.objectSize = objectSize;
61exports.setVerbosityLevel = setVerbosityLevel;
62exports.shadow = shadow;
63exports.string32 = string32;
64exports.stringToBytes = stringToBytes;
65exports.stringToPDFString = stringToPDFString;
66exports.stringToUTF8String = stringToUTF8String;
67exports.unreachable = unreachable;
68exports.utf8StringToString = utf8StringToString;
69exports.warn = warn;
70;
71const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
72exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
73const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
74exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
75const LINE_FACTOR = 1.35;
76exports.LINE_FACTOR = LINE_FACTOR;
77const LINE_DESCENT_FACTOR = 0.35;
78exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
79const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
80exports.BASELINE_FACTOR = BASELINE_FACTOR;
81const RenderingIntentFlag = {
82 ANY: 0x01,
83 DISPLAY: 0x02,
84 PRINT: 0x04,
85 SAVE: 0x08,
86 ANNOTATIONS_FORMS: 0x10,
87 ANNOTATIONS_STORAGE: 0x20,
88 ANNOTATIONS_DISABLE: 0x40,
89 OPLIST: 0x100
90};
91exports.RenderingIntentFlag = RenderingIntentFlag;
92const AnnotationMode = {
93 DISABLE: 0,
94 ENABLE: 1,
95 ENABLE_FORMS: 2,
96 ENABLE_STORAGE: 3
97};
98exports.AnnotationMode = AnnotationMode;
99const AnnotationEditorPrefix = "pdfjs_internal_editor_";
100exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
101const AnnotationEditorType = {
102 DISABLE: -1,
103 NONE: 0,
104 FREETEXT: 3,
105 INK: 15
106};
107exports.AnnotationEditorType = AnnotationEditorType;
108const AnnotationEditorParamsType = {
109 FREETEXT_SIZE: 1,
110 FREETEXT_COLOR: 2,
111 FREETEXT_OPACITY: 3,
112 INK_COLOR: 11,
113 INK_THICKNESS: 12,
114 INK_OPACITY: 13
115};
116exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
117const PermissionFlag = {
118 PRINT: 0x04,
119 MODIFY_CONTENTS: 0x08,
120 COPY: 0x10,
121 MODIFY_ANNOTATIONS: 0x20,
122 FILL_INTERACTIVE_FORMS: 0x100,
123 COPY_FOR_ACCESSIBILITY: 0x200,
124 ASSEMBLE: 0x400,
125 PRINT_HIGH_QUALITY: 0x800
126};
127exports.PermissionFlag = PermissionFlag;
128const TextRenderingMode = {
129 FILL: 0,
130 STROKE: 1,
131 FILL_STROKE: 2,
132 INVISIBLE: 3,
133 FILL_ADD_TO_PATH: 4,
134 STROKE_ADD_TO_PATH: 5,
135 FILL_STROKE_ADD_TO_PATH: 6,
136 ADD_TO_PATH: 7,
137 FILL_STROKE_MASK: 3,
138 ADD_TO_PATH_FLAG: 4
139};
140exports.TextRenderingMode = TextRenderingMode;
141const ImageKind = {
142 GRAYSCALE_1BPP: 1,
143 RGB_24BPP: 2,
144 RGBA_32BPP: 3
145};
146exports.ImageKind = ImageKind;
147const AnnotationType = {
148 TEXT: 1,
149 LINK: 2,
150 FREETEXT: 3,
151 LINE: 4,
152 SQUARE: 5,
153 CIRCLE: 6,
154 POLYGON: 7,
155 POLYLINE: 8,
156 HIGHLIGHT: 9,
157 UNDERLINE: 10,
158 SQUIGGLY: 11,
159 STRIKEOUT: 12,
160 STAMP: 13,
161 CARET: 14,
162 INK: 15,
163 POPUP: 16,
164 FILEATTACHMENT: 17,
165 SOUND: 18,
166 MOVIE: 19,
167 WIDGET: 20,
168 SCREEN: 21,
169 PRINTERMARK: 22,
170 TRAPNET: 23,
171 WATERMARK: 24,
172 THREED: 25,
173 REDACT: 26
174};
175exports.AnnotationType = AnnotationType;
176const AnnotationStateModelType = {
177 MARKED: "Marked",
178 REVIEW: "Review"
179};
180exports.AnnotationStateModelType = AnnotationStateModelType;
181const AnnotationMarkedState = {
182 MARKED: "Marked",
183 UNMARKED: "Unmarked"
184};
185exports.AnnotationMarkedState = AnnotationMarkedState;
186const AnnotationReviewState = {
187 ACCEPTED: "Accepted",
188 REJECTED: "Rejected",
189 CANCELLED: "Cancelled",
190 COMPLETED: "Completed",
191 NONE: "None"
192};
193exports.AnnotationReviewState = AnnotationReviewState;
194const AnnotationReplyType = {
195 GROUP: "Group",
196 REPLY: "R"
197};
198exports.AnnotationReplyType = AnnotationReplyType;
199const AnnotationFlag = {
200 INVISIBLE: 0x01,
201 HIDDEN: 0x02,
202 PRINT: 0x04,
203 NOZOOM: 0x08,
204 NOROTATE: 0x10,
205 NOVIEW: 0x20,
206 READONLY: 0x40,
207 LOCKED: 0x80,
208 TOGGLENOVIEW: 0x100,
209 LOCKEDCONTENTS: 0x200
210};
211exports.AnnotationFlag = AnnotationFlag;
212const AnnotationFieldFlag = {
213 READONLY: 0x0000001,
214 REQUIRED: 0x0000002,
215 NOEXPORT: 0x0000004,
216 MULTILINE: 0x0001000,
217 PASSWORD: 0x0002000,
218 NOTOGGLETOOFF: 0x0004000,
219 RADIO: 0x0008000,
220 PUSHBUTTON: 0x0010000,
221 COMBO: 0x0020000,
222 EDIT: 0x0040000,
223 SORT: 0x0080000,
224 FILESELECT: 0x0100000,
225 MULTISELECT: 0x0200000,
226 DONOTSPELLCHECK: 0x0400000,
227 DONOTSCROLL: 0x0800000,
228 COMB: 0x1000000,
229 RICHTEXT: 0x2000000,
230 RADIOSINUNISON: 0x2000000,
231 COMMITONSELCHANGE: 0x4000000
232};
233exports.AnnotationFieldFlag = AnnotationFieldFlag;
234const AnnotationBorderStyleType = {
235 SOLID: 1,
236 DASHED: 2,
237 BEVELED: 3,
238 INSET: 4,
239 UNDERLINE: 5
240};
241exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
242const AnnotationActionEventType = {
243 E: "Mouse Enter",
244 X: "Mouse Exit",
245 D: "Mouse Down",
246 U: "Mouse Up",
247 Fo: "Focus",
248 Bl: "Blur",
249 PO: "PageOpen",
250 PC: "PageClose",
251 PV: "PageVisible",
252 PI: "PageInvisible",
253 K: "Keystroke",
254 F: "Format",
255 V: "Validate",
256 C: "Calculate"
257};
258exports.AnnotationActionEventType = AnnotationActionEventType;
259const DocumentActionEventType = {
260 WC: "WillClose",
261 WS: "WillSave",
262 DS: "DidSave",
263 WP: "WillPrint",
264 DP: "DidPrint"
265};
266exports.DocumentActionEventType = DocumentActionEventType;
267const PageActionEventType = {
268 O: "PageOpen",
269 C: "PageClose"
270};
271exports.PageActionEventType = PageActionEventType;
272const VerbosityLevel = {
273 ERRORS: 0,
274 WARNINGS: 1,
275 INFOS: 5
276};
277exports.VerbosityLevel = VerbosityLevel;
278const CMapCompressionType = {
279 NONE: 0,
280 BINARY: 1
281};
282exports.CMapCompressionType = CMapCompressionType;
283const OPS = {
284 dependency: 1,
285 setLineWidth: 2,
286 setLineCap: 3,
287 setLineJoin: 4,
288 setMiterLimit: 5,
289 setDash: 6,
290 setRenderingIntent: 7,
291 setFlatness: 8,
292 setGState: 9,
293 save: 10,
294 restore: 11,
295 transform: 12,
296 moveTo: 13,
297 lineTo: 14,
298 curveTo: 15,
299 curveTo2: 16,
300 curveTo3: 17,
301 closePath: 18,
302 rectangle: 19,
303 stroke: 20,
304 closeStroke: 21,
305 fill: 22,
306 eoFill: 23,
307 fillStroke: 24,
308 eoFillStroke: 25,
309 closeFillStroke: 26,
310 closeEOFillStroke: 27,
311 endPath: 28,
312 clip: 29,
313 eoClip: 30,
314 beginText: 31,
315 endText: 32,
316 setCharSpacing: 33,
317 setWordSpacing: 34,
318 setHScale: 35,
319 setLeading: 36,
320 setFont: 37,
321 setTextRenderingMode: 38,
322 setTextRise: 39,
323 moveText: 40,
324 setLeadingMoveText: 41,
325 setTextMatrix: 42,
326 nextLine: 43,
327 showText: 44,
328 showSpacedText: 45,
329 nextLineShowText: 46,
330 nextLineSetSpacingShowText: 47,
331 setCharWidth: 48,
332 setCharWidthAndBounds: 49,
333 setStrokeColorSpace: 50,
334 setFillColorSpace: 51,
335 setStrokeColor: 52,
336 setStrokeColorN: 53,
337 setFillColor: 54,
338 setFillColorN: 55,
339 setStrokeGray: 56,
340 setFillGray: 57,
341 setStrokeRGBColor: 58,
342 setFillRGBColor: 59,
343 setStrokeCMYKColor: 60,
344 setFillCMYKColor: 61,
345 shadingFill: 62,
346 beginInlineImage: 63,
347 beginImageData: 64,
348 endInlineImage: 65,
349 paintXObject: 66,
350 markPoint: 67,
351 markPointProps: 68,
352 beginMarkedContent: 69,
353 beginMarkedContentProps: 70,
354 endMarkedContent: 71,
355 beginCompat: 72,
356 endCompat: 73,
357 paintFormXObjectBegin: 74,
358 paintFormXObjectEnd: 75,
359 beginGroup: 76,
360 endGroup: 77,
361 beginAnnotation: 80,
362 endAnnotation: 81,
363 paintImageMaskXObject: 83,
364 paintImageMaskXObjectGroup: 84,
365 paintImageXObject: 85,
366 paintInlineImageXObject: 86,
367 paintInlineImageXObjectGroup: 87,
368 paintImageXObjectRepeat: 88,
369 paintImageMaskXObjectRepeat: 89,
370 paintSolidColorImageMask: 90,
371 constructPath: 91
372};
373exports.OPS = OPS;
374const UNSUPPORTED_FEATURES = {
375 forms: "forms",
376 javaScript: "javaScript",
377 signatures: "signatures",
378 smask: "smask",
379 shadingPattern: "shadingPattern",
380 errorTilingPattern: "errorTilingPattern",
381 errorExtGState: "errorExtGState",
382 errorXObject: "errorXObject",
383 errorFontLoadType3: "errorFontLoadType3",
384 errorFontState: "errorFontState",
385 errorFontMissing: "errorFontMissing",
386 errorFontTranslate: "errorFontTranslate",
387 errorColorSpace: "errorColorSpace",
388 errorOperatorList: "errorOperatorList",
389 errorFontToUnicode: "errorFontToUnicode",
390 errorFontLoadNative: "errorFontLoadNative",
391 errorFontBuildPath: "errorFontBuildPath",
392 errorFontGetPath: "errorFontGetPath",
393 errorMarkedContent: "errorMarkedContent",
394 errorContentSubStream: "errorContentSubStream"
395};
396exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
397const PasswordResponses = {
398 NEED_PASSWORD: 1,
399 INCORRECT_PASSWORD: 2
400};
401exports.PasswordResponses = PasswordResponses;
402let verbosity = VerbosityLevel.WARNINGS;
403function setVerbosityLevel(level) {
404 if (Number.isInteger(level)) {
405 verbosity = level;
406 }
407}
408function getVerbosityLevel() {
409 return verbosity;
410}
411function info(msg) {
412 if (verbosity >= VerbosityLevel.INFOS) {
413 if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) {
414 console.log(`Info: ${msg}`);
415 } else if (Window && Window['ngxConsole']) {
416 Window['ngxConsole'].log(`Info: ${msg}`);
417 } else {
418 console.log(`Info: ${msg}`);
419 }
420 }
421}
422function warn(msg) {
423 if (verbosity >= VerbosityLevel.WARNINGS) {
424 if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) {
425 console.log(`Warning: ${msg}`);
426 } else if (Window && Window["ngxConsole"]) {
427 Window["ngxConsole"].log(`Warning: ${msg}`);
428 } else {
429 console.log(`Warning: ${msg}`);
430 }
431 }
432}
433function unreachable(msg) {
434 throw new Error(msg);
435}
436function assert(cond, msg) {
437 if (!cond) {
438 unreachable(msg);
439 }
440}
441function _isValidProtocol(url) {
442 if (!url) {
443 return false;
444 }
445 switch (url.protocol) {
446 case "http:":
447 case "https:":
448 case "ftp:":
449 case "mailto:":
450 case "tel:":
451 case "capacitor":
452 return true;
453 default:
454 return false;
455 }
456}
457function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
458 if (!url) {
459 return null;
460 }
461 try {
462 if (options && typeof url === "string") {
463 if (options.addDefaultProtocol && url.startsWith("www.")) {
464 const dots = url.match(/\./g);
465 if (dots && dots.length >= 2) {
466 url = `http://${url}`;
467 }
468 }
469 if (options.tryConvertEncoding) {
470 try {
471 url = stringToUTF8String(url);
472 } catch (ex) {}
473 }
474 }
475 const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
476 if (_isValidProtocol(absoluteUrl)) {
477 return absoluteUrl;
478 }
479 } catch (ex) {}
480 return null;
481}
482function shadow(obj, prop, value, nonSerializable = false) {
483 Object.defineProperty(obj, prop, {
484 value,
485 enumerable: !nonSerializable,
486 configurable: true,
487 writable: false
488 });
489 return value;
490}
491const BaseException = function BaseExceptionClosure() {
492 function BaseException(message, name) {
493 if (this.constructor === BaseException) {
494 unreachable("Cannot initialize BaseException.");
495 }
496 this.message = message;
497 this.name = name;
498 }
499 BaseException.prototype = new Error();
500 BaseException.constructor = BaseException;
501 return BaseException;
502}();
503exports.BaseException = BaseException;
504class PasswordException extends BaseException {
505 constructor(msg, code) {
506 super(msg, "PasswordException");
507 this.code = code;
508 }
509}
510exports.PasswordException = PasswordException;
511class UnknownErrorException extends BaseException {
512 constructor(msg, details) {
513 super(msg, "UnknownErrorException");
514 this.details = details;
515 }
516}
517exports.UnknownErrorException = UnknownErrorException;
518class InvalidPDFException extends BaseException {
519 constructor(msg) {
520 super(msg, "InvalidPDFException");
521 }
522}
523exports.InvalidPDFException = InvalidPDFException;
524class MissingPDFException extends BaseException {
525 constructor(msg) {
526 super(msg, "MissingPDFException");
527 }
528}
529exports.MissingPDFException = MissingPDFException;
530class UnexpectedResponseException extends BaseException {
531 constructor(msg, status) {
532 super(msg, "UnexpectedResponseException");
533 this.status = status;
534 }
535}
536exports.UnexpectedResponseException = UnexpectedResponseException;
537class FormatError extends BaseException {
538 constructor(msg) {
539 super(msg, "FormatError");
540 }
541}
542exports.FormatError = FormatError;
543class AbortException extends BaseException {
544 constructor(msg) {
545 super(msg, "AbortException");
546 }
547}
548exports.AbortException = AbortException;
549function bytesToString(bytes) {
550 if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
551 unreachable("Invalid argument for bytesToString");
552 }
553 const length = bytes.length;
554 const MAX_ARGUMENT_COUNT = 8192;
555 if (length < MAX_ARGUMENT_COUNT) {
556 return String.fromCharCode.apply(null, bytes);
557 }
558 const strBuf = [];
559 for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
560 const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
561 const chunk = bytes.subarray(i, chunkEnd);
562 strBuf.push(String.fromCharCode.apply(null, chunk));
563 }
564 return strBuf.join("");
565}
566function stringToBytes(str) {
567 if (typeof str !== "string") {
568 unreachable("Invalid argument for stringToBytes");
569 }
570 const length = str.length;
571 const bytes = new Uint8Array(length);
572 for (let i = 0; i < length; ++i) {
573 bytes[i] = str.charCodeAt(i) & 0xff;
574 }
575 return bytes;
576}
577function string32(value) {
578 return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
579}
580function objectSize(obj) {
581 return Object.keys(obj).length;
582}
583function objectFromMap(map) {
584 const obj = Object.create(null);
585 for (const [key, value] of map) {
586 obj[key] = value;
587 }
588 return obj;
589}
590function isLittleEndian() {
591 const buffer8 = new Uint8Array(4);
592 buffer8[0] = 1;
593 const view32 = new Uint32Array(buffer8.buffer, 0, 1);
594 return view32[0] === 1;
595}
596function isEvalSupported() {
597 try {
598 new Function("");
599 return true;
600 } catch (e) {
601 return false;
602 }
603}
604class FeatureTest {
605 static get isLittleEndian() {
606 return shadow(this, "isLittleEndian", isLittleEndian());
607 }
608 static get isEvalSupported() {
609 return shadow(this, "isEvalSupported", isEvalSupported());
610 }
611 static get isOffscreenCanvasSupported() {
612 return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
613 }
614 static get platform() {
615 if (typeof navigator === "undefined") {
616 return shadow(this, "platform", {
617 isWin: false,
618 isMac: false
619 });
620 }
621 return shadow(this, "platform", {
622 isWin: navigator.platform.includes("Win"),
623 isMac: navigator.platform.includes("Mac")
624 });
625 }
626}
627exports.FeatureTest = FeatureTest;
628const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
629class Util {
630 static makeHexColor(r, g, b) {
631 return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
632 }
633 static scaleMinMax(transform, minMax) {
634 let temp;
635 if (transform[0]) {
636 if (transform[0] < 0) {
637 temp = minMax[0];
638 minMax[0] = minMax[1];
639 minMax[1] = temp;
640 }
641 minMax[0] *= transform[0];
642 minMax[1] *= transform[0];
643 if (transform[3] < 0) {
644 temp = minMax[2];
645 minMax[2] = minMax[3];
646 minMax[3] = temp;
647 }
648 minMax[2] *= transform[3];
649 minMax[3] *= transform[3];
650 } else {
651 temp = minMax[0];
652 minMax[0] = minMax[2];
653 minMax[2] = temp;
654 temp = minMax[1];
655 minMax[1] = minMax[3];
656 minMax[3] = temp;
657 if (transform[1] < 0) {
658 temp = minMax[2];
659 minMax[2] = minMax[3];
660 minMax[3] = temp;
661 }
662 minMax[2] *= transform[1];
663 minMax[3] *= transform[1];
664 if (transform[2] < 0) {
665 temp = minMax[0];
666 minMax[0] = minMax[1];
667 minMax[1] = temp;
668 }
669 minMax[0] *= transform[2];
670 minMax[1] *= transform[2];
671 }
672 minMax[0] += transform[4];
673 minMax[1] += transform[4];
674 minMax[2] += transform[5];
675 minMax[3] += transform[5];
676 }
677 static transform(m1, m2) {
678 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]];
679 }
680 static applyTransform(p, m) {
681 const xt = p[0] * m[0] + p[1] * m[2] + m[4];
682 const yt = p[0] * m[1] + p[1] * m[3] + m[5];
683 return [xt, yt];
684 }
685 static applyInverseTransform(p, m) {
686 const d = m[0] * m[3] - m[1] * m[2];
687 const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
688 const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
689 return [xt, yt];
690 }
691 static getAxialAlignedBoundingBox(r, m) {
692 const p1 = Util.applyTransform(r, m);
693 const p2 = Util.applyTransform(r.slice(2, 4), m);
694 const p3 = Util.applyTransform([r[0], r[3]], m);
695 const p4 = Util.applyTransform([r[2], r[1]], m);
696 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])];
697 }
698 static inverseTransform(m) {
699 const d = m[0] * m[3] - m[1] * m[2];
700 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];
701 }
702 static singularValueDecompose2dScale(m) {
703 const transpose = [m[0], m[2], m[1], m[3]];
704 const a = m[0] * transpose[0] + m[1] * transpose[2];
705 const b = m[0] * transpose[1] + m[1] * transpose[3];
706 const c = m[2] * transpose[0] + m[3] * transpose[2];
707 const d = m[2] * transpose[1] + m[3] * transpose[3];
708 const first = (a + d) / 2;
709 const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
710 const sx = first + second || 1;
711 const sy = first - second || 1;
712 return [Math.sqrt(sx), Math.sqrt(sy)];
713 }
714 static normalizeRect(rect) {
715 const r = rect.slice(0);
716 if (rect[0] > rect[2]) {
717 r[0] = rect[2];
718 r[2] = rect[0];
719 }
720 if (rect[1] > rect[3]) {
721 r[1] = rect[3];
722 r[3] = rect[1];
723 }
724 return r;
725 }
726 static intersect(rect1, rect2) {
727 const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
728 const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
729 if (xLow > xHigh) {
730 return null;
731 }
732 const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
733 const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
734 if (yLow > yHigh) {
735 return null;
736 }
737 return [xLow, yLow, xHigh, yHigh];
738 }
739 static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
740 const tvalues = [],
741 bounds = [[], []];
742 let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
743 for (let i = 0; i < 2; ++i) {
744 if (i === 0) {
745 b = 6 * x0 - 12 * x1 + 6 * x2;
746 a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
747 c = 3 * x1 - 3 * x0;
748 } else {
749 b = 6 * y0 - 12 * y1 + 6 * y2;
750 a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
751 c = 3 * y1 - 3 * y0;
752 }
753 if (Math.abs(a) < 1e-12) {
754 if (Math.abs(b) < 1e-12) {
755 continue;
756 }
757 t = -c / b;
758 if (0 < t && t < 1) {
759 tvalues.push(t);
760 }
761 continue;
762 }
763 b2ac = b * b - 4 * c * a;
764 sqrtb2ac = Math.sqrt(b2ac);
765 if (b2ac < 0) {
766 continue;
767 }
768 t1 = (-b + sqrtb2ac) / (2 * a);
769 if (0 < t1 && t1 < 1) {
770 tvalues.push(t1);
771 }
772 t2 = (-b - sqrtb2ac) / (2 * a);
773 if (0 < t2 && t2 < 1) {
774 tvalues.push(t2);
775 }
776 }
777 let j = tvalues.length,
778 mt;
779 const jlen = j;
780 while (j--) {
781 t = tvalues[j];
782 mt = 1 - t;
783 bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
784 bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
785 }
786 bounds[0][jlen] = x0;
787 bounds[1][jlen] = y0;
788 bounds[0][jlen + 1] = x3;
789 bounds[1][jlen + 1] = y3;
790 bounds[0].length = bounds[1].length = jlen + 2;
791 return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
792 }
793}
794exports.Util = Util;
795const 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];
796function stringToPDFString(str) {
797 if (str[0] >= "\xEF") {
798 let encoding;
799 if (str[0] === "\xFE" && str[1] === "\xFF") {
800 encoding = "utf-16be";
801 } else if (str[0] === "\xFF" && str[1] === "\xFE") {
802 encoding = "utf-16le";
803 } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
804 encoding = "utf-8";
805 }
806 if (encoding) {
807 try {
808 const decoder = new TextDecoder(encoding, {
809 fatal: true
810 });
811 const buffer = stringToBytes(str);
812 return decoder.decode(buffer);
813 } catch (ex) {
814 warn(`stringToPDFString: "${ex}".`);
815 }
816 }
817 }
818 const strBuf = [];
819 for (let i = 0, ii = str.length; i < ii; i++) {
820 const code = PDFStringTranslateTable[str.charCodeAt(i)];
821 strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
822 }
823 return strBuf.join("");
824}
825function stringToUTF8String(str) {
826 return decodeURIComponent(escape(str));
827}
828function utf8StringToString(str) {
829 return unescape(encodeURIComponent(str));
830}
831function isArrayBuffer(v) {
832 return typeof v === "object" && v !== null && v.byteLength !== undefined;
833}
834function isArrayEqual(arr1, arr2) {
835 if (arr1.length !== arr2.length) {
836 return false;
837 }
838 for (let i = 0, ii = arr1.length; i < ii; i++) {
839 if (arr1[i] !== arr2[i]) {
840 return false;
841 }
842 }
843 return true;
844}
845function getModificationDate(date = new Date()) {
846 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")];
847 return buffer.join("");
848}
849function createPromiseCapability() {
850 const capability = Object.create(null);
851 let isSettled = false;
852 Object.defineProperty(capability, "settled", {
853 get() {
854 return isSettled;
855 }
856 });
857 capability.promise = new Promise(function (resolve, reject) {
858 capability.resolve = function (data) {
859 isSettled = true;
860 resolve(data);
861 };
862 capability.reject = function (reason) {
863 isSettled = true;
864 reject(reason);
865 };
866 });
867 return capability;
868}
869
870/***/ }),
871/* 2 */
872/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
873
874
875
876Object.defineProperty(exports, "__esModule", ({
877 value: true
878}));
879exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
880exports.getDocument = getDocument;
881exports.version = void 0;
882var _util = __w_pdfjs_require__(1);
883var _annotation_storage = __w_pdfjs_require__(3);
884var _display_utils = __w_pdfjs_require__(6);
885var _font_loader = __w_pdfjs_require__(9);
886var _canvas = __w_pdfjs_require__(11);
887var _worker_options = __w_pdfjs_require__(14);
888var _is_node = __w_pdfjs_require__(10);
889var _message_handler = __w_pdfjs_require__(15);
890var _metadata = __w_pdfjs_require__(16);
891var _optional_content_config = __w_pdfjs_require__(17);
892var _transport_stream = __w_pdfjs_require__(18);
893var _xfa_text = __w_pdfjs_require__(19);
894const DEFAULT_RANGE_CHUNK_SIZE = 65536;
895const RENDERING_CANCELLED_TIMEOUT = 100;
896const ServiceWorkerOptions = {
897 showUnverifiedSignatures: false
898};
899window.ServiceWorkerOptions = ServiceWorkerOptions;
900let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
901exports.DefaultCanvasFactory = DefaultCanvasFactory;
902let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
903exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
904let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
905exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
906if (_is_node.isNodeJS) {
907 const {
908 NodeCanvasFactory,
909 NodeCMapReaderFactory,
910 NodeStandardFontDataFactory
911 } = __w_pdfjs_require__(20);
912 exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
913 exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
914 exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
915}
916let createPDFNetworkStream;
917{
918 if (_is_node.isNodeJS) {
919 const {
920 PDFNodeStream
921 } = __w_pdfjs_require__(21);
922 createPDFNetworkStream = params => {
923 return new PDFNodeStream(params);
924 };
925 } else {
926 const {
927 PDFNetworkStream
928 } = __w_pdfjs_require__(24);
929 const {
930 PDFFetchStream
931 } = __w_pdfjs_require__(25);
932 createPDFNetworkStream = params => {
933 return (0, _display_utils.isValidFetchUrl)(params.url) ? new PDFFetchStream(params) : new PDFNetworkStream(params);
934 };
935 }
936}
937function getDocument(src) {
938 if (typeof src === "string" || src instanceof URL) {
939 src = {
940 url: src
941 };
942 } else if ((0, _util.isArrayBuffer)(src)) {
943 src = {
944 data: src
945 };
946 } else if (src instanceof PDFDataRangeTransport) {
947 (0, _display_utils.deprecated)("`PDFDataRangeTransport`-instance, " + "please use a parameter object with `range`-property instead.");
948 src = {
949 range: src
950 };
951 } else {
952 if (typeof src !== "object") {
953 throw new Error("Invalid parameter in getDocument, " + "need either string, URL, TypedArray, or parameter object.");
954 }
955 }
956 if (!src.url && !src.data && !src.range) {
957 throw new Error("Invalid parameter object: need either .data, .range or .url");
958 }
959 const task = new PDFDocumentLoadingTask();
960 const url = src.url ? getUrlProp(src.url, src.baseHref) : null;
961 const data = src.data ? getDataProp(src.data) : null;
962 const httpHeaders = src.httpHeaders || null;
963 const withCredentials = src.withCredentials === true;
964 const password = src.password ?? null;
965 const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
966 const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
967 let worker = src.worker instanceof PDFWorker ? src.worker : null;
968 const verbosity = src.verbosity;
969 const docBaseUrl = typeof src.docBaseUrl === "string" && !(0, _display_utils.isDataScheme)(src.docBaseUrl) ? src.docBaseUrl : null;
970 const cMapUrl = typeof src.cMapUrl === "function" ? src.cMapUrl() : typeof src.cMapUrl === "string" ? src.cMapUrl : null;
971 const cMapPacked = src.cMapPacked !== false;
972 const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
973 const standardFontDataUrl = typeof src.standardFontDataUrl === "function" ? src.standardFontDataUrl() : typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
974 const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
975 const ignoreErrors = src.stopAtErrors !== true;
976 const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
977 const isEvalSupported = src.isEvalSupported !== false;
978 const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !_is_node.isNodeJS;
979 const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : _is_node.isNodeJS;
980 const fontExtraProperties = src.fontExtraProperties === true;
981 const enableXfa = src.enableXfa === true;
982 const ownerDocument = src.ownerDocument || globalThis.document;
983 const disableRange = src.disableRange === true;
984 const disableStream = src.disableStream === true;
985 const disableAutoFetch = src.disableAutoFetch === true;
986 const pdfBug = src.pdfBug === true;
987 const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
988 const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !_is_node.isNodeJS && !disableFontFace;
989 const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === _display_utils.DOMCMapReaderFactory && StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory && (0, _display_utils.isValidFetchUrl)(cMapUrl, document.baseURI) && (0, _display_utils.isValidFetchUrl)(standardFontDataUrl, document.baseURI);
990 const styleElement = null;
991 (0, _util.setVerbosityLevel)(verbosity);
992 const transportFactory = useWorkerFetch ? null : {
993 cMapReaderFactory: new CMapReaderFactory({
994 baseUrl: cMapUrl,
995 isCompressed: cMapPacked
996 }),
997 standardFontDataFactory: new StandardFontDataFactory({
998 baseUrl: standardFontDataUrl
999 })
1000 };
1001 if (!worker) {
1002 const workerParams = {
1003 verbosity,
1004 port: _worker_options.GlobalWorkerOptions.workerPort
1005 };
1006 worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
1007 task._worker = worker;
1008 }
1009 const docId = task.docId;
1010 const fetchDocParams = {
1011 docId,
1012 apiVersion: '3.4.493',
1013 data,
1014 password,
1015 disableAutoFetch,
1016 rangeChunkSize,
1017 length,
1018 docBaseUrl,
1019 enableXfa,
1020 evaluatorOptions: {
1021 maxImageSize,
1022 disableFontFace,
1023 ignoreErrors,
1024 isEvalSupported,
1025 isOffscreenCanvasSupported,
1026 fontExtraProperties,
1027 useSystemFonts,
1028 cMapUrl: useWorkerFetch ? cMapUrl : null,
1029 standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
1030 }
1031 };
1032 const transportParams = {
1033 ignoreErrors,
1034 isEvalSupported,
1035 disableFontFace,
1036 fontExtraProperties,
1037 enableXfa,
1038 ownerDocument,
1039 disableAutoFetch,
1040 pdfBug,
1041 styleElement
1042 };
1043 worker.promise.then(function () {
1044 if (task.destroyed) {
1045 throw new Error("Loading aborted");
1046 }
1047 const workerIdPromise = _fetchDocument(worker, fetchDocParams);
1048 const networkStreamPromise = new Promise(function (resolve) {
1049 let networkStream;
1050 if (rangeTransport) {
1051 networkStream = new _transport_stream.PDFDataTransportStream({
1052 length,
1053 initialData: rangeTransport.initialData,
1054 progressiveDone: rangeTransport.progressiveDone,
1055 contentDispositionFilename: rangeTransport.contentDispositionFilename,
1056 disableRange,
1057 disableStream
1058 }, rangeTransport);
1059 } else if (!data) {
1060 networkStream = createPDFNetworkStream({
1061 url,
1062 length,
1063 httpHeaders,
1064 withCredentials,
1065 rangeChunkSize,
1066 disableRange,
1067 disableStream
1068 });
1069 }
1070 resolve(networkStream);
1071 });
1072 return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
1073 if (task.destroyed) {
1074 throw new Error("Loading aborted");
1075 }
1076 const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
1077 const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
1078 task._transport = transport;
1079 messageHandler.send("showUnverifiedSignatures", window.ServiceWorkerOptions.showUnverifiedSignatures);
1080 messageHandler.send("Ready", null);
1081 });
1082 }).catch(task._capability.reject);
1083 return task;
1084}
1085async function _fetchDocument(worker, source) {
1086 if (worker.destroyed) {
1087 throw new Error("Worker was destroyed");
1088 }
1089 const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", source, source.data ? [source.data.buffer] : null);
1090 if (worker.destroyed) {
1091 throw new Error("Worker was destroyed");
1092 }
1093 return workerId;
1094}
1095function getUrlProp(val, baseHref) {
1096 if (val instanceof URL) {
1097 return val.href;
1098 }
1099 try {
1100 if (baseHref) {
1101 return new URL(val, window.location.origin + baseHref).href;
1102 } else {
1103 return new URL(val, window.location).href;
1104 }
1105 } catch (ex) {
1106 if (_is_node.isNodeJS && typeof val === "string") {
1107 return val;
1108 }
1109 }
1110 throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
1111}
1112function getDataProp(val) {
1113 if (_is_node.isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
1114 (0, _display_utils.deprecated)("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
1115 return new Uint8Array(val);
1116 }
1117 if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
1118 return val;
1119 }
1120 if (typeof val === "string") {
1121 return (0, _util.stringToBytes)(val);
1122 }
1123 if (typeof val === "object" && !isNaN(val?.length) || (0, _util.isArrayBuffer)(val)) {
1124 return new Uint8Array(val);
1125 }
1126 throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
1127}
1128class PDFDocumentLoadingTask {
1129 static #docId = 0;
1130 #onUnsupportedFeature = null;
1131 constructor() {
1132 this._capability = (0, _util.createPromiseCapability)();
1133 this._transport = null;
1134 this._worker = null;
1135 this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
1136 this.destroyed = false;
1137 this.onPassword = null;
1138 this.onProgress = null;
1139 }
1140 get onUnsupportedFeature() {
1141 return this.#onUnsupportedFeature;
1142 }
1143 set onUnsupportedFeature(callback) {
1144 (0, _display_utils.deprecated)("The PDFDocumentLoadingTask onUnsupportedFeature property will be removed in the future.");
1145 this.#onUnsupportedFeature = callback;
1146 }
1147 get promise() {
1148 return this._capability.promise;
1149 }
1150 async destroy() {
1151 this.destroyed = true;
1152 await this._transport?.destroy();
1153 this._transport = null;
1154 if (this._worker) {
1155 this._worker.destroy();
1156 this._worker = null;
1157 }
1158 }
1159}
1160exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
1161class PDFDataRangeTransport {
1162 constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
1163 this.length = length;
1164 this.initialData = initialData;
1165 this.progressiveDone = progressiveDone;
1166 this.contentDispositionFilename = contentDispositionFilename;
1167 this._rangeListeners = [];
1168 this._progressListeners = [];
1169 this._progressiveReadListeners = [];
1170 this._progressiveDoneListeners = [];
1171 this._readyCapability = (0, _util.createPromiseCapability)();
1172 }
1173 addRangeListener(listener) {
1174 this._rangeListeners.push(listener);
1175 }
1176 addProgressListener(listener) {
1177 this._progressListeners.push(listener);
1178 }
1179 addProgressiveReadListener(listener) {
1180 this._progressiveReadListeners.push(listener);
1181 }
1182 addProgressiveDoneListener(listener) {
1183 this._progressiveDoneListeners.push(listener);
1184 }
1185 onDataRange(begin, chunk) {
1186 for (const listener of this._rangeListeners) {
1187 listener(begin, chunk);
1188 }
1189 }
1190 onDataProgress(loaded, total) {
1191 this._readyCapability.promise.then(() => {
1192 for (const listener of this._progressListeners) {
1193 listener(loaded, total);
1194 }
1195 });
1196 }
1197 onDataProgressiveRead(chunk) {
1198 this._readyCapability.promise.then(() => {
1199 for (const listener of this._progressiveReadListeners) {
1200 listener(chunk);
1201 }
1202 });
1203 }
1204 onDataProgressiveDone() {
1205 this._readyCapability.promise.then(() => {
1206 for (const listener of this._progressiveDoneListeners) {
1207 listener();
1208 }
1209 });
1210 }
1211 transportReady() {
1212 this._readyCapability.resolve();
1213 }
1214 requestDataRange(begin, end) {
1215 (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
1216 }
1217 abort() {}
1218}
1219exports.PDFDataRangeTransport = PDFDataRangeTransport;
1220class PDFDocumentProxy {
1221 constructor(pdfInfo, transport) {
1222 this._pdfInfo = pdfInfo;
1223 this._transport = transport;
1224 }
1225 get annotationStorage() {
1226 return this._transport.annotationStorage;
1227 }
1228 get numPages() {
1229 return this._pdfInfo.numPages;
1230 }
1231 get fingerprints() {
1232 return this._pdfInfo.fingerprints;
1233 }
1234 get isPureXfa() {
1235 return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
1236 }
1237 get allXfaHtml() {
1238 return this._transport._htmlForXfa;
1239 }
1240 getPage(pageNumber) {
1241 return this._transport.getPage(pageNumber);
1242 }
1243 getPageIndex(ref) {
1244 return this._transport.getPageIndex(ref);
1245 }
1246 getDestinations() {
1247 return this._transport.getDestinations();
1248 }
1249 getDestination(id) {
1250 return this._transport.getDestination(id);
1251 }
1252 getPageLabels() {
1253 return this._transport.getPageLabels();
1254 }
1255 getPageLayout() {
1256 return this._transport.getPageLayout();
1257 }
1258 getPageMode() {
1259 return this._transport.getPageMode();
1260 }
1261 getViewerPreferences() {
1262 return this._transport.getViewerPreferences();
1263 }
1264 getOpenAction() {
1265 return this._transport.getOpenAction();
1266 }
1267 getAttachments() {
1268 return this._transport.getAttachments();
1269 }
1270 getJavaScript() {
1271 return this._transport.getJavaScript();
1272 }
1273 getJSActions() {
1274 return this._transport.getDocJSActions();
1275 }
1276 getOutline() {
1277 return this._transport.getOutline();
1278 }
1279 getOptionalContentConfig() {
1280 return this._transport.getOptionalContentConfig();
1281 }
1282 getPermissions() {
1283 return this._transport.getPermissions();
1284 }
1285 getMetadata() {
1286 return this._transport.getMetadata();
1287 }
1288 getMarkInfo() {
1289 return this._transport.getMarkInfo();
1290 }
1291 getData() {
1292 return this._transport.getData();
1293 }
1294 saveDocument() {
1295 return this._transport.saveDocument();
1296 }
1297 getDownloadInfo() {
1298 return this._transport.downloadInfoCapability.promise;
1299 }
1300 cleanup(keepLoadedFonts = false) {
1301 return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
1302 }
1303 destroy() {
1304 return this.loadingTask.destroy();
1305 }
1306 get loadingParams() {
1307 return this._transport.loadingParams;
1308 }
1309 get loadingTask() {
1310 return this._transport.loadingTask;
1311 }
1312 getFieldObjects() {
1313 return this._transport.getFieldObjects();
1314 }
1315 hasJSActions() {
1316 return this._transport.hasJSActions();
1317 }
1318 getCalculationOrderIds() {
1319 return this._transport.getCalculationOrderIds();
1320 }
1321}
1322exports.PDFDocumentProxy = PDFDocumentProxy;
1323class PDFPageProxy {
1324 constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
1325 this._pageIndex = pageIndex;
1326 this._pageInfo = pageInfo;
1327 this._ownerDocument = ownerDocument;
1328 this._transport = transport;
1329 this._stats = pdfBug ? new _display_utils.StatTimer() : null;
1330 this._pdfBug = pdfBug;
1331 this.commonObjs = transport.commonObjs;
1332 this.objs = new PDFObjects();
1333 this.cleanupAfterRender = false;
1334 this.pendingCleanup = false;
1335 this._intentStates = new Map();
1336 this.destroyed = false;
1337 }
1338 get pageNumber() {
1339 return this._pageIndex + 1;
1340 }
1341 get rotate() {
1342 return this._pageInfo.rotate;
1343 }
1344 get ref() {
1345 return this._pageInfo.ref;
1346 }
1347 get userUnit() {
1348 return this._pageInfo.userUnit;
1349 }
1350 get view() {
1351 return this._pageInfo.view;
1352 }
1353 getViewport({
1354 scale,
1355 rotation = this.rotate,
1356 offsetX = 0,
1357 offsetY = 0,
1358 dontFlip = false
1359 } = {}) {
1360 return new _display_utils.PageViewport({
1361 viewBox: this.view,
1362 scale,
1363 rotation,
1364 offsetX,
1365 offsetY,
1366 dontFlip
1367 });
1368 }
1369 getAnnotations({
1370 intent = "display"
1371 } = {}) {
1372 const intentArgs = this._transport.getRenderingIntent(intent);
1373 return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
1374 }
1375 getJSActions() {
1376 return this._transport.getPageJSActions(this._pageIndex);
1377 }
1378 get isPureXfa() {
1379 return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
1380 }
1381 async getXfa() {
1382 return this._transport._htmlForXfa?.children[this._pageIndex] || null;
1383 }
1384 render({
1385 canvasContext,
1386 viewport,
1387 intent = "display",
1388 annotationMode = _util.AnnotationMode.ENABLE,
1389 transform = null,
1390 canvasFactory = null,
1391 background = null,
1392 backgroundColorToReplace = null,
1393 optionalContentConfigPromise = null,
1394 annotationCanvasMap = null,
1395 pageColors = null,
1396 printAnnotationStorage = null
1397 }) {
1398 this._stats?.time("Overall");
1399 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
1400 this.pendingCleanup = false;
1401 if (!optionalContentConfigPromise) {
1402 optionalContentConfigPromise = this._transport.getOptionalContentConfig();
1403 }
1404 let intentState = this._intentStates.get(intentArgs.cacheKey);
1405 if (!intentState) {
1406 intentState = Object.create(null);
1407 this._intentStates.set(intentArgs.cacheKey, intentState);
1408 }
1409 if (intentState.streamReaderCancelTimeout) {
1410 clearTimeout(intentState.streamReaderCancelTimeout);
1411 intentState.streamReaderCancelTimeout = null;
1412 }
1413 const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
1414 ownerDocument: this._ownerDocument
1415 });
1416 const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
1417 if (!intentState.displayReadyCapability) {
1418 intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
1419 intentState.operatorList = {
1420 fnArray: [],
1421 argsArray: [],
1422 lastChunk: false,
1423 separateAnnots: null
1424 };
1425 this._stats?.time("Page Request");
1426 this._pumpOperatorList(intentArgs);
1427 }
1428 const complete = error => {
1429 intentState.renderTasks.delete(internalRenderTask);
1430 if (this.cleanupAfterRender || intentPrint) {
1431 this.pendingCleanup = true;
1432 }
1433 this._tryCleanup();
1434 if (error) {
1435 internalRenderTask.capability.reject(error);
1436 this._abortOperatorList({
1437 intentState,
1438 reason: error instanceof Error ? error : new Error(error)
1439 });
1440 } else {
1441 internalRenderTask.capability.resolve();
1442 }
1443 this._stats?.timeEnd("Rendering");
1444 this._stats?.timeEnd("Overall");
1445 };
1446 const internalRenderTask = new InternalRenderTask({
1447 callback: complete,
1448 params: {
1449 canvasContext,
1450 viewport,
1451 transform,
1452 background,
1453 backgroundColorToReplace
1454 },
1455 objs: this.objs,
1456 commonObjs: this.commonObjs,
1457 annotationCanvasMap,
1458 operatorList: intentState.operatorList,
1459 pageIndex: this._pageIndex,
1460 canvasFactory: canvasFactoryInstance,
1461 useRequestAnimationFrame: !intentPrint,
1462 pdfBug: this._pdfBug,
1463 pageColors
1464 });
1465 (intentState.renderTasks ||= new Set()).add(internalRenderTask);
1466 const renderTask = internalRenderTask.task;
1467 Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
1468 if (this.pendingCleanup) {
1469 complete();
1470 return;
1471 }
1472 this._stats?.time("Rendering");
1473 internalRenderTask.initializeGraphics({
1474 transparency,
1475 optionalContentConfig
1476 });
1477 internalRenderTask.operatorListChanged();
1478 }).catch(complete);
1479 return renderTask;
1480 }
1481 getOperatorList({
1482 intent = "display",
1483 annotationMode = _util.AnnotationMode.ENABLE,
1484 printAnnotationStorage = null
1485 } = {}) {
1486 function operatorListChanged() {
1487 if (intentState.operatorList.lastChunk) {
1488 intentState.opListReadCapability.resolve(intentState.operatorList);
1489 intentState.renderTasks.delete(opListTask);
1490 }
1491 }
1492 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
1493 let intentState = this._intentStates.get(intentArgs.cacheKey);
1494 if (!intentState) {
1495 intentState = Object.create(null);
1496 this._intentStates.set(intentArgs.cacheKey, intentState);
1497 }
1498 let opListTask;
1499 if (!intentState.opListReadCapability) {
1500 opListTask = Object.create(null);
1501 opListTask.operatorListChanged = operatorListChanged;
1502 intentState.opListReadCapability = (0, _util.createPromiseCapability)();
1503 (intentState.renderTasks ||= new Set()).add(opListTask);
1504 intentState.operatorList = {
1505 fnArray: [],
1506 argsArray: [],
1507 lastChunk: false,
1508 separateAnnots: null
1509 };
1510 this._stats?.time("Page Request");
1511 this._pumpOperatorList(intentArgs);
1512 }
1513 return intentState.opListReadCapability.promise;
1514 }
1515 streamTextContent({
1516 disableCombineTextItems = false,
1517 includeMarkedContent = false
1518 } = {}) {
1519 const TEXT_CONTENT_CHUNK_SIZE = 100;
1520 return this._transport.messageHandler.sendWithStream("GetTextContent", {
1521 pageIndex: this._pageIndex,
1522 combineTextItems: disableCombineTextItems !== true,
1523 includeMarkedContent: includeMarkedContent === true
1524 }, {
1525 highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
1526 size(textContent) {
1527 return textContent.items.length;
1528 }
1529 });
1530 }
1531 getTextContent(params = {}) {
1532 if (this._transport._htmlForXfa) {
1533 return this.getXfa().then(xfa => {
1534 return _xfa_text.XfaText.textContent(xfa);
1535 });
1536 }
1537 const readableStream = this.streamTextContent(params);
1538 return new Promise(function (resolve, reject) {
1539 function pump() {
1540 reader.read().then(function ({
1541 value,
1542 done
1543 }) {
1544 if (done) {
1545 resolve(textContent);
1546 return;
1547 }
1548 Object.assign(textContent.styles, value.styles);
1549 textContent.items.push(...value.items);
1550 pump();
1551 }, reject);
1552 }
1553 const reader = readableStream.getReader();
1554 const textContent = {
1555 items: [],
1556 styles: Object.create(null)
1557 };
1558 pump();
1559 });
1560 }
1561 getStructTree() {
1562 return this._transport.getStructTree(this._pageIndex);
1563 }
1564 _destroy() {
1565 this.destroyed = true;
1566 const waitOn = [];
1567 for (const intentState of this._intentStates.values()) {
1568 this._abortOperatorList({
1569 intentState,
1570 reason: new Error("Page was destroyed."),
1571 force: true
1572 });
1573 if (intentState.opListReadCapability) {
1574 continue;
1575 }
1576 for (const internalRenderTask of intentState.renderTasks) {
1577 waitOn.push(internalRenderTask.completed);
1578 internalRenderTask.cancel();
1579 }
1580 }
1581 this.objs.clear();
1582 this.pendingCleanup = false;
1583 return Promise.all(waitOn);
1584 }
1585 cleanup(resetStats = false) {
1586 this.pendingCleanup = true;
1587 if (!this._tryCleanup(resetStats)) {
1588 this.cleanupAfterRender = true;
1589 }
1590 return true;
1591 }
1592 _tryCleanup(resetStats = false) {
1593 if (!this.pendingCleanup) {
1594 return false;
1595 }
1596 for (const {
1597 renderTasks,
1598 operatorList
1599 } of this._intentStates.values()) {
1600 if (renderTasks.size > 0 || !operatorList.lastChunk) {
1601 return false;
1602 }
1603 }
1604 this._intentStates.clear();
1605 this.objs.clear();
1606 if (resetStats && this._stats) {
1607 this._stats = new _display_utils.StatTimer();
1608 }
1609 this.pendingCleanup = false;
1610 return true;
1611 }
1612 _startRenderPage(transparency, cacheKey) {
1613 const intentState = this._intentStates.get(cacheKey);
1614 if (!intentState) {
1615 return;
1616 }
1617 this._stats?.timeEnd("Page Request");
1618 intentState.displayReadyCapability?.resolve(transparency);
1619 }
1620 _renderPageChunk(operatorListChunk, intentState) {
1621 for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
1622 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
1623 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
1624 }
1625 intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
1626 intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
1627 for (const internalRenderTask of intentState.renderTasks) {
1628 internalRenderTask.operatorListChanged();
1629 }
1630 if (operatorListChunk.lastChunk) {
1631 this._tryCleanup();
1632 }
1633 }
1634 _pumpOperatorList({
1635 renderingIntent,
1636 cacheKey,
1637 annotationStorageMap
1638 }) {
1639 const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
1640 pageIndex: this._pageIndex,
1641 intent: renderingIntent,
1642 cacheKey,
1643 annotationStorage: annotationStorageMap
1644 });
1645 const reader = readableStream.getReader();
1646 const intentState = this._intentStates.get(cacheKey);
1647 intentState.streamReader = reader;
1648 const pump = () => {
1649 reader.read().then(({
1650 value,
1651 done
1652 }) => {
1653 if (done) {
1654 intentState.streamReader = null;
1655 return;
1656 }
1657 if (this._transport.destroyed) {
1658 return;
1659 }
1660 this._renderPageChunk(value, intentState);
1661 pump();
1662 }, reason => {
1663 intentState.streamReader = null;
1664 if (this._transport.destroyed) {
1665 return;
1666 }
1667 if (intentState.operatorList) {
1668 intentState.operatorList.lastChunk = true;
1669 for (const internalRenderTask of intentState.renderTasks) {
1670 internalRenderTask.operatorListChanged();
1671 }
1672 this._tryCleanup();
1673 }
1674 if (intentState.displayReadyCapability) {
1675 intentState.displayReadyCapability.reject(reason);
1676 } else if (intentState.opListReadCapability) {
1677 intentState.opListReadCapability.reject(reason);
1678 } else {
1679 throw reason;
1680 }
1681 });
1682 };
1683 pump();
1684 }
1685 _abortOperatorList({
1686 intentState,
1687 reason,
1688 force = false
1689 }) {
1690 if (!intentState.streamReader) {
1691 return;
1692 }
1693 if (intentState.streamReaderCancelTimeout) {
1694 clearTimeout(intentState.streamReaderCancelTimeout);
1695 intentState.streamReaderCancelTimeout = null;
1696 }
1697 if (!force) {
1698 if (intentState.renderTasks.size > 0) {
1699 return;
1700 }
1701 if (reason instanceof _display_utils.RenderingCancelledException) {
1702 let delay = RENDERING_CANCELLED_TIMEOUT;
1703 if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
1704 delay += reason.extraDelay;
1705 }
1706 intentState.streamReaderCancelTimeout = setTimeout(() => {
1707 intentState.streamReaderCancelTimeout = null;
1708 this._abortOperatorList({
1709 intentState,
1710 reason,
1711 force: true
1712 });
1713 }, delay);
1714 return;
1715 }
1716 }
1717 intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
1718 intentState.streamReader = null;
1719 if (this._transport.destroyed) {
1720 return;
1721 }
1722 for (const [curCacheKey, curIntentState] of this._intentStates) {
1723 if (curIntentState === intentState) {
1724 this._intentStates.delete(curCacheKey);
1725 break;
1726 }
1727 }
1728 this.cleanup();
1729 }
1730 get stats() {
1731 return this._stats;
1732 }
1733}
1734exports.PDFPageProxy = PDFPageProxy;
1735class LoopbackPort {
1736 #listeners = new Set();
1737 #deferred = Promise.resolve();
1738 postMessage(obj, transfers) {
1739 const event = {
1740 data: structuredClone(obj, transfers)
1741 };
1742 this.#deferred.then(() => {
1743 for (const listener of this.#listeners) {
1744 listener.call(this, event);
1745 }
1746 });
1747 }
1748 addEventListener(name, listener) {
1749 this.#listeners.add(listener);
1750 }
1751 removeEventListener(name, listener) {
1752 this.#listeners.delete(listener);
1753 }
1754 terminate() {
1755 this.#listeners.clear();
1756 }
1757}
1758exports.LoopbackPort = LoopbackPort;
1759const PDFWorkerUtil = {
1760 isWorkerDisabled: false,
1761 fallbackWorkerSrc: null,
1762 fakeWorkerId: 0
1763};
1764exports.PDFWorkerUtil = PDFWorkerUtil;
1765{
1766 if (_is_node.isNodeJS && typeof require === "function") {
1767 PDFWorkerUtil.isWorkerDisabled = true;
1768 PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
1769 } else if (typeof document === "object") {
1770 const pdfjsFilePath = document?.currentScript?.src;
1771 if (pdfjsFilePath) {
1772 PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
1773 }
1774 }
1775 PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
1776 let base;
1777 try {
1778 base = new URL(baseUrl);
1779 if (!base.origin || base.origin === "null") {
1780 return false;
1781 }
1782 } catch (e) {
1783 return false;
1784 }
1785 const other = new URL(otherUrl, base);
1786 return base.origin === other.origin;
1787 };
1788 PDFWorkerUtil.createCDNWrapper = function (url) {
1789 const wrapper = `importScripts("${url}");`;
1790 return URL.createObjectURL(new Blob([wrapper]));
1791 };
1792}
1793class PDFWorker {
1794 static #workerPorts = new WeakMap();
1795 constructor({
1796 name = null,
1797 port = null,
1798 verbosity = (0, _util.getVerbosityLevel)()
1799 } = {}) {
1800 if (port && PDFWorker.#workerPorts.has(port)) {
1801 throw new Error("Cannot use more than one PDFWorker per port.");
1802 }
1803 this.name = name;
1804 this.destroyed = false;
1805 this.verbosity = verbosity;
1806 this._readyCapability = (0, _util.createPromiseCapability)();
1807 this._port = null;
1808 this._webWorker = null;
1809 this._messageHandler = null;
1810 if (port) {
1811 PDFWorker.#workerPorts.set(port, this);
1812 this._initializeFromPort(port);
1813 return;
1814 }
1815 this._initialize();
1816 }
1817 get promise() {
1818 return this._readyCapability.promise;
1819 }
1820 get port() {
1821 return this._port;
1822 }
1823 get messageHandler() {
1824 return this._messageHandler;
1825 }
1826 _initializeFromPort(port) {
1827 this._port = port;
1828 this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
1829 this._messageHandler.on("ready", function () {});
1830 this._readyCapability.resolve();
1831 this._messageHandler.send("configure", {
1832 verbosity: this.verbosity
1833 });
1834 }
1835 #generateTrustedURL(sourcePath) {
1836 if (window.trustedTypes) {
1837 const sanitizer = window.trustedTypes.createPolicy("foo", {
1838 createScriptURL: url => url
1839 });
1840 return sanitizer.createScriptURL(sourcePath);
1841 }
1842 return sourcePath;
1843 }
1844 _initialize() {
1845 if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
1846 let {
1847 workerSrc
1848 } = PDFWorker;
1849 try {
1850 if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
1851 workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
1852 }
1853 const worker = new Worker(this.#generateTrustedURL(workerSrc));
1854 const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
1855 const terminateEarly = () => {
1856 worker.removeEventListener("error", onWorkerError);
1857 messageHandler.destroy();
1858 worker.terminate();
1859 if (this.destroyed) {
1860 this._readyCapability.reject(new Error("Worker was destroyed"));
1861 } else {
1862 this._setupFakeWorker();
1863 }
1864 };
1865 const onWorkerError = () => {
1866 if (!this._webWorker) {
1867 terminateEarly();
1868 }
1869 };
1870 worker.addEventListener("error", onWorkerError);
1871 messageHandler.on("test", data => {
1872 worker.removeEventListener("error", onWorkerError);
1873 if (this.destroyed) {
1874 terminateEarly();
1875 return;
1876 }
1877 if (data) {
1878 this._messageHandler = messageHandler;
1879 this._port = worker;
1880 this._webWorker = worker;
1881 this._readyCapability.resolve();
1882 messageHandler.send("configure", {
1883 verbosity: this.verbosity
1884 });
1885 } else {
1886 this._setupFakeWorker();
1887 messageHandler.destroy();
1888 worker.terminate();
1889 }
1890 });
1891 messageHandler.on("ready", data => {
1892 worker.removeEventListener("error", onWorkerError);
1893 if (this.destroyed) {
1894 terminateEarly();
1895 return;
1896 }
1897 try {
1898 sendTest();
1899 } catch (e) {
1900 this._setupFakeWorker();
1901 }
1902 });
1903 const sendTest = () => {
1904 const testObj = new Uint8Array();
1905 messageHandler.send("test", testObj, [testObj.buffer]);
1906 };
1907 sendTest();
1908 return;
1909 } catch (e) {
1910 (0, _util.info)("The worker has been disabled.");
1911 }
1912 }
1913 this._setupFakeWorker();
1914 }
1915 _setupFakeWorker() {
1916 if (!PDFWorkerUtil.isWorkerDisabled) {
1917 (0, _util.warn)("Setting up fake worker.");
1918 PDFWorkerUtil.isWorkerDisabled = true;
1919 }
1920 PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
1921 if (this.destroyed) {
1922 this._readyCapability.reject(new Error("Worker was destroyed"));
1923 return;
1924 }
1925 const port = new LoopbackPort();
1926 this._port = port;
1927 const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
1928 const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
1929 WorkerMessageHandler.setup(workerHandler, port);
1930 const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
1931 this._messageHandler = messageHandler;
1932 this._readyCapability.resolve();
1933 messageHandler.send("configure", {
1934 verbosity: this.verbosity
1935 });
1936 }).catch(reason => {
1937 this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
1938 });
1939 }
1940 destroy() {
1941 this.destroyed = true;
1942 if (this._webWorker) {
1943 this._webWorker.terminate();
1944 this._webWorker = null;
1945 }
1946 PDFWorker.#workerPorts.delete(this._port);
1947 this._port = null;
1948 if (this._messageHandler) {
1949 this._messageHandler.destroy();
1950 this._messageHandler = null;
1951 }
1952 }
1953 static fromPort(params) {
1954 if (!params?.port) {
1955 throw new Error("PDFWorker.fromPort - invalid method signature.");
1956 }
1957 if (this.#workerPorts.has(params.port)) {
1958 return this.#workerPorts.get(params.port);
1959 }
1960 return new PDFWorker(params);
1961 }
1962 static get workerSrc() {
1963 if (_worker_options.GlobalWorkerOptions.workerSrc) {
1964 if (_worker_options.GlobalWorkerOptions.workerSrc.constructor.name === "Function") {
1965 return _worker_options.GlobalWorkerOptions.workerSrc();
1966 }
1967 return _worker_options.GlobalWorkerOptions.workerSrc;
1968 }
1969 if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
1970 if (!_is_node.isNodeJS) {
1971 (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
1972 }
1973 return PDFWorkerUtil.fallbackWorkerSrc;
1974 }
1975 throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
1976 }
1977 static get _mainThreadWorkerMessageHandler() {
1978 try {
1979 return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
1980 } catch (ex) {
1981 return null;
1982 }
1983 }
1984 static get _setupFakeWorkerGlobal() {
1985 const loader = async () => {
1986 const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
1987 if (mainWorkerMessageHandler) {
1988 return mainWorkerMessageHandler;
1989 }
1990 if (_is_node.isNodeJS && typeof require === "function") {
1991 const worker = eval("require")(this.workerSrc);
1992 return worker.WorkerMessageHandler;
1993 }
1994 await (0, _display_utils.loadScript)(this.workerSrc);
1995 return window.pdfjsWorker.WorkerMessageHandler;
1996 };
1997 return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
1998 }
1999}
2000exports.PDFWorker = PDFWorker;
2001class WorkerTransport {
2002 #methodPromises = new Map();
2003 #pageCache = new Map();
2004 #pagePromises = new Map();
2005 constructor(messageHandler, loadingTask, networkStream, params, factory) {
2006 this.messageHandler = messageHandler;
2007 this.loadingTask = loadingTask;
2008 this.commonObjs = new PDFObjects();
2009 this.fontLoader = new _font_loader.FontLoader({
2010 onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
2011 ownerDocument: params.ownerDocument,
2012 styleElement: params.styleElement
2013 });
2014 this._params = params;
2015 this.cMapReaderFactory = factory?.cMapReaderFactory;
2016 this.standardFontDataFactory = factory?.standardFontDataFactory;
2017 this.destroyed = false;
2018 this.destroyCapability = null;
2019 this._passwordCapability = null;
2020 this._networkStream = networkStream;
2021 this._fullReader = null;
2022 this._lastProgress = null;
2023 this.downloadInfoCapability = (0, _util.createPromiseCapability)();
2024 this.setupMessageHandler();
2025 }
2026 #cacheSimpleMethod(name, data = null) {
2027 const cachedPromise = this.#methodPromises.get(name);
2028 if (cachedPromise) {
2029 return cachedPromise;
2030 }
2031 const promise = this.messageHandler.sendWithPromise(name, data);
2032 this.#methodPromises.set(name, promise);
2033 return promise;
2034 }
2035 get annotationStorage() {
2036 return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
2037 }
2038 getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
2039 let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
2040 let annotationMap = null;
2041 switch (intent) {
2042 case "any":
2043 renderingIntent = _util.RenderingIntentFlag.ANY;
2044 break;
2045 case "display":
2046 break;
2047 case "print":
2048 renderingIntent = _util.RenderingIntentFlag.PRINT;
2049 break;
2050 default:
2051 (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
2052 }
2053 switch (annotationMode) {
2054 case _util.AnnotationMode.DISABLE:
2055 renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
2056 break;
2057 case _util.AnnotationMode.ENABLE:
2058 break;
2059 case _util.AnnotationMode.ENABLE_FORMS:
2060 renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
2061 break;
2062 case _util.AnnotationMode.ENABLE_STORAGE:
2063 renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
2064 const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
2065 annotationMap = annotationStorage.serializable;
2066 break;
2067 default:
2068 (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
2069 }
2070 if (isOpList) {
2071 renderingIntent += _util.RenderingIntentFlag.OPLIST;
2072 }
2073 return {
2074 renderingIntent,
2075 cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
2076 annotationStorageMap: annotationMap
2077 };
2078 }
2079 destroy() {
2080 if (this.destroyCapability) {
2081 return this.destroyCapability.promise;
2082 }
2083 this.destroyed = true;
2084 this.destroyCapability = (0, _util.createPromiseCapability)();
2085 if (this._passwordCapability) {
2086 this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
2087 }
2088 const waitOn = [];
2089 for (const page of this.#pageCache.values()) {
2090 waitOn.push(page._destroy());
2091 }
2092 this.#pageCache.clear();
2093 this.#pagePromises.clear();
2094 if (this.hasOwnProperty("annotationStorage")) {
2095 this.annotationStorage.resetModified();
2096 }
2097 const terminated = this.messageHandler.sendWithPromise("Terminate", null);
2098 waitOn.push(terminated);
2099 Promise.all(waitOn).then(() => {
2100 this.commonObjs.clear();
2101 this.fontLoader.clear();
2102 this.#methodPromises.clear();
2103 if (this._networkStream) {
2104 this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
2105 }
2106 if (this.messageHandler) {
2107 this.messageHandler.destroy();
2108 this.messageHandler = null;
2109 }
2110 this.destroyCapability.resolve();
2111 }, this.destroyCapability.reject);
2112 return this.destroyCapability.promise;
2113 }
2114 setupMessageHandler() {
2115 const {
2116 messageHandler,
2117 loadingTask
2118 } = this;
2119 messageHandler.on("GetReader", (data, sink) => {
2120 (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
2121 this._fullReader = this._networkStream.getFullReader();
2122 this._fullReader.onProgress = evt => {
2123 this._lastProgress = {
2124 loaded: evt.loaded,
2125 total: evt.total
2126 };
2127 };
2128 sink.onPull = () => {
2129 this._fullReader.read().then(function ({
2130 value,
2131 done
2132 }) {
2133 if (done) {
2134 sink.close();
2135 return;
2136 }
2137 (0, _util.assert)(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
2138 sink.enqueue(new Uint8Array(value), 1, [value]);
2139 }).catch(reason => {
2140 sink.error(reason);
2141 });
2142 };
2143 sink.onCancel = reason => {
2144 this._fullReader.cancel(reason);
2145 sink.ready.catch(readyReason => {
2146 if (this.destroyed) {
2147 return;
2148 }
2149 throw readyReason;
2150 });
2151 };
2152 });
2153 messageHandler.on("ReaderHeadersReady", data => {
2154 const headersCapability = (0, _util.createPromiseCapability)();
2155 const fullReader = this._fullReader;
2156 fullReader.headersReady.then(() => {
2157 if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
2158 if (this._lastProgress) {
2159 loadingTask.onProgress?.(this._lastProgress);
2160 }
2161 fullReader.onProgress = evt => {
2162 loadingTask.onProgress?.({
2163 loaded: evt.loaded,
2164 total: evt.total
2165 });
2166 };
2167 }
2168 headersCapability.resolve({
2169 isStreamingSupported: fullReader.isStreamingSupported,
2170 isRangeSupported: fullReader.isRangeSupported,
2171 contentLength: fullReader.contentLength
2172 });
2173 }, headersCapability.reject);
2174 return headersCapability.promise;
2175 });
2176 messageHandler.on("GetRangeReader", (data, sink) => {
2177 (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
2178 const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
2179 if (!rangeReader) {
2180 sink.close();
2181 return;
2182 }
2183 sink.onPull = () => {
2184 rangeReader.read().then(function ({
2185 value,
2186 done
2187 }) {
2188 if (done) {
2189 sink.close();
2190 return;
2191 }
2192 (0, _util.assert)(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
2193 sink.enqueue(new Uint8Array(value), 1, [value]);
2194 }).catch(reason => {
2195 sink.error(reason);
2196 });
2197 };
2198 sink.onCancel = reason => {
2199 rangeReader.cancel(reason);
2200 sink.ready.catch(readyReason => {
2201 if (this.destroyed) {
2202 return;
2203 }
2204 throw readyReason;
2205 });
2206 };
2207 });
2208 messageHandler.on("GetDoc", ({
2209 pdfInfo
2210 }) => {
2211 this._numPages = pdfInfo.numPages;
2212 this._htmlForXfa = pdfInfo.htmlForXfa;
2213 delete pdfInfo.htmlForXfa;
2214 loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
2215 });
2216 messageHandler.on("DocException", function (ex) {
2217 let reason;
2218 switch (ex.name) {
2219 case "PasswordException":
2220 reason = new _util.PasswordException(ex.message, ex.code);
2221 break;
2222 case "InvalidPDFException":
2223 reason = new _util.InvalidPDFException(ex.message);
2224 break;
2225 case "MissingPDFException":
2226 reason = new _util.MissingPDFException(ex.message);
2227 break;
2228 case "UnexpectedResponseException":
2229 reason = new _util.UnexpectedResponseException(ex.message, ex.status);
2230 break;
2231 case "UnknownErrorException":
2232 reason = new _util.UnknownErrorException(ex.message, ex.details);
2233 break;
2234 default:
2235 (0, _util.unreachable)("DocException - expected a valid Error.");
2236 }
2237 loadingTask._capability.reject(reason);
2238 });
2239 messageHandler.on("PasswordRequest", exception => {
2240 this._passwordCapability = (0, _util.createPromiseCapability)();
2241 if (loadingTask.onPassword) {
2242 const updatePassword = password => {
2243 if (password instanceof Error) {
2244 this._passwordCapability.reject(password);
2245 } else {
2246 this._passwordCapability.resolve({
2247 password
2248 });
2249 }
2250 };
2251 try {
2252 loadingTask.onPassword(updatePassword, exception.code);
2253 } catch (ex) {
2254 this._passwordCapability.reject(ex);
2255 }
2256 } else {
2257 this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
2258 }
2259 return this._passwordCapability.promise;
2260 });
2261 messageHandler.on("DataLoaded", data => {
2262 loadingTask.onProgress?.({
2263 loaded: data.length,
2264 total: data.length
2265 });
2266 this.downloadInfoCapability.resolve(data);
2267 });
2268 messageHandler.on("StartRenderPage", data => {
2269 if (this.destroyed) {
2270 return;
2271 }
2272 const page = this.#pageCache.get(data.pageIndex);
2273 page._startRenderPage(data.transparency, data.cacheKey);
2274 });
2275 messageHandler.on("commonobj", ([id, type, exportedData]) => {
2276 if (this.destroyed) {
2277 return;
2278 }
2279 if (this.commonObjs.has(id)) {
2280 return;
2281 }
2282 switch (type) {
2283 case "Font":
2284 const params = this._params;
2285 if ("error" in exportedData) {
2286 const exportedError = exportedData.error;
2287 (0, _util.warn)(`Error during font loading: ${exportedError}`);
2288 this.commonObjs.resolve(id, exportedError);
2289 break;
2290 }
2291 let fontRegistry = null;
2292 if (params.pdfBug && globalThis.FontInspector?.enabled) {
2293 fontRegistry = {
2294 registerFont(font, url) {
2295 globalThis.FontInspector.fontAdded(font, url);
2296 }
2297 };
2298 }
2299 const font = new _font_loader.FontFaceObject(exportedData, {
2300 isEvalSupported: params.isEvalSupported,
2301 disableFontFace: params.disableFontFace,
2302 ignoreErrors: params.ignoreErrors,
2303 onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
2304 fontRegistry
2305 });
2306 this.fontLoader.bind(font).catch(reason => {
2307 return messageHandler.sendWithPromise("FontFallback", {
2308 id
2309 });
2310 }).finally(() => {
2311 if (!params.fontExtraProperties && font.data) {
2312 font.data = null;
2313 }
2314 this.commonObjs.resolve(id, font);
2315 });
2316 break;
2317 case "FontPath":
2318 case "Image":
2319 this.commonObjs.resolve(id, exportedData);
2320 break;
2321 default:
2322 throw new Error(`Got unknown common object type ${type}`);
2323 }
2324 });
2325 messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
2326 if (this.destroyed) {
2327 return;
2328 }
2329 const pageProxy = this.#pageCache.get(pageIndex);
2330 if (pageProxy.objs.has(id)) {
2331 return;
2332 }
2333 switch (type) {
2334 case "Image":
2335 pageProxy.objs.resolve(id, imageData);
2336 const MAX_IMAGE_SIZE_TO_STORE = 8000000;
2337 if (imageData) {
2338 let length;
2339 if (imageData.bitmap) {
2340 const {
2341 width,
2342 height
2343 } = imageData;
2344 length = width * height * 4;
2345 } else {
2346 length = imageData.data?.length || 0;
2347 }
2348 if (length > MAX_IMAGE_SIZE_TO_STORE) {
2349 pageProxy.cleanupAfterRender = true;
2350 }
2351 }
2352 break;
2353 case "Pattern":
2354 pageProxy.objs.resolve(id, imageData);
2355 break;
2356 default:
2357 throw new Error(`Got unknown object type ${type}`);
2358 }
2359 });
2360 messageHandler.on("DocProgress", data => {
2361 if (this.destroyed) {
2362 return;
2363 }
2364 loadingTask.onProgress?.({
2365 loaded: data.loaded,
2366 total: data.total
2367 });
2368 });
2369 messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
2370 messageHandler.on("FetchBuiltInCMap", data => {
2371 if (this.destroyed) {
2372 return Promise.reject(new Error("Worker was destroyed."));
2373 }
2374 if (!this.cMapReaderFactory) {
2375 return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
2376 }
2377 return this.cMapReaderFactory.fetch(data);
2378 });
2379 messageHandler.on("FetchStandardFontData", data => {
2380 if (this.destroyed) {
2381 return Promise.reject(new Error("Worker was destroyed."));
2382 }
2383 if (!this.standardFontDataFactory) {
2384 return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
2385 }
2386 return this.standardFontDataFactory.fetch(data);
2387 });
2388 }
2389 _onUnsupportedFeature({
2390 featureId
2391 }) {
2392 if (this.destroyed) {
2393 return;
2394 }
2395 this.loadingTask.onUnsupportedFeature?.(featureId);
2396 }
2397 getData() {
2398 return this.messageHandler.sendWithPromise("GetData", null);
2399 }
2400 saveDocument() {
2401 if (this.annotationStorage.size <= 0) {
2402 (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
2403 }
2404 return this.messageHandler.sendWithPromise("SaveDocument", {
2405 isPureXfa: !!this._htmlForXfa,
2406 numPages: this._numPages,
2407 annotationStorage: this.annotationStorage.serializable,
2408 filename: this._fullReader?.filename ?? null
2409 }).finally(() => {
2410 this.annotationStorage.resetModified();
2411 });
2412 }
2413 getPage(pageNumber) {
2414 if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
2415 return Promise.reject(new Error("Invalid page request."));
2416 }
2417 const pageIndex = pageNumber - 1,
2418 cachedPromise = this.#pagePromises.get(pageIndex);
2419 if (cachedPromise) {
2420 return cachedPromise;
2421 }
2422 const promise = this.messageHandler.sendWithPromise("GetPage", {
2423 pageIndex
2424 }).then(pageInfo => {
2425 if (this.destroyed) {
2426 throw new Error("Transport destroyed");
2427 }
2428 const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
2429 this.#pageCache.set(pageIndex, page);
2430 return page;
2431 });
2432 this.#pagePromises.set(pageIndex, promise);
2433 return promise;
2434 }
2435 getPageIndex(ref) {
2436 if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
2437 return Promise.reject(new Error("Invalid pageIndex request."));
2438 }
2439 return this.messageHandler.sendWithPromise("GetPageIndex", {
2440 num: ref.num,
2441 gen: ref.gen
2442 });
2443 }
2444 getAnnotations(pageIndex, intent) {
2445 return this.messageHandler.sendWithPromise("GetAnnotations", {
2446 pageIndex,
2447 intent
2448 });
2449 }
2450 getFieldObjects() {
2451 return this.#cacheSimpleMethod("GetFieldObjects");
2452 }
2453 hasJSActions() {
2454 return this.#cacheSimpleMethod("HasJSActions");
2455 }
2456 getCalculationOrderIds() {
2457 return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
2458 }
2459 getDestinations() {
2460 return this.messageHandler.sendWithPromise("GetDestinations", null);
2461 }
2462 getDestination(id) {
2463 if (typeof id !== "string") {
2464 return Promise.reject(new Error("Invalid destination request."));
2465 }
2466 return this.messageHandler.sendWithPromise("GetDestination", {
2467 id
2468 });
2469 }
2470 getPageLabels() {
2471 return this.messageHandler.sendWithPromise("GetPageLabels", null);
2472 }
2473 getPageLayout() {
2474 return this.messageHandler.sendWithPromise("GetPageLayout", null);
2475 }
2476 getPageMode() {
2477 return this.messageHandler.sendWithPromise("GetPageMode", null);
2478 }
2479 getViewerPreferences() {
2480 return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
2481 }
2482 getOpenAction() {
2483 return this.messageHandler.sendWithPromise("GetOpenAction", null);
2484 }
2485 getAttachments() {
2486 return this.messageHandler.sendWithPromise("GetAttachments", null);
2487 }
2488 getJavaScript() {
2489 return this.messageHandler.sendWithPromise("GetJavaScript", null);
2490 }
2491 getDocJSActions() {
2492 return this.messageHandler.sendWithPromise("GetDocJSActions", null);
2493 }
2494 getPageJSActions(pageIndex) {
2495 return this.messageHandler.sendWithPromise("GetPageJSActions", {
2496 pageIndex
2497 });
2498 }
2499 getStructTree(pageIndex) {
2500 return this.messageHandler.sendWithPromise("GetStructTree", {
2501 pageIndex
2502 });
2503 }
2504 getOutline() {
2505 return this.messageHandler.sendWithPromise("GetOutline", null);
2506 }
2507 getOptionalContentConfig() {
2508 return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
2509 return new _optional_content_config.OptionalContentConfig(results);
2510 });
2511 }
2512 getPermissions() {
2513 return this.messageHandler.sendWithPromise("GetPermissions", null);
2514 }
2515 getMetadata() {
2516 const name = "GetMetadata",
2517 cachedPromise = this.#methodPromises.get(name);
2518 if (cachedPromise) {
2519 return cachedPromise;
2520 }
2521 const promise = this.messageHandler.sendWithPromise(name, null).then(results => {
2522 return {
2523 info: results[0],
2524 metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
2525 contentDispositionFilename: this._fullReader?.filename ?? null,
2526 contentLength: this._fullReader?.contentLength ?? null
2527 };
2528 });
2529 this.#methodPromises.set(name, promise);
2530 return promise;
2531 }
2532 getMarkInfo() {
2533 return this.messageHandler.sendWithPromise("GetMarkInfo", null);
2534 }
2535 async startCleanup(keepLoadedFonts = false) {
2536 if (this.destroyed) {
2537 return;
2538 }
2539 await this.messageHandler.sendWithPromise("Cleanup", null);
2540 for (const page of this.#pageCache.values()) {
2541 const cleanupSuccessful = page.cleanup();
2542 if (!cleanupSuccessful) {
2543 throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
2544 }
2545 }
2546 this.commonObjs.clear();
2547 if (!keepLoadedFonts) {
2548 this.fontLoader.clear();
2549 }
2550 this.#methodPromises.clear();
2551 }
2552 get loadingParams() {
2553 const {
2554 disableAutoFetch,
2555 enableXfa
2556 } = this._params;
2557 return (0, _util.shadow)(this, "loadingParams", {
2558 disableAutoFetch,
2559 enableXfa
2560 });
2561 }
2562}
2563class PDFObjects {
2564 #objs = Object.create(null);
2565 #ensureObj(objId) {
2566 const obj = this.#objs[objId];
2567 if (obj) {
2568 return obj;
2569 }
2570 return this.#objs[objId] = {
2571 capability: (0, _util.createPromiseCapability)(),
2572 data: null
2573 };
2574 }
2575 get(objId, callback = null) {
2576 if (callback) {
2577 const obj = this.#ensureObj(objId);
2578 obj.capability.promise.then(() => callback(obj.data));
2579 return null;
2580 }
2581 const obj = this.#objs[objId];
2582 if (!obj?.capability.settled) {
2583 throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
2584 }
2585 return obj.data;
2586 }
2587 has(objId) {
2588 const obj = this.#objs[objId];
2589 return obj?.capability.settled || false;
2590 }
2591 resolve(objId, data = null) {
2592 const obj = this.#ensureObj(objId);
2593 obj.data = data;
2594 obj.capability.resolve();
2595 }
2596 clear() {
2597 for (const objId in this.#objs) {
2598 const {
2599 data
2600 } = this.#objs[objId];
2601 data?.bitmap?.close();
2602 }
2603 this.#objs = Object.create(null);
2604 }
2605}
2606class RenderTask {
2607 #internalRenderTask = null;
2608 constructor(internalRenderTask) {
2609 this.#internalRenderTask = internalRenderTask;
2610 this.onContinue = null;
2611 }
2612 get promise() {
2613 return this.#internalRenderTask.capability.promise;
2614 }
2615 cancel(extraDelay = 0) {
2616 this.#internalRenderTask.cancel(null, extraDelay);
2617 }
2618 get separateAnnots() {
2619 const {
2620 separateAnnots
2621 } = this.#internalRenderTask.operatorList;
2622 if (!separateAnnots) {
2623 return false;
2624 }
2625 const {
2626 annotationCanvasMap
2627 } = this.#internalRenderTask;
2628 return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
2629 }
2630}
2631exports.RenderTask = RenderTask;
2632class InternalRenderTask {
2633 static #canvasInUse = new WeakSet();
2634 constructor({
2635 callback,
2636 params,
2637 objs,
2638 commonObjs,
2639 annotationCanvasMap,
2640 operatorList,
2641 pageIndex,
2642 canvasFactory,
2643 useRequestAnimationFrame = false,
2644 pdfBug = false,
2645 pageColors = null
2646 }) {
2647 this.callback = callback;
2648 this.params = params;
2649 this.objs = objs;
2650 this.commonObjs = commonObjs;
2651 this.annotationCanvasMap = annotationCanvasMap;
2652 this.operatorListIdx = null;
2653 this.operatorList = operatorList;
2654 this._pageIndex = pageIndex;
2655 this.canvasFactory = canvasFactory;
2656 this._pdfBug = pdfBug;
2657 this.pageColors = pageColors;
2658 this.running = false;
2659 this.graphicsReadyCallback = null;
2660 this.graphicsReady = false;
2661 this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
2662 this.cancelled = false;
2663 this.capability = (0, _util.createPromiseCapability)();
2664 this.task = new RenderTask(this);
2665 this._cancelBound = this.cancel.bind(this);
2666 this._continueBound = this._continue.bind(this);
2667 this._scheduleNextBound = this._scheduleNext.bind(this);
2668 this._nextBound = this._next.bind(this);
2669 this._canvas = params.canvasContext.canvas;
2670 }
2671 get completed() {
2672 return this.capability.promise.catch(function () {});
2673 }
2674 initializeGraphics({
2675 transparency = false,
2676 optionalContentConfig
2677 }) {
2678 if (this.cancelled) {
2679 return;
2680 }
2681 if (this._canvas) {
2682 if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
2683 throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
2684 }
2685 InternalRenderTask.#canvasInUse.add(this._canvas);
2686 }
2687 if (this._pdfBug && globalThis.StepperManager?.enabled) {
2688 this.stepper = globalThis.StepperManager.create(this._pageIndex);
2689 this.stepper.init(this.operatorList);
2690 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
2691 }
2692 const {
2693 canvasContext,
2694 viewport,
2695 transform,
2696 background,
2697 backgroundColorToReplace
2698 } = this.params;
2699 this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, {
2700 optionalContentConfig
2701 }, this.annotationCanvasMap, this.pageColors);
2702 this.gfx.beginDrawing({
2703 transform,
2704 viewport,
2705 transparency,
2706 background,
2707 backgroundColorToReplace
2708 });
2709 this.operatorListIdx = 0;
2710 this.graphicsReady = true;
2711 this.graphicsReadyCallback?.();
2712 }
2713 cancel(error = null, extraDelay = 0) {
2714 this.running = false;
2715 this.cancelled = true;
2716 this.gfx?.endDrawing();
2717 if (this._canvas) {
2718 InternalRenderTask.#canvasInUse.delete(this._canvas);
2719 }
2720 this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas", extraDelay));
2721 }
2722 operatorListChanged() {
2723 if (!this.graphicsReady) {
2724 if (!this.graphicsReadyCallback) {
2725 this.graphicsReadyCallback = this._continueBound;
2726 }
2727 return;
2728 }
2729 this.stepper?.updateOperatorList(this.operatorList);
2730 if (this.running) {
2731 return;
2732 }
2733 this._continue();
2734 }
2735 _continue() {
2736 this.running = true;
2737 if (this.cancelled) {
2738 return;
2739 }
2740 if (this.task.onContinue) {
2741 this.task.onContinue(this._scheduleNextBound);
2742 } else {
2743 this._scheduleNext();
2744 }
2745 }
2746 _scheduleNext() {
2747 window.ngxZone.runOutsideAngular(() => {
2748 if (this._useRequestAnimationFrame) {
2749 window.requestAnimationFrame(() => {
2750 this._nextBound().catch(this._cancelBound);
2751 });
2752 } else {
2753 Promise.resolve().then(this._nextBound).catch(this._cancelBound);
2754 }
2755 });
2756 }
2757 async _next() {
2758 if (this.cancelled) {
2759 return;
2760 }
2761 this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
2762 if (this.operatorListIdx === this.operatorList.argsArray.length) {
2763 this.running = false;
2764 if (this.operatorList.lastChunk) {
2765 this.gfx.endDrawing();
2766 if (this._canvas) {
2767 InternalRenderTask.#canvasInUse.delete(this._canvas);
2768 }
2769 this.callback();
2770 }
2771 }
2772 }
2773}
2774const version = '3.4.493';
2775exports.version = version;
2776const build = '7b85cf0e7';
2777exports.build = build;
2778
2779/***/ }),
2780/* 3 */
2781/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
2782
2783
2784
2785Object.defineProperty(exports, "__esModule", ({
2786 value: true
2787}));
2788exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
2789var _util = __w_pdfjs_require__(1);
2790var _editor = __w_pdfjs_require__(4);
2791var _murmurhash = __w_pdfjs_require__(8);
2792class AnnotationStorage {
2793 #modified = false;
2794 #storage = new Map();
2795 constructor() {
2796 this.onSetModified = null;
2797 this.onResetModified = null;
2798 this.onAnnotationEditor = null;
2799 }
2800 getValue(key, fieldname, defaultValue, radioButtonField = undefined) {
2801 let obj = this.#storage.get(key);
2802 if (obj === undefined) {
2803 if (window.getFormValue) {
2804 window.assignFormIdAndFieldName(key, fieldname, radioButtonField);
2805 const ngObj = window.getFormValue(fieldname);
2806 if (ngObj !== undefined && ngObj.value !== undefined) {
2807 if (radioButtonField) {
2808 const value = {
2809 value: ngObj.value === radioButtonField
2810 };
2811 obj = value;
2812 } else {
2813 obj = ngObj;
2814 }
2815 this.setValue(key, undefined, obj, undefined, true);
2816 }
2817 if (obj === undefined && defaultValue !== undefined && defaultValue.value !== undefined && defaultValue.value !== "") {
2818 if (radioButtonField) {
2819 if (defaultValue.value) {
2820 window.setFormValue(fieldname, radioButtonField);
2821 }
2822 } else {
2823 window.setFormValue(fieldname, defaultValue.value);
2824 }
2825 }
2826 }
2827 }
2828 if (obj === undefined) {
2829 return defaultValue;
2830 }
2831 return Object.assign(defaultValue, obj);
2832 }
2833 getRawValue(key) {
2834 return this.#storage.get(key);
2835 }
2836 remove(key) {
2837 this.#storage.delete(key);
2838 if (this.#storage.size === 0) {
2839 this.resetModified();
2840 }
2841 if (typeof this.onAnnotationEditor === "function") {
2842 for (const value of this.#storage.values()) {
2843 if (value instanceof _editor.AnnotationEditor) {
2844 return;
2845 }
2846 }
2847 this.onAnnotationEditor(null);
2848 }
2849 }
2850 setValue(key, fieldname, value, radioButtonField = undefined, isDefaultValue = false) {
2851 const obj = this.#storage.get(key);
2852 let modified = false;
2853 if (obj !== undefined) {
2854 for (const [entry, val] of Object.entries(value)) {
2855 if (entry !== "radioValue" && entry !== "emitMessage" && obj[entry] !== val) {
2856 modified = true;
2857 obj[entry] = val;
2858 }
2859 }
2860 } else {
2861 if (!isDefaultValue) {
2862 modified = true;
2863 }
2864 this.#storage.set(key, value);
2865 }
2866 if (modified) {
2867 this.#setModified();
2868 if (fieldname?.constructor.name !== "FreeTextEditor") {
2869 if (fieldname || radioButtonField) {
2870 if (window.setFormValue) {
2871 if (value.items) {
2872 window.setFormValue(fieldname, value.items);
2873 } else if (value.emitMessage === false) {} else if (value.radioValue) {
2874 window.setFormValue(fieldname, value.radioValue);
2875 } else if (value.exportValue) {
2876 window.setFormValue(fieldname, value.exportValue);
2877 } else {
2878 for (const val of Object.values(value)) {
2879 window.setFormValue(fieldname, val);
2880 }
2881 }
2882 }
2883 }
2884 }
2885 }
2886 if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
2887 this.onAnnotationEditor(value.constructor._type);
2888 }
2889 }
2890 has(key) {
2891 return this.#storage.has(key);
2892 }
2893 getAll() {
2894 return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null;
2895 }
2896 setAll(obj) {
2897 for (const [key, val] of Object.entries(obj)) {
2898 this.setValue(key, val);
2899 }
2900 }
2901 get size() {
2902 return this.#storage.size;
2903 }
2904 #setModified() {
2905 if (!this.#modified) {
2906 this.#modified = true;
2907 if (typeof this.onSetModified === "function") {
2908 this.onSetModified();
2909 }
2910 }
2911 }
2912 resetModified() {
2913 if (this.#modified) {
2914 this.#modified = false;
2915 if (typeof this.onResetModified === "function") {
2916 this.onResetModified();
2917 }
2918 }
2919 }
2920 get print() {
2921 return new PrintAnnotationStorage(this);
2922 }
2923 get serializable() {
2924 if (this.#storage.size === 0) {
2925 return null;
2926 }
2927 const clone = new Map();
2928 for (const [key, val] of this.#storage) {
2929 const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
2930 if (serialized) {
2931 clone.set(key, serialized);
2932 }
2933 }
2934 return clone;
2935 }
2936 static getHash(map) {
2937 if (!map) {
2938 return "";
2939 }
2940 const hash = new _murmurhash.MurmurHash3_64();
2941 for (const [key, val] of map) {
2942 hash.update(`${key}:${JSON.stringify(val)}`);
2943 }
2944 return hash.hexdigest();
2945 }
2946}
2947exports.AnnotationStorage = AnnotationStorage;
2948class PrintAnnotationStorage extends AnnotationStorage {
2949 #serializable = null;
2950 constructor(parent) {
2951 super();
2952 this.#serializable = structuredClone(parent.serializable);
2953 }
2954 get print() {
2955 (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
2956 }
2957 get serializable() {
2958 return this.#serializable;
2959 }
2960}
2961exports.PrintAnnotationStorage = PrintAnnotationStorage;
2962
2963/***/ }),
2964/* 4 */
2965/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
2966
2967
2968
2969Object.defineProperty(exports, "__esModule", ({
2970 value: true
2971}));
2972exports.AnnotationEditor = void 0;
2973var _tools = __w_pdfjs_require__(5);
2974var _util = __w_pdfjs_require__(1);
2975class AnnotationEditor {
2976 #boundFocusin = this.focusin.bind(this);
2977 #boundFocusout = this.focusout.bind(this);
2978 #hasBeenSelected = false;
2979 #isEditing = false;
2980 #isInEditMode = false;
2981 _uiManager = null;
2982 #zIndex = AnnotationEditor._zIndex++;
2983 static _colorManager = new _tools.ColorManager();
2984 static _zIndex = 1;
2985 constructor(parameters) {
2986 if (this.constructor === AnnotationEditor) {
2987 (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
2988 }
2989 this.parent = parameters.parent;
2990 this.id = parameters.id;
2991 this.width = this.height = null;
2992 this.pageIndex = parameters.parent.pageIndex;
2993 this.name = parameters.name;
2994 this.div = null;
2995 this._uiManager = parameters.uiManager;
2996 const {
2997 rotation,
2998 rawDims: {
2999 pageWidth,
3000 pageHeight,
3001 pageX,
3002 pageY
3003 }
3004 } = this.parent.viewport;
3005 this.rotation = rotation;
3006 this.pageDimensions = [pageWidth, pageHeight];
3007 this.pageTranslation = [pageX, pageY];
3008 const [width, height] = this.parentDimensions;
3009 this.x = parameters.x / width;
3010 this.y = parameters.y / height;
3011 this.isAttachedToDOM = false;
3012 }
3013 static get _defaultLineColor() {
3014 return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
3015 }
3016 addCommands(params) {
3017 this._uiManager.addCommands(params);
3018 }
3019 get currentLayer() {
3020 return this._uiManager.currentLayer;
3021 }
3022 setInBackground() {
3023 this.div.style.zIndex = 0;
3024 }
3025 setInForeground() {
3026 this.div.style.zIndex = this.#zIndex;
3027 }
3028 setParent(parent) {
3029 if (parent !== null) {
3030 this.pageIndex = parent.pageIndex;
3031 this.pageDimensions = parent.pageDimensions;
3032 }
3033 this.parent = parent;
3034 }
3035 focusin(event) {
3036 if (!this.#hasBeenSelected) {
3037 this.parent.setSelected(this);
3038 } else {
3039 this.#hasBeenSelected = false;
3040 }
3041 }
3042 focusout(event) {
3043 if (!this.isAttachedToDOM) {
3044 return;
3045 }
3046 const target = event.relatedTarget;
3047 if (target?.closest(`#${this.id}`)) {
3048 return;
3049 }
3050 event.preventDefault();
3051 if (!this.parent?.isMultipleSelection) {
3052 this.commitOrRemove();
3053 }
3054 }
3055 commitOrRemove() {
3056 if (this.isEmpty()) {
3057 this.remove();
3058 } else {
3059 this.commit();
3060 }
3061 }
3062 commit() {
3063 this.addToAnnotationStorage();
3064 }
3065 addToAnnotationStorage() {
3066 this._uiManager.addToAnnotationStorage(this);
3067 }
3068 dragstart(event) {
3069 const rect = this.parent.div.getBoundingClientRect();
3070 this.startX = event.clientX - rect.x;
3071 this.startY = event.clientY - rect.y;
3072 event.dataTransfer.setData("text/plain", this.id);
3073 event.dataTransfer.effectAllowed = "move";
3074 }
3075 setAt(x, y, tx, ty) {
3076 const [width, height] = this.parentDimensions;
3077 [tx, ty] = this.screenToPageTranslation(tx, ty);
3078 this.x = (x + tx) / width;
3079 this.y = (y + ty) / height;
3080 this.div.style.left = `${100 * this.x}%`;
3081 this.div.style.top = `${100 * this.y}%`;
3082 }
3083 translate(x, y) {
3084 const [width, height] = this.parentDimensions;
3085 [x, y] = this.screenToPageTranslation(x, y);
3086 this.x += x / width;
3087 this.y += y / height;
3088 this.div.style.left = `${100 * this.x}%`;
3089 this.div.style.top = `${100 * this.y}%`;
3090 }
3091 screenToPageTranslation(x, y) {
3092 switch (this.parentRotation) {
3093 case 90:
3094 return [y, -x];
3095 case 180:
3096 return [-x, -y];
3097 case 270:
3098 return [-y, x];
3099 default:
3100 return [x, y];
3101 }
3102 }
3103 get parentScale() {
3104 return this._uiManager.viewParameters.realScale;
3105 }
3106 get parentRotation() {
3107 return this._uiManager.viewParameters.rotation;
3108 }
3109 get parentDimensions() {
3110 const {
3111 realScale
3112 } = this._uiManager.viewParameters;
3113 const [pageWidth, pageHeight] = this.pageDimensions;
3114 return [pageWidth * realScale, pageHeight * realScale];
3115 }
3116 setDims(width, height) {
3117 const [parentWidth, parentHeight] = this.parentDimensions;
3118 this.div.style.width = `${100 * width / parentWidth}%`;
3119 this.div.style.height = `${100 * height / parentHeight}%`;
3120 }
3121 fixDims() {
3122 const {
3123 style
3124 } = this.div;
3125 const {
3126 height,
3127 width
3128 } = style;
3129 const widthPercent = width.endsWith("%");
3130 const heightPercent = height.endsWith("%");
3131 if (widthPercent && heightPercent) {
3132 return;
3133 }
3134 const [parentWidth, parentHeight] = this.parentDimensions;
3135 if (!widthPercent) {
3136 style.width = `${100 * parseFloat(width) / parentWidth}%`;
3137 }
3138 if (!heightPercent) {
3139 style.height = `${100 * parseFloat(height) / parentHeight}%`;
3140 }
3141 }
3142 getInitialTranslation() {
3143 return [0, 0];
3144 }
3145 render() {
3146 this.div = document.createElement("div");
3147 this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
3148 this.div.className = this.name;
3149 this.div.setAttribute("id", this.id);
3150 this.div.setAttribute("tabIndex", 0);
3151 this.setInForeground();
3152 this.div.addEventListener("focusin", this.#boundFocusin);
3153 this.div.addEventListener("focusout", this.#boundFocusout);
3154 const [tx, ty] = this.getInitialTranslation();
3155 this.translate(tx, ty);
3156 (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
3157 return this.div;
3158 }
3159 pointerdown(event) {
3160 const {
3161 isMac
3162 } = _util.FeatureTest.platform;
3163 if (event.button !== 0 || event.ctrlKey && isMac) {
3164 event.preventDefault();
3165 return;
3166 }
3167 if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
3168 this.parent.toggleSelected(this);
3169 } else {
3170 this.parent.setSelected(this);
3171 }
3172 this.#hasBeenSelected = true;
3173 }
3174 getRect(tx, ty) {
3175 const scale = this.parentScale;
3176 const [pageWidth, pageHeight] = this.pageDimensions;
3177 const [pageX, pageY] = this.pageTranslation;
3178 const shiftX = tx / scale;
3179 const shiftY = ty / scale;
3180 const x = this.x * pageWidth;
3181 const y = this.y * pageHeight;
3182 const width = this.width * pageWidth;
3183 const height = this.height * pageHeight;
3184 switch (this.rotation) {
3185 case 0:
3186 return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
3187 case 90:
3188 return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
3189 case 180:
3190 return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
3191 case 270:
3192 return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
3193 default:
3194 throw new Error("Invalid rotation");
3195 }
3196 }
3197 getRectInCurrentCoords(rect, pageHeight) {
3198 const [x1, y1, x2, y2] = rect;
3199 const width = x2 - x1;
3200 const height = y2 - y1;
3201 switch (this.rotation) {
3202 case 0:
3203 return [x1, pageHeight - y2, width, height];
3204 case 90:
3205 return [x1, pageHeight - y1, height, width];
3206 case 180:
3207 return [x2, pageHeight - y1, width, height];
3208 case 270:
3209 return [x2, pageHeight - y2, height, width];
3210 default:
3211 throw new Error("Invalid rotation");
3212 }
3213 }
3214 onceAdded() {}
3215 isEmpty() {
3216 return false;
3217 }
3218 enableEditMode() {
3219 this.#isInEditMode = true;
3220 }
3221 disableEditMode() {
3222 this.#isInEditMode = false;
3223 }
3224 isInEditMode() {
3225 return this.#isInEditMode;
3226 }
3227 shouldGetKeyboardEvents() {
3228 return false;
3229 }
3230 needsToBeRebuilt() {
3231 return this.div && !this.isAttachedToDOM;
3232 }
3233 rebuild() {
3234 this.div?.addEventListener("focusin", this.#boundFocusin);
3235 }
3236 serialize() {
3237 (0, _util.unreachable)("An editor must be serializable");
3238 }
3239 static deserialize(data, parent, uiManager) {
3240 const editor = new this.prototype.constructor({
3241 parent,
3242 id: parent.getNextId(),
3243 uiManager
3244 });
3245 editor.rotation = data.rotation;
3246 const [pageWidth, pageHeight] = editor.pageDimensions;
3247 const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
3248 editor.x = x / pageWidth;
3249 editor.y = y / pageHeight;
3250 editor.width = width / pageWidth;
3251 editor.height = height / pageHeight;
3252 return editor;
3253 }
3254 remove() {
3255 this.div.removeEventListener("focusin", this.#boundFocusin);
3256 this.div.removeEventListener("focusout", this.#boundFocusout);
3257 if (!this.isEmpty()) {
3258 this.commit();
3259 }
3260 this.parent.remove(this);
3261 }
3262 select() {
3263 this.div?.classList.add("selectedEditor");
3264 }
3265 unselect() {
3266 this.div?.classList.remove("selectedEditor");
3267 }
3268 updateParams(type, value) {}
3269 disableEditing() {}
3270 enableEditing() {}
3271 get propertiesToUpdate() {
3272 return {};
3273 }
3274 get contentDiv() {
3275 return this.div;
3276 }
3277 get isEditing() {
3278 return this.#isEditing;
3279 }
3280 set isEditing(value) {
3281 this.#isEditing = value;
3282 if (value) {
3283 this.parent.setSelected(this);
3284 this.parent.setActiveEditor(this);
3285 } else {
3286 this.parent.setActiveEditor(null);
3287 }
3288 }
3289}
3290exports.AnnotationEditor = AnnotationEditor;
3291
3292/***/ }),
3293/* 5 */
3294/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3295
3296
3297
3298Object.defineProperty(exports, "__esModule", ({
3299 value: true
3300}));
3301exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
3302exports.bindEvents = bindEvents;
3303exports.opacityToHex = opacityToHex;
3304var _util = __w_pdfjs_require__(1);
3305var _display_utils = __w_pdfjs_require__(6);
3306function bindEvents(obj, element, names) {
3307 for (const name of names) {
3308 element.addEventListener(name, obj[name].bind(obj));
3309 }
3310}
3311function opacityToHex(opacity) {
3312 return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
3313}
3314class IdManager {
3315 #id = 0;
3316 getId() {
3317 return `${_util.AnnotationEditorPrefix}${this.#id++}`;
3318 }
3319}
3320class CommandManager {
3321 #commands = [];
3322 #locked = false;
3323 #maxSize;
3324 #position = -1;
3325 constructor(maxSize = 128) {
3326 this.#maxSize = maxSize;
3327 }
3328 add({
3329 cmd,
3330 undo,
3331 mustExec,
3332 type = NaN,
3333 overwriteIfSameType = false,
3334 keepUndo = false
3335 }) {
3336 if (mustExec) {
3337 cmd();
3338 }
3339 if (this.#locked) {
3340 return;
3341 }
3342 const save = {
3343 cmd,
3344 undo,
3345 type
3346 };
3347 if (this.#position === -1) {
3348 if (this.#commands.length > 0) {
3349 this.#commands.length = 0;
3350 }
3351 this.#position = 0;
3352 this.#commands.push(save);
3353 return;
3354 }
3355 if (overwriteIfSameType && this.#commands[this.#position].type === type) {
3356 if (keepUndo) {
3357 save.undo = this.#commands[this.#position].undo;
3358 }
3359 this.#commands[this.#position] = save;
3360 return;
3361 }
3362 const next = this.#position + 1;
3363 if (next === this.#maxSize) {
3364 this.#commands.splice(0, 1);
3365 } else {
3366 this.#position = next;
3367 if (next < this.#commands.length) {
3368 this.#commands.splice(next);
3369 }
3370 }
3371 this.#commands.push(save);
3372 }
3373 undo() {
3374 if (this.#position === -1) {
3375 return;
3376 }
3377 this.#locked = true;
3378 this.#commands[this.#position].undo();
3379 this.#locked = false;
3380 this.#position -= 1;
3381 }
3382 redo() {
3383 if (this.#position < this.#commands.length - 1) {
3384 this.#position += 1;
3385 this.#locked = true;
3386 this.#commands[this.#position].cmd();
3387 this.#locked = false;
3388 }
3389 }
3390 hasSomethingToUndo() {
3391 return this.#position !== -1;
3392 }
3393 hasSomethingToRedo() {
3394 return this.#position < this.#commands.length - 1;
3395 }
3396 destroy() {
3397 this.#commands = null;
3398 }
3399}
3400exports.CommandManager = CommandManager;
3401class KeyboardManager {
3402 constructor(callbacks) {
3403 this.buffer = [];
3404 this.callbacks = new Map();
3405 this.allKeys = new Set();
3406 const {
3407 isMac
3408 } = _util.FeatureTest.platform;
3409 for (const [keys, callback] of callbacks) {
3410 for (const key of keys) {
3411 const isMacKey = key.startsWith("mac+");
3412 if (isMac && isMacKey) {
3413 this.callbacks.set(key.slice(4), callback);
3414 this.allKeys.add(key.split("+").at(-1));
3415 } else if (!isMac && !isMacKey) {
3416 this.callbacks.set(key, callback);
3417 this.allKeys.add(key.split("+").at(-1));
3418 }
3419 }
3420 }
3421 }
3422 #serialize(event) {
3423 if (event.altKey) {
3424 this.buffer.push("alt");
3425 }
3426 if (event.ctrlKey) {
3427 this.buffer.push("ctrl");
3428 }
3429 if (event.metaKey) {
3430 this.buffer.push("meta");
3431 }
3432 if (event.shiftKey) {
3433 this.buffer.push("shift");
3434 }
3435 this.buffer.push(event.key);
3436 const str = this.buffer.join("+");
3437 this.buffer.length = 0;
3438 return str;
3439 }
3440 exec(self, event) {
3441 if (!this.allKeys.has(event.key)) {
3442 return;
3443 }
3444 const callback = this.callbacks.get(this.#serialize(event));
3445 if (!callback) {
3446 return;
3447 }
3448 callback.bind(self)();
3449 event.stopPropagation();
3450 event.preventDefault();
3451 }
3452}
3453exports.KeyboardManager = KeyboardManager;
3454class ColorManager {
3455 static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
3456 get _colors() {
3457 const colors = new Map([["CanvasText", null], ["Canvas", null]]);
3458 (0, _display_utils.getColorValues)(colors);
3459 return (0, _util.shadow)(this, "_colors", colors);
3460 }
3461 convert(color) {
3462 const rgb = (0, _display_utils.getRGB)(color);
3463 if (!window.matchMedia("(forced-colors: active)").matches) {
3464 return rgb;
3465 }
3466 for (const [name, RGB] of this._colors) {
3467 if (RGB.every((x, i) => x === rgb[i])) {
3468 return ColorManager._colorsMapping.get(name);
3469 }
3470 }
3471 return rgb;
3472 }
3473 getHexCode(name) {
3474 const rgb = this._colors.get(name);
3475 if (!rgb) {
3476 return name;
3477 }
3478 return _util.Util.makeHexColor(...rgb);
3479 }
3480}
3481exports.ColorManager = ColorManager;
3482class AnnotationEditorUIManager {
3483 #activeEditor = null;
3484 #allEditors = new Map();
3485 #allLayers = new Map();
3486 #annotationStorage = null;
3487 #commandManager = new CommandManager();
3488 #currentPageIndex = 0;
3489 #editorTypes = null;
3490 #editorsToRescale = new Set();
3491 #eventBus = null;
3492 #idManager = new IdManager();
3493 #isEnabled = false;
3494 #mode = _util.AnnotationEditorType.NONE;
3495 #selectedEditors = new Set();
3496 #boundCopy = this.copy.bind(this);
3497 #boundCut = this.cut.bind(this);
3498 #boundPaste = this.paste.bind(this);
3499 #boundKeydown = this.keydown.bind(this);
3500 #boundOnEditingAction = this.onEditingAction.bind(this);
3501 #boundOnPageChanging = this.onPageChanging.bind(this);
3502 #boundOnScaleChanging = this.onScaleChanging.bind(this);
3503 #boundOnRotationChanging = this.onRotationChanging.bind(this);
3504 #previousStates = {
3505 isEditing: false,
3506 isEmpty: true,
3507 hasSomethingToUndo: false,
3508 hasSomethingToRedo: false,
3509 hasSelectedEditor: false
3510 };
3511 #container = null;
3512 static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+z", "mac+meta+z"], AnnotationEditorUIManager.prototype.undo], [["ctrl+y", "ctrl+shift+Z", "mac+meta+shift+Z"], AnnotationEditorUIManager.prototype.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete"], AnnotationEditorUIManager.prototype.delete], [["Escape", "mac+Escape"], AnnotationEditorUIManager.prototype.unselectAll]]);
3513 constructor(container, eventBus, annotationStorage) {
3514 this.#container = container;
3515 this.#eventBus = eventBus;
3516 this.#eventBus._on("editingaction", this.#boundOnEditingAction);
3517 this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
3518 this.#eventBus._on("scalechanging", this.#boundOnScaleChanging);
3519 this.#eventBus._on("rotationchanging", this.#boundOnRotationChanging);
3520 this.#annotationStorage = annotationStorage;
3521 this.viewParameters = {
3522 realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS,
3523 rotation: 0
3524 };
3525 }
3526 destroy() {
3527 this.#removeKeyboardManager();
3528 this.#eventBus._off("editingaction", this.#boundOnEditingAction);
3529 this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
3530 this.#eventBus._off("scalechanging", this.#boundOnScaleChanging);
3531 this.#eventBus._off("rotationchanging", this.#boundOnRotationChanging);
3532 for (const layer of this.#allLayers.values()) {
3533 layer.destroy();
3534 }
3535 this.#allLayers.clear();
3536 this.#allEditors.clear();
3537 this.#editorsToRescale.clear();
3538 this.#activeEditor = null;
3539 this.#selectedEditors.clear();
3540 this.#commandManager.destroy();
3541 }
3542 onPageChanging({
3543 pageNumber
3544 }) {
3545 this.#currentPageIndex = pageNumber - 1;
3546 }
3547 focusMainContainer() {
3548 this.#container.focus();
3549 }
3550 addShouldRescale(editor) {
3551 this.#editorsToRescale.add(editor);
3552 }
3553 removeShouldRescale(editor) {
3554 this.#editorsToRescale.delete(editor);
3555 }
3556 onScaleChanging({
3557 scale
3558 }) {
3559 this.commitOrRemove();
3560 this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS;
3561 for (const editor of this.#editorsToRescale) {
3562 editor.onScaleChanging();
3563 }
3564 }
3565 onRotationChanging({
3566 pagesRotation
3567 }) {
3568 this.commitOrRemove();
3569 this.viewParameters.rotation = pagesRotation;
3570 }
3571 addToAnnotationStorage(editor) {
3572 if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
3573 this.#annotationStorage.setValue(editor.id, null, editor);
3574 }
3575 }
3576 #addKeyboardManager() {
3577 this.#container.addEventListener("keydown", this.#boundKeydown);
3578 }
3579 #removeKeyboardManager() {
3580 this.#container.removeEventListener("keydown", this.#boundKeydown);
3581 }
3582 #addCopyPasteListeners() {
3583 document.addEventListener("copy", this.#boundCopy);
3584 document.addEventListener("cut", this.#boundCut);
3585 document.addEventListener("paste", this.#boundPaste);
3586 }
3587 #removeCopyPasteListeners() {
3588 document.removeEventListener("copy", this.#boundCopy);
3589 document.removeEventListener("cut", this.#boundCut);
3590 document.removeEventListener("paste", this.#boundPaste);
3591 }
3592 copy(event) {
3593 event.preventDefault();
3594 if (this.#activeEditor) {
3595 this.#activeEditor.commitOrRemove();
3596 }
3597 if (!this.hasSelection) {
3598 return;
3599 }
3600 const editors = [];
3601 for (const editor of this.#selectedEditors) {
3602 if (!editor.isEmpty()) {
3603 editors.push(editor.serialize());
3604 }
3605 }
3606 if (editors.length === 0) {
3607 return;
3608 }
3609 event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
3610 }
3611 cut(event) {
3612 this.copy(event);
3613 this.delete();
3614 }
3615 paste(event) {
3616 event.preventDefault();
3617 let data = event.clipboardData.getData("application/pdfjs");
3618 if (!data) {
3619 return;
3620 }
3621 try {
3622 data = JSON.parse(data);
3623 } catch (ex) {
3624 (0, _util.warn)(`paste: "${ex.message}".`);
3625 return;
3626 }
3627 if (!Array.isArray(data)) {
3628 return;
3629 }
3630 this.unselectAll();
3631 const layer = this.#allLayers.get(this.#currentPageIndex);
3632 try {
3633 const newEditors = [];
3634 for (const editor of data) {
3635 const deserializedEditor = layer.deserialize(editor);
3636 if (!deserializedEditor) {
3637 return;
3638 }
3639 newEditors.push(deserializedEditor);
3640 }
3641 const cmd = () => {
3642 for (const editor of newEditors) {
3643 this.#addEditorToLayer(editor);
3644 }
3645 this.#selectEditors(newEditors);
3646 };
3647 const undo = () => {
3648 for (const editor of newEditors) {
3649 editor.remove();
3650 }
3651 };
3652 this.addCommands({
3653 cmd,
3654 undo,
3655 mustExec: true
3656 });
3657 } catch (ex) {
3658 (0, _util.warn)(`paste: "${ex.message}".`);
3659 }
3660 }
3661 keydown(event) {
3662 if (!this.getActive()?.shouldGetKeyboardEvents()) {
3663 AnnotationEditorUIManager._keyboardManager.exec(this, event);
3664 }
3665 }
3666 onEditingAction(details) {
3667 if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
3668 this[details.name]();
3669 }
3670 }
3671 #dispatchUpdateStates(details) {
3672 const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
3673 if (hasChanged) {
3674 this.#eventBus.dispatch("annotationeditorstateschanged", {
3675 source: this,
3676 details: Object.assign(this.#previousStates, details)
3677 });
3678 }
3679 }
3680 #dispatchUpdateUI(details) {
3681 this.#eventBus.dispatch("annotationeditorparamschanged", {
3682 source: this,
3683 details
3684 });
3685 }
3686 setEditingState(isEditing) {
3687 if (isEditing) {
3688 this.#addKeyboardManager();
3689 this.#addCopyPasteListeners();
3690 this.#dispatchUpdateStates({
3691 isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
3692 isEmpty: this.#isEmpty(),
3693 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
3694 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
3695 hasSelectedEditor: false
3696 });
3697 } else {
3698 this.#removeKeyboardManager();
3699 this.#removeCopyPasteListeners();
3700 this.#dispatchUpdateStates({
3701 isEditing: false
3702 });
3703 }
3704 }
3705 registerEditorTypes(types) {
3706 if (this.#editorTypes) {
3707 return;
3708 }
3709 this.#editorTypes = types;
3710 for (const editorType of this.#editorTypes) {
3711 this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
3712 }
3713 }
3714 getId() {
3715 return this.#idManager.getId();
3716 }
3717 get currentLayer() {
3718 return this.#allLayers.get(this.#currentPageIndex);
3719 }
3720 get currentPageIndex() {
3721 return this.#currentPageIndex;
3722 }
3723 addLayer(layer) {
3724 this.#allLayers.set(layer.pageIndex, layer);
3725 if (this.#isEnabled) {
3726 layer.enable();
3727 } else {
3728 layer.disable();
3729 }
3730 }
3731 removeLayer(layer) {
3732 this.#allLayers.delete(layer.pageIndex);
3733 }
3734 updateMode(mode) {
3735 this.#mode = mode;
3736 if (mode === _util.AnnotationEditorType.NONE) {
3737 this.setEditingState(false);
3738 this.#disableAll();
3739 } else {
3740 this.setEditingState(true);
3741 this.#enableAll();
3742 for (const layer of this.#allLayers.values()) {
3743 layer.updateMode(mode);
3744 }
3745 }
3746 }
3747 updateToolbar(mode) {
3748 if (mode === this.#mode) {
3749 return;
3750 }
3751 this.#eventBus.dispatch("switchannotationeditormode", {
3752 source: this,
3753 mode
3754 });
3755 }
3756 updateParams(type, value) {
3757 if (!this.#editorTypes) {
3758 return;
3759 }
3760 for (const editor of this.#selectedEditors) {
3761 editor.updateParams(type, value);
3762 }
3763 for (const editorType of this.#editorTypes) {
3764 editorType.updateDefaultParams(type, value);
3765 }
3766 }
3767 #enableAll() {
3768 if (!this.#isEnabled) {
3769 this.#isEnabled = true;
3770 for (const layer of this.#allLayers.values()) {
3771 layer.enable();
3772 }
3773 }
3774 }
3775 #disableAll() {
3776 this.unselectAll();
3777 if (this.#isEnabled) {
3778 this.#isEnabled = false;
3779 for (const layer of this.#allLayers.values()) {
3780 layer.disable();
3781 }
3782 }
3783 }
3784 getEditors(pageIndex) {
3785 const editors = [];
3786 for (const editor of this.#allEditors.values()) {
3787 if (editor.pageIndex === pageIndex) {
3788 editors.push(editor);
3789 }
3790 }
3791 return editors;
3792 }
3793 getEditor(id) {
3794 return this.#allEditors.get(id);
3795 }
3796 addEditor(editor) {
3797 this.#allEditors.set(editor.id, editor);
3798 }
3799 removeEditor(editor) {
3800 this.#allEditors.delete(editor.id);
3801 this.unselect(editor);
3802 this.#annotationStorage?.remove(editor.id);
3803 }
3804 #addEditorToLayer(editor) {
3805 const layer = this.#allLayers.get(editor.pageIndex);
3806 if (layer) {
3807 layer.addOrRebuild(editor);
3808 } else {
3809 this.addEditor(editor);
3810 }
3811 }
3812 setActiveEditor(editor) {
3813 if (this.#activeEditor === editor) {
3814 return;
3815 }
3816 this.#activeEditor = editor;
3817 if (editor) {
3818 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3819 }
3820 }
3821 toggleSelected(editor) {
3822 if (this.#selectedEditors.has(editor)) {
3823 this.#selectedEditors.delete(editor);
3824 editor.unselect();
3825 this.#dispatchUpdateStates({
3826 hasSelectedEditor: this.hasSelection
3827 });
3828 return;
3829 }
3830 this.#selectedEditors.add(editor);
3831 editor.select();
3832 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3833 this.#dispatchUpdateStates({
3834 hasSelectedEditor: true
3835 });
3836 }
3837 setSelected(editor) {
3838 for (const ed of this.#selectedEditors) {
3839 if (ed !== editor) {
3840 ed.unselect();
3841 }
3842 }
3843 this.#selectedEditors.clear();
3844 this.#selectedEditors.add(editor);
3845 editor.select();
3846 this.#dispatchUpdateUI(editor.propertiesToUpdate);
3847 this.#dispatchUpdateStates({
3848 hasSelectedEditor: true
3849 });
3850 }
3851 isSelected(editor) {
3852 return this.#selectedEditors.has(editor);
3853 }
3854 unselect(editor) {
3855 editor.unselect();
3856 this.#selectedEditors.delete(editor);
3857 this.#dispatchUpdateStates({
3858 hasSelectedEditor: this.hasSelection
3859 });
3860 }
3861 get hasSelection() {
3862 return this.#selectedEditors.size !== 0;
3863 }
3864 undo() {
3865 this.#commandManager.undo();
3866 this.#dispatchUpdateStates({
3867 hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
3868 hasSomethingToRedo: true,
3869 isEmpty: this.#isEmpty()
3870 });
3871 }
3872 redo() {
3873 this.#commandManager.redo();
3874 this.#dispatchUpdateStates({
3875 hasSomethingToUndo: true,
3876 hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
3877 isEmpty: this.#isEmpty()
3878 });
3879 }
3880 addCommands(params) {
3881 this.#commandManager.add(params);
3882 this.#dispatchUpdateStates({
3883 hasSomethingToUndo: true,
3884 hasSomethingToRedo: false,
3885 isEmpty: this.#isEmpty()
3886 });
3887 }
3888 #isEmpty() {
3889 if (this.#allEditors.size === 0) {
3890 return true;
3891 }
3892 if (this.#allEditors.size === 1) {
3893 for (const editor of this.#allEditors.values()) {
3894 return editor.isEmpty();
3895 }
3896 }
3897 return false;
3898 }
3899 delete() {
3900 this.commitOrRemove();
3901 if (!this.hasSelection) {
3902 return;
3903 }
3904 const editors = [...this.#selectedEditors];
3905 const cmd = () => {
3906 for (const editor of editors) {
3907 editor.remove();
3908 }
3909 };
3910 const undo = () => {
3911 for (const editor of editors) {
3912 this.#addEditorToLayer(editor);
3913 }
3914 };
3915 this.addCommands({
3916 cmd,
3917 undo,
3918 mustExec: true
3919 });
3920 }
3921 commitOrRemove() {
3922 this.#activeEditor?.commitOrRemove();
3923 }
3924 #selectEditors(editors) {
3925 this.#selectedEditors.clear();
3926 for (const editor of editors) {
3927 if (editor.isEmpty()) {
3928 continue;
3929 }
3930 this.#selectedEditors.add(editor);
3931 editor.select();
3932 }
3933 this.#dispatchUpdateStates({
3934 hasSelectedEditor: true
3935 });
3936 }
3937 selectAll() {
3938 for (const editor of this.#selectedEditors) {
3939 editor.commit();
3940 }
3941 this.#selectEditors(this.#allEditors.values());
3942 }
3943 unselectAll() {
3944 if (this.#activeEditor) {
3945 this.#activeEditor.commitOrRemove();
3946 return;
3947 }
3948 if (this.#selectedEditors.size === 0) {
3949 return;
3950 }
3951 for (const editor of this.#selectedEditors) {
3952 editor.unselect();
3953 }
3954 this.#selectedEditors.clear();
3955 this.#dispatchUpdateStates({
3956 hasSelectedEditor: false
3957 });
3958 }
3959 isActive(editor) {
3960 return this.#activeEditor === editor;
3961 }
3962 getActive() {
3963 return this.#activeEditor;
3964 }
3965 getMode() {
3966 return this.#mode;
3967 }
3968}
3969exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
3970
3971/***/ }),
3972/* 6 */
3973/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3974
3975
3976
3977Object.defineProperty(exports, "__esModule", ({
3978 value: true
3979}));
3980exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
3981exports.deprecated = deprecated;
3982exports.getColorValues = getColorValues;
3983exports.getCurrentTransform = getCurrentTransform;
3984exports.getCurrentTransformInverse = getCurrentTransformInverse;
3985exports.getFilenameFromUrl = getFilenameFromUrl;
3986exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
3987exports.getRGB = getRGB;
3988exports.getXfaPageViewport = getXfaPageViewport;
3989exports.isDataScheme = isDataScheme;
3990exports.isPdfFile = isPdfFile;
3991exports.isValidFetchUrl = isValidFetchUrl;
3992exports.loadScript = loadScript;
3993exports.setLayerDimensions = setLayerDimensions;
3994var _base_factory = __w_pdfjs_require__(7);
3995var _util = __w_pdfjs_require__(1);
3996const SVG_NS = "http://www.w3.org/2000/svg";
3997const AnnotationPrefix = "pdfjs_internal_id_";
3998exports.AnnotationPrefix = AnnotationPrefix;
3999class PixelsPerInch {
4000 static CSS = 96.0;
4001 static PDF = 72.0;
4002 static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
4003}
4004exports.PixelsPerInch = PixelsPerInch;
4005class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
4006 constructor({
4007 ownerDocument = globalThis.document
4008 } = {}) {
4009 super();
4010 this._document = ownerDocument;
4011 }
4012 _createCanvas(width, height) {
4013 const canvas = this._document.createElement("canvas");
4014 canvas.width = width;
4015 canvas.height = height;
4016 return canvas;
4017 }
4018}
4019exports.DOMCanvasFactory = DOMCanvasFactory;
4020async function fetchData(url, asTypedArray = false) {
4021 if (isValidFetchUrl(url, document.baseURI)) {
4022 const response = await fetch(url);
4023 if (!response.ok) {
4024 throw new Error(response.statusText);
4025 }
4026 return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
4027 }
4028 return new Promise((resolve, reject) => {
4029 const request = new XMLHttpRequest();
4030 request.open("GET", url, true);
4031 if (asTypedArray) {
4032 request.responseType = "arraybuffer";
4033 }
4034 request.onreadystatechange = () => {
4035 if (request.readyState !== XMLHttpRequest.DONE) {
4036 return;
4037 }
4038 if (request.status === 200 || request.status === 0) {
4039 let data;
4040 if (asTypedArray && request.response) {
4041 data = new Uint8Array(request.response);
4042 } else if (!asTypedArray && request.responseText) {
4043 data = (0, _util.stringToBytes)(request.responseText);
4044 }
4045 if (data) {
4046 resolve(data);
4047 return;
4048 }
4049 }
4050 reject(new Error(request.statusText));
4051 };
4052 request.send(null);
4053 });
4054}
4055class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
4056 _fetchData(url, compressionType) {
4057 return fetchData(url, this.isCompressed).then(data => {
4058 return {
4059 cMapData: data,
4060 compressionType
4061 };
4062 });
4063 }
4064}
4065exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
4066class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
4067 _fetchData(url) {
4068 return fetchData(url, true);
4069 }
4070}
4071exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
4072class DOMSVGFactory extends _base_factory.BaseSVGFactory {
4073 _createSVG(type) {
4074 return document.createElementNS(SVG_NS, type);
4075 }
4076}
4077exports.DOMSVGFactory = DOMSVGFactory;
4078class PageViewport {
4079 constructor({
4080 viewBox,
4081 scale,
4082 rotation,
4083 offsetX = 0,
4084 offsetY = 0,
4085 dontFlip = false
4086 }) {
4087 this.viewBox = viewBox;
4088 this.scale = scale;
4089 this.rotation = rotation;
4090 this.offsetX = offsetX;
4091 this.offsetY = offsetY;
4092 const centerX = (viewBox[2] + viewBox[0]) / 2;
4093 const centerY = (viewBox[3] + viewBox[1]) / 2;
4094 let rotateA, rotateB, rotateC, rotateD;
4095 rotation %= 360;
4096 if (rotation < 0) {
4097 rotation += 360;
4098 }
4099 switch (rotation) {
4100 case 180:
4101 rotateA = -1;
4102 rotateB = 0;
4103 rotateC = 0;
4104 rotateD = 1;
4105 break;
4106 case 90:
4107 rotateA = 0;
4108 rotateB = 1;
4109 rotateC = 1;
4110 rotateD = 0;
4111 break;
4112 case 270:
4113 rotateA = 0;
4114 rotateB = -1;
4115 rotateC = -1;
4116 rotateD = 0;
4117 break;
4118 case 0:
4119 rotateA = 1;
4120 rotateB = 0;
4121 rotateC = 0;
4122 rotateD = -1;
4123 break;
4124 default:
4125 throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
4126 }
4127 if (dontFlip) {
4128 rotateC = -rotateC;
4129 rotateD = -rotateD;
4130 }
4131 let offsetCanvasX, offsetCanvasY;
4132 let width, height;
4133 if (rotateA === 0) {
4134 offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
4135 offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
4136 width = (viewBox[3] - viewBox[1]) * scale;
4137 height = (viewBox[2] - viewBox[0]) * scale;
4138 } else {
4139 offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
4140 offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
4141 width = (viewBox[2] - viewBox[0]) * scale;
4142 height = (viewBox[3] - viewBox[1]) * scale;
4143 }
4144 this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
4145 this.width = width;
4146 this.height = height;
4147 }
4148 get rawDims() {
4149 const {
4150 viewBox
4151 } = this;
4152 return (0, _util.shadow)(this, "rawDims", {
4153 pageWidth: viewBox[2] - viewBox[0],
4154 pageHeight: viewBox[3] - viewBox[1],
4155 pageX: viewBox[0],
4156 pageY: viewBox[1]
4157 });
4158 }
4159 clone({
4160 scale = this.scale,
4161 rotation = this.rotation,
4162 offsetX = this.offsetX,
4163 offsetY = this.offsetY,
4164 dontFlip = false
4165 } = {}) {
4166 return new PageViewport({
4167 viewBox: this.viewBox.slice(),
4168 scale,
4169 rotation,
4170 offsetX,
4171 offsetY,
4172 dontFlip
4173 });
4174 }
4175 convertToViewportPoint(x, y) {
4176 return _util.Util.applyTransform([x, y], this.transform);
4177 }
4178 convertToViewportRectangle(rect) {
4179 const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
4180 const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
4181 return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
4182 }
4183 convertToPdfPoint(x, y) {
4184 return _util.Util.applyInverseTransform([x, y], this.transform);
4185 }
4186}
4187exports.PageViewport = PageViewport;
4188class RenderingCancelledException extends _util.BaseException {
4189 constructor(msg, type, extraDelay = 0) {
4190 super(msg, "RenderingCancelledException");
4191 this.type = type;
4192 this.extraDelay = extraDelay;
4193 }
4194}
4195exports.RenderingCancelledException = RenderingCancelledException;
4196function isDataScheme(url) {
4197 const ii = url.length;
4198 let i = 0;
4199 while (i < ii && url[i].trim() === "") {
4200 i++;
4201 }
4202 return url.substring(i, i + 5).toLowerCase() === "data:";
4203}
4204function isPdfFile(filename) {
4205 return typeof filename === "string" && /\.pdf$/i.test(filename);
4206}
4207function getFilenameFromUrl(url, onlyStripPath = false) {
4208 if (!onlyStripPath) {
4209 [url] = url.split(/[#?]/, 1);
4210 }
4211 return url.substring(url.lastIndexOf("/") + 1);
4212}
4213function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
4214 if (window.PDFViewerApplication.appConfig.filenameForDownload) {
4215 return window.PDFViewerApplication.appConfig.filenameForDownload;
4216 }
4217 if (typeof url !== "string") {
4218 return defaultFilename;
4219 }
4220 if (isDataScheme(url)) {
4221 (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
4222 return defaultFilename;
4223 }
4224 const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
4225 const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
4226 const splitURI = reURI.exec(url);
4227 let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
4228 if (suggestedFilename) {
4229 suggestedFilename = suggestedFilename[0];
4230 if (suggestedFilename.includes("%")) {
4231 try {
4232 suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
4233 } catch (ex) {}
4234 }
4235 }
4236 return suggestedFilename || defaultFilename;
4237}
4238class StatTimer {
4239 started = Object.create(null);
4240 times = [];
4241 time(name) {
4242 if (name in this.started) {
4243 (0, _util.warn)(`Timer is already running for ${name}`);
4244 }
4245 this.started[name] = Date.now();
4246 }
4247 timeEnd(name) {
4248 if (!(name in this.started)) {
4249 (0, _util.warn)(`Timer has not been started for ${name}`);
4250 }
4251 this.times.push({
4252 name,
4253 start: this.started[name],
4254 end: Date.now()
4255 });
4256 delete this.started[name];
4257 }
4258 toString() {
4259 const outBuf = [];
4260 let longest = 0;
4261 for (const {
4262 name
4263 } of this.times) {
4264 longest = Math.max(name.length, longest);
4265 }
4266 for (const {
4267 name,
4268 start,
4269 end
4270 } of this.times) {
4271 outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
4272 }
4273 return outBuf.join("");
4274 }
4275}
4276exports.StatTimer = StatTimer;
4277function isValidFetchUrl(url, baseUrl) {
4278 try {
4279 const {
4280 protocol
4281 } = baseUrl ? new URL(url, baseUrl) : new URL(url);
4282 return protocol === "http:" || protocol === "https:" || protocol === "capacitor:";
4283 } catch (ex) {
4284 return false;
4285 }
4286}
4287function generateTrustedURL(sourcePath) {
4288 if (window.trustedTypes) {
4289 const sanitizer = window.trustedTypes.createPolicy("foo", {
4290 createScriptURL: url => url
4291 });
4292 return sanitizer.createScriptURL(sourcePath);
4293 }
4294 return sourcePath;
4295}
4296function loadScript(src, removeScriptElement = false) {
4297 return new Promise((resolve, reject) => {
4298 const script = document.createElement("script");
4299 let source = src;
4300 if (src.constructor.name === "Function") {
4301 source = src();
4302 }
4303 const secureSource = generateTrustedURL(source);
4304 script.src = secureSource;
4305 script.onload = function (evt) {
4306 if (removeScriptElement) {
4307 script.remove();
4308 }
4309 resolve(evt);
4310 };
4311 script.onerror = function (error) {
4312 Window['ngxConsole'].log(error);
4313 reject(new Error(`Cannot load script at: ${script.src}`));
4314 };
4315 (document.head || document.documentElement).append(script);
4316 });
4317}
4318function deprecated(details) {
4319 Window['ngxConsole'].log("Deprecated API usage: " + details);
4320}
4321let pdfDateStringRegex;
4322class PDFDateString {
4323 static toDateObject(input) {
4324 if (!input || typeof input !== "string") {
4325 return null;
4326 }
4327 if (!pdfDateStringRegex) {
4328 pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
4329 }
4330 const matches = pdfDateStringRegex.exec(input);
4331 if (!matches) {
4332 return null;
4333 }
4334 const year = parseInt(matches[1], 10);
4335 let month = parseInt(matches[2], 10);
4336 month = month >= 1 && month <= 12 ? month - 1 : 0;
4337 let day = parseInt(matches[3], 10);
4338 day = day >= 1 && day <= 31 ? day : 1;
4339 let hour = parseInt(matches[4], 10);
4340 hour = hour >= 0 && hour <= 23 ? hour : 0;
4341 let minute = parseInt(matches[5], 10);
4342 minute = minute >= 0 && minute <= 59 ? minute : 0;
4343 let second = parseInt(matches[6], 10);
4344 second = second >= 0 && second <= 59 ? second : 0;
4345 const universalTimeRelation = matches[7] || "Z";
4346 let offsetHour = parseInt(matches[8], 10);
4347 offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
4348 let offsetMinute = parseInt(matches[9], 10) || 0;
4349 offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
4350 if (universalTimeRelation === "-") {
4351 hour += offsetHour;
4352 minute += offsetMinute;
4353 } else if (universalTimeRelation === "+") {
4354 hour -= offsetHour;
4355 minute -= offsetMinute;
4356 }
4357 return new Date(Date.UTC(year, month, day, hour, minute, second));
4358 }
4359}
4360exports.PDFDateString = PDFDateString;
4361function getXfaPageViewport(xfaPage, {
4362 scale = 1,
4363 rotation = 0
4364}) {
4365 const {
4366 width,
4367 height
4368 } = xfaPage.attributes.style;
4369 const viewBox = [0, 0, parseInt(width), parseInt(height)];
4370 return new PageViewport({
4371 viewBox,
4372 scale,
4373 rotation
4374 });
4375}
4376function getRGB(color) {
4377 if (color.startsWith("#")) {
4378 const colorRGB = parseInt(color.slice(1), 16);
4379 return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
4380 }
4381 if (color.startsWith("rgb(")) {
4382 return color.slice(4, -1).split(",").map(x => parseInt(x));
4383 }
4384 if (color.startsWith("rgba(")) {
4385 return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
4386 }
4387 (0, _util.warn)(`Not a valid color format: "${color}"`);
4388 return [0, 0, 0];
4389}
4390function getColorValues(colors) {
4391 const span = document.createElement("span");
4392 span.style.visibility = "hidden";
4393 document.body.append(span);
4394 for (const name of colors.keys()) {
4395 span.style.color = name;
4396 const computedColor = window.getComputedStyle(span).color;
4397 colors.set(name, getRGB(computedColor));
4398 }
4399 span.remove();
4400}
4401function getCurrentTransform(ctx) {
4402 const {
4403 a,
4404 b,
4405 c,
4406 d,
4407 e,
4408 f
4409 } = ctx.getTransform();
4410 return [a, b, c, d, e, f];
4411}
4412function getCurrentTransformInverse(ctx) {
4413 const {
4414 a,
4415 b,
4416 c,
4417 d,
4418 e,
4419 f
4420 } = ctx.getTransform().invertSelf();
4421 return [a, b, c, d, e, f];
4422}
4423function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
4424 if (viewport instanceof PageViewport) {
4425 const {
4426 pageWidth,
4427 pageHeight
4428 } = viewport.rawDims;
4429 const {
4430 style
4431 } = div;
4432 const widthStr = `calc(var(--scale-factor) * ${pageWidth}px)`;
4433 const heightStr = `calc(var(--scale-factor) * ${pageHeight}px)`;
4434 if (!mustFlip || viewport.rotation % 180 === 0) {
4435 style.width = widthStr;
4436 style.height = heightStr;
4437 } else {
4438 style.width = heightStr;
4439 style.height = widthStr;
4440 }
4441 }
4442 if (mustRotate) {
4443 div.setAttribute("data-main-rotation", viewport.rotation);
4444 }
4445}
4446
4447/***/ }),
4448/* 7 */
4449/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4450
4451
4452
4453Object.defineProperty(exports, "__esModule", ({
4454 value: true
4455}));
4456exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
4457var _util = __w_pdfjs_require__(1);
4458class BaseCanvasFactory {
4459 constructor() {
4460 if (this.constructor === BaseCanvasFactory) {
4461 (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
4462 }
4463 }
4464 create(width, height) {
4465 if (width <= 0 || height <= 0) {
4466 throw new Error("Invalid canvas size");
4467 }
4468 const canvas = this._createCanvas(width, height);
4469 const options = window.pdfDefaultOptions.activateWillReadFrequentlyFlag ? {
4470 willReadFrequently: true
4471 } : undefined;
4472 const context = canvas.getContext("2d", options);
4473 return {
4474 canvas,
4475 context
4476 };
4477 }
4478 reset(canvasAndContext, width, height) {
4479 if (!canvasAndContext.canvas) {
4480 throw new Error("Canvas is not specified");
4481 }
4482 if (width <= 0 || height <= 0) {
4483 throw new Error("Invalid canvas size");
4484 }
4485 canvasAndContext.canvas.width = width;
4486 canvasAndContext.canvas.height = height;
4487 }
4488 destroy(canvasAndContext) {
4489 if (!canvasAndContext.canvas) {
4490 throw new Error("Canvas is not specified");
4491 }
4492 canvasAndContext.canvas.width = 0;
4493 canvasAndContext.canvas.height = 0;
4494 canvasAndContext.canvas = null;
4495 canvasAndContext.context = null;
4496 }
4497 _createCanvas(width, height) {
4498 (0, _util.unreachable)("Abstract method `_createCanvas` called.");
4499 }
4500}
4501exports.BaseCanvasFactory = BaseCanvasFactory;
4502class BaseCMapReaderFactory {
4503 constructor({
4504 baseUrl = null,
4505 isCompressed = true
4506 }) {
4507 if (this.constructor === BaseCMapReaderFactory) {
4508 (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
4509 }
4510 this.baseUrl = baseUrl;
4511 this.isCompressed = isCompressed;
4512 }
4513 async fetch({
4514 name
4515 }) {
4516 if (!this.baseUrl) {
4517 throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
4518 }
4519 if (!name) {
4520 throw new Error("CMap name must be specified.");
4521 }
4522 const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
4523 const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
4524 return this._fetchData(url, compressionType).catch(reason => {
4525 throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
4526 });
4527 }
4528 _fetchData(url, compressionType) {
4529 (0, _util.unreachable)("Abstract method `_fetchData` called.");
4530 }
4531}
4532exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
4533class BaseStandardFontDataFactory {
4534 constructor({
4535 baseUrl = null
4536 }) {
4537 if (this.constructor === BaseStandardFontDataFactory) {
4538 (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
4539 }
4540 this.baseUrl = baseUrl;
4541 }
4542 async fetch({
4543 filename
4544 }) {
4545 if (!this.baseUrl) {
4546 throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
4547 }
4548 if (!filename) {
4549 throw new Error("Font filename must be specified.");
4550 }
4551 const url = `${this.baseUrl}${filename}`;
4552 return this._fetchData(url).catch(reason => {
4553 throw new Error(`Unable to load font data at: ${url}`);
4554 });
4555 }
4556 _fetchData(url) {
4557 (0, _util.unreachable)("Abstract method `_fetchData` called.");
4558 }
4559}
4560exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
4561class BaseSVGFactory {
4562 constructor() {
4563 if (this.constructor === BaseSVGFactory) {
4564 (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
4565 }
4566 }
4567 create(width, height, skipDimensions = false) {
4568 if (width <= 0 || height <= 0) {
4569 throw new Error("Invalid SVG dimensions");
4570 }
4571 const svg = this._createSVG("svg:svg");
4572 svg.setAttribute("version", "1.1");
4573 if (!skipDimensions) {
4574 svg.setAttribute("width", `${width}px`);
4575 svg.setAttribute("height", `${height}px`);
4576 }
4577 svg.setAttribute("preserveAspectRatio", "none");
4578 svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
4579 return svg;
4580 }
4581 createElement(type) {
4582 if (typeof type !== "string") {
4583 throw new Error("Invalid SVG element type");
4584 }
4585 return this._createSVG(type);
4586 }
4587 _createSVG(type) {
4588 (0, _util.unreachable)("Abstract method `_createSVG` called.");
4589 }
4590}
4591exports.BaseSVGFactory = BaseSVGFactory;
4592
4593/***/ }),
4594/* 8 */
4595/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4596
4597
4598
4599Object.defineProperty(exports, "__esModule", ({
4600 value: true
4601}));
4602exports.MurmurHash3_64 = void 0;
4603var _util = __w_pdfjs_require__(1);
4604const SEED = 0xc3d2e1f0;
4605const MASK_HIGH = 0xffff0000;
4606const MASK_LOW = 0xffff;
4607class MurmurHash3_64 {
4608 constructor(seed) {
4609 this.h1 = seed ? seed & 0xffffffff : SEED;
4610 this.h2 = seed ? seed & 0xffffffff : SEED;
4611 }
4612 update(input) {
4613 let data, length;
4614 if (typeof input === "string") {
4615 data = new Uint8Array(input.length * 2);
4616 length = 0;
4617 for (let i = 0, ii = input.length; i < ii; i++) {
4618 const code = input.charCodeAt(i);
4619 if (code <= 0xff) {
4620 data[length++] = code;
4621 } else {
4622 data[length++] = code >>> 8;
4623 data[length++] = code & 0xff;
4624 }
4625 }
4626 } else if ((0, _util.isArrayBuffer)(input)) {
4627 data = input.slice();
4628 length = data.byteLength;
4629 } else {
4630 throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
4631 }
4632 const blockCounts = length >> 2;
4633 const tailLength = length - blockCounts * 4;
4634 const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
4635 let k1 = 0,
4636 k2 = 0;
4637 let h1 = this.h1,
4638 h2 = this.h2;
4639 const C1 = 0xcc9e2d51,
4640 C2 = 0x1b873593;
4641 const C1_LOW = C1 & MASK_LOW,
4642 C2_LOW = C2 & MASK_LOW;
4643 for (let i = 0; i < blockCounts; i++) {
4644 if (i & 1) {
4645 k1 = dataUint32[i];
4646 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
4647 k1 = k1 << 15 | k1 >>> 17;
4648 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
4649 h1 ^= k1;
4650 h1 = h1 << 13 | h1 >>> 19;
4651 h1 = h1 * 5 + 0xe6546b64;
4652 } else {
4653 k2 = dataUint32[i];
4654 k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
4655 k2 = k2 << 15 | k2 >>> 17;
4656 k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
4657 h2 ^= k2;
4658 h2 = h2 << 13 | h2 >>> 19;
4659 h2 = h2 * 5 + 0xe6546b64;
4660 }
4661 }
4662 k1 = 0;
4663 switch (tailLength) {
4664 case 3:
4665 k1 ^= data[blockCounts * 4 + 2] << 16;
4666 case 2:
4667 k1 ^= data[blockCounts * 4 + 1] << 8;
4668 case 1:
4669 k1 ^= data[blockCounts * 4];
4670 k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
4671 k1 = k1 << 15 | k1 >>> 17;
4672 k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
4673 if (blockCounts & 1) {
4674 h1 ^= k1;
4675 } else {
4676 h2 ^= k1;
4677 }
4678 }
4679 this.h1 = h1;
4680 this.h2 = h2;
4681 }
4682 hexdigest() {
4683 let h1 = this.h1,
4684 h2 = this.h2;
4685 h1 ^= h2 >>> 1;
4686 h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
4687 h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
4688 h1 ^= h2 >>> 1;
4689 h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
4690 h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
4691 h1 ^= h2 >>> 1;
4692 return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
4693 }
4694}
4695exports.MurmurHash3_64 = MurmurHash3_64;
4696
4697/***/ }),
4698/* 9 */
4699/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4700
4701
4702
4703Object.defineProperty(exports, "__esModule", ({
4704 value: true
4705}));
4706exports.FontLoader = exports.FontFaceObject = void 0;
4707var _util = __w_pdfjs_require__(1);
4708var _is_node = __w_pdfjs_require__(10);
4709class FontLoader {
4710 constructor({
4711 onUnsupportedFeature,
4712 ownerDocument = globalThis.document,
4713 styleElement = null
4714 }) {
4715 this._onUnsupportedFeature = onUnsupportedFeature;
4716 this._document = ownerDocument;
4717 this.nativeFontFaces = [];
4718 this.styleElement = null;
4719 this.loadingRequests = [];
4720 this.loadTestFontId = 0;
4721 }
4722 addNativeFontFace(nativeFontFace) {
4723 this.nativeFontFaces.push(nativeFontFace);
4724 this._document.fonts.add(nativeFontFace);
4725 }
4726 insertRule(rule) {
4727 if (!this.styleElement) {
4728 this.styleElement = this._document.createElement("style");
4729 this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
4730 }
4731 const styleSheet = this.styleElement.sheet;
4732 styleSheet.insertRule(rule, styleSheet.cssRules.length);
4733 }
4734 clear() {
4735 for (const nativeFontFace of this.nativeFontFaces) {
4736 this._document.fonts.delete(nativeFontFace);
4737 }
4738 this.nativeFontFaces.length = 0;
4739 if (this.styleElement) {
4740 this.styleElement.remove();
4741 this.styleElement = null;
4742 }
4743 }
4744 async bind(font) {
4745 if (font.attached || font.missingFile) {
4746 return;
4747 }
4748 font.attached = true;
4749 if (this.isFontLoadingAPISupported) {
4750 const nativeFontFace = font.createNativeFontFace();
4751 if (nativeFontFace) {
4752 this.addNativeFontFace(nativeFontFace);
4753 try {
4754 await nativeFontFace.loaded;
4755 } catch (ex) {
4756 this._onUnsupportedFeature({
4757 featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
4758 });
4759 (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
4760 font.disableFontFace = true;
4761 throw ex;
4762 }
4763 }
4764 return;
4765 }
4766 const rule = font.createFontFaceRule();
4767 if (rule) {
4768 this.insertRule(rule);
4769 if (this.isSyncFontLoadingSupported) {
4770 return;
4771 }
4772 await new Promise(resolve => {
4773 const request = this._queueLoadingCallback(resolve);
4774 this._prepareFontLoadEvent(font, request);
4775 });
4776 }
4777 }
4778 get isFontLoadingAPISupported() {
4779 const hasFonts = !!this._document?.fonts;
4780 return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
4781 }
4782 get isSyncFontLoadingSupported() {
4783 let supported = false;
4784 if (_is_node.isNodeJS) {
4785 supported = true;
4786 } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
4787 supported = true;
4788 }
4789 return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
4790 }
4791 _queueLoadingCallback(callback) {
4792 function completeRequest() {
4793 (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
4794 request.done = true;
4795 while (loadingRequests.length > 0 && loadingRequests[0].done) {
4796 const otherRequest = loadingRequests.shift();
4797 setTimeout(otherRequest.callback, 0);
4798 }
4799 }
4800 const {
4801 loadingRequests
4802 } = this;
4803 const request = {
4804 done: false,
4805 complete: completeRequest,
4806 callback
4807 };
4808 loadingRequests.push(request);
4809 return request;
4810 }
4811 get _loadTestFont() {
4812 const testFont = 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==");
4813 return (0, _util.shadow)(this, "_loadTestFont", testFont);
4814 }
4815 _prepareFontLoadEvent(font, request) {
4816 function int32(data, offset) {
4817 return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
4818 }
4819 function spliceString(s, offset, remove, insert) {
4820 const chunk1 = s.substring(0, offset);
4821 const chunk2 = s.substring(offset + remove);
4822 return chunk1 + insert + chunk2;
4823 }
4824 let i, ii;
4825 const canvas = this._document.createElement("canvas");
4826 canvas.width = 1;
4827 canvas.height = 1;
4828 const options = window.pdfDefaultOptions.activateWillReadFrequentlyFlag ? {
4829 willReadFrequently: true
4830 } : undefined;
4831 const ctx = canvas.getContext("2d", options);
4832 let called = 0;
4833 function isFontReady(name, callback) {
4834 if (++called > 30) {
4835 (0, _util.warn)("Load test font never loaded.");
4836 callback();
4837 return;
4838 }
4839 ctx.font = "30px " + name;
4840 ctx.fillText(".", 0, 20);
4841 const imageData = ctx.getImageData(0, 0, 1, 1);
4842 if (imageData.data[3] > 0) {
4843 callback();
4844 return;
4845 }
4846 setTimeout(isFontReady.bind(null, name, callback));
4847 }
4848 const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
4849 let data = this._loadTestFont;
4850 const COMMENT_OFFSET = 976;
4851 data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
4852 const CFF_CHECKSUM_OFFSET = 16;
4853 const XXXX_VALUE = 0x58585858;
4854 let checksum = int32(data, CFF_CHECKSUM_OFFSET);
4855 for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
4856 checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
4857 }
4858 if (i < loadTestFontId.length) {
4859 checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
4860 }
4861 data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
4862 const url = `url(data:font/opentype;base64,${btoa(data)});`;
4863 const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
4864 this.insertRule(rule);
4865 const div = this._document.createElement("div");
4866 div.style.visibility = "hidden";
4867 div.style.width = div.style.height = "10px";
4868 div.style.position = "absolute";
4869 div.style.top = div.style.left = "0px";
4870 for (const name of [font.loadedName, loadTestFontId]) {
4871 const span = this._document.createElement("span");
4872 span.textContent = "Hi";
4873 span.style.fontFamily = name;
4874 div.append(span);
4875 }
4876 this._document.body.append(div);
4877 isFontReady(loadTestFontId, () => {
4878 div.remove();
4879 request.complete();
4880 });
4881 }
4882}
4883exports.FontLoader = FontLoader;
4884class FontFaceObject {
4885 constructor(translatedData, {
4886 isEvalSupported = true,
4887 disableFontFace = false,
4888 ignoreErrors = false,
4889 onUnsupportedFeature,
4890 fontRegistry = null
4891 }) {
4892 this.compiledGlyphs = Object.create(null);
4893 for (const i in translatedData) {
4894 this[i] = translatedData[i];
4895 }
4896 this.isEvalSupported = isEvalSupported !== false;
4897 this.disableFontFace = disableFontFace === true;
4898 this.ignoreErrors = ignoreErrors === true;
4899 this._onUnsupportedFeature = onUnsupportedFeature;
4900 this.fontRegistry = fontRegistry;
4901 }
4902 createNativeFontFace() {
4903 if (!this.data || this.disableFontFace) {
4904 return null;
4905 }
4906 let nativeFontFace;
4907 if (!this.cssFontInfo) {
4908 nativeFontFace = new FontFace(this.loadedName, this.data, {});
4909 } else {
4910 const css = {
4911 weight: this.cssFontInfo.fontWeight
4912 };
4913 if (this.cssFontInfo.italicAngle) {
4914 css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
4915 }
4916 nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
4917 }
4918 this.fontRegistry?.registerFont(this);
4919 return nativeFontFace;
4920 }
4921 createFontFaceRule() {
4922 if (!this.data || this.disableFontFace) {
4923 return null;
4924 }
4925 const data = (0, _util.bytesToString)(this.data);
4926 const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
4927 let rule;
4928 if (!this.cssFontInfo) {
4929 rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
4930 } else {
4931 let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
4932 if (this.cssFontInfo.italicAngle) {
4933 css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
4934 }
4935 rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
4936 }
4937 this.fontRegistry?.registerFont(this, url);
4938 return rule;
4939 }
4940 getPathGenerator(objs, character) {
4941 if (this.compiledGlyphs[character] !== undefined) {
4942 return this.compiledGlyphs[character];
4943 }
4944 let cmds;
4945 try {
4946 cmds = objs.get(this.loadedName + "_path_" + character);
4947 } catch (ex) {
4948 if (!this.ignoreErrors) {
4949 throw ex;
4950 }
4951 this._onUnsupportedFeature({
4952 featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
4953 });
4954 (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
4955 return this.compiledGlyphs[character] = function (c, size) {};
4956 }
4957 if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
4958 const jsBuf = [];
4959 for (const current of cmds) {
4960 const args = current.args !== undefined ? current.args.join(",") : "";
4961 jsBuf.push("c.", current.cmd, "(", args, ");\n");
4962 }
4963 return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
4964 }
4965 return this.compiledGlyphs[character] = function (c, size) {
4966 for (const current of cmds) {
4967 if (current.cmd === "scale") {
4968 current.args = [size, -size];
4969 }
4970 c[current.cmd].apply(c, current.args);
4971 }
4972 };
4973 }
4974}
4975exports.FontFaceObject = FontFaceObject;
4976
4977/***/ }),
4978/* 10 */
4979/***/ ((__unused_webpack_module, exports) => {
4980
4981
4982
4983Object.defineProperty(exports, "__esModule", ({
4984 value: true
4985}));
4986exports.isNodeJS = void 0;
4987const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
4988exports.isNodeJS = isNodeJS;
4989
4990/***/ }),
4991/* 11 */
4992/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4993
4994
4995
4996Object.defineProperty(exports, "__esModule", ({
4997 value: true
4998}));
4999exports.CanvasGraphics = void 0;
5000var _util = __w_pdfjs_require__(1);
5001var _display_utils = __w_pdfjs_require__(6);
5002var _pattern_helper = __w_pdfjs_require__(12);
5003var _image_utils = __w_pdfjs_require__(13);
5004const MIN_FONT_SIZE = 16;
5005const MAX_FONT_SIZE = 100;
5006const MAX_GROUP_SIZE = 4096;
5007const EXECUTION_TIME = 15;
5008const EXECUTION_STEPS = 10;
5009const MAX_SIZE_TO_COMPILE = 1000;
5010const FULL_CHUNK_HEIGHT = 16;
5011function mirrorContextOperations(ctx, destCtx) {
5012 if (ctx._removeMirroring) {
5013 throw new Error("Context is already forwarding operations.");
5014 }
5015 ctx.__originalSave = ctx.save;
5016 ctx.__originalRestore = ctx.restore;
5017 ctx.__originalRotate = ctx.rotate;
5018 ctx.__originalScale = ctx.scale;
5019 ctx.__originalTranslate = ctx.translate;
5020 ctx.__originalTransform = ctx.transform;
5021 ctx.__originalSetTransform = ctx.setTransform;
5022 ctx.__originalResetTransform = ctx.resetTransform;
5023 ctx.__originalClip = ctx.clip;
5024 ctx.__originalMoveTo = ctx.moveTo;
5025 ctx.__originalLineTo = ctx.lineTo;
5026 ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
5027 ctx.__originalRect = ctx.rect;
5028 ctx.__originalClosePath = ctx.closePath;
5029 ctx.__originalBeginPath = ctx.beginPath;
5030 ctx._removeMirroring = () => {
5031 ctx.save = ctx.__originalSave;
5032 ctx.restore = ctx.__originalRestore;
5033 ctx.rotate = ctx.__originalRotate;
5034 ctx.scale = ctx.__originalScale;
5035 ctx.translate = ctx.__originalTranslate;
5036 ctx.transform = ctx.__originalTransform;
5037 ctx.setTransform = ctx.__originalSetTransform;
5038 ctx.resetTransform = ctx.__originalResetTransform;
5039 ctx.clip = ctx.__originalClip;
5040 ctx.moveTo = ctx.__originalMoveTo;
5041 ctx.lineTo = ctx.__originalLineTo;
5042 ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
5043 ctx.rect = ctx.__originalRect;
5044 ctx.closePath = ctx.__originalClosePath;
5045 ctx.beginPath = ctx.__originalBeginPath;
5046 delete ctx._removeMirroring;
5047 };
5048 ctx.save = function ctxSave() {
5049 destCtx.save();
5050 this.__originalSave();
5051 };
5052 ctx.restore = function ctxRestore() {
5053 destCtx.restore();
5054 this.__originalRestore();
5055 };
5056 ctx.translate = function ctxTranslate(x, y) {
5057 destCtx.translate(x, y);
5058 this.__originalTranslate(x, y);
5059 };
5060 ctx.scale = function ctxScale(x, y) {
5061 destCtx.scale(x, y);
5062 this.__originalScale(x, y);
5063 };
5064 ctx.transform = function ctxTransform(a, b, c, d, e, f) {
5065 destCtx.transform(a, b, c, d, e, f);
5066 this.__originalTransform(a, b, c, d, e, f);
5067 };
5068 ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
5069 destCtx.setTransform(a, b, c, d, e, f);
5070 this.__originalSetTransform(a, b, c, d, e, f);
5071 };
5072 ctx.resetTransform = function ctxResetTransform() {
5073 destCtx.resetTransform();
5074 this.__originalResetTransform();
5075 };
5076 ctx.rotate = function ctxRotate(angle) {
5077 destCtx.rotate(angle);
5078 this.__originalRotate(angle);
5079 };
5080 ctx.clip = function ctxRotate(rule) {
5081 destCtx.clip(rule);
5082 this.__originalClip(rule);
5083 };
5084 ctx.moveTo = function (x, y) {
5085 destCtx.moveTo(x, y);
5086 this.__originalMoveTo(x, y);
5087 };
5088 ctx.lineTo = function (x, y) {
5089 destCtx.lineTo(x, y);
5090 this.__originalLineTo(x, y);
5091 };
5092 ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
5093 destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
5094 this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
5095 };
5096 ctx.rect = function (x, y, width, height) {
5097 destCtx.rect(x, y, width, height);
5098 this.__originalRect(x, y, width, height);
5099 };
5100 ctx.closePath = function () {
5101 destCtx.closePath();
5102 this.__originalClosePath();
5103 };
5104 ctx.beginPath = function () {
5105 destCtx.beginPath();
5106 this.__originalBeginPath();
5107 };
5108}
5109class CachedCanvases {
5110 constructor(canvasFactory) {
5111 this.canvasFactory = canvasFactory;
5112 this.cache = Object.create(null);
5113 }
5114 getCanvas(id, width, height) {
5115 let canvasEntry;
5116 if (this.cache[id] !== undefined) {
5117 canvasEntry = this.cache[id];
5118 this.canvasFactory.reset(canvasEntry, width, height);
5119 } else {
5120 canvasEntry = this.canvasFactory.create(width, height);
5121 this.cache[id] = canvasEntry;
5122 }
5123 return canvasEntry;
5124 }
5125 delete(id) {
5126 delete this.cache[id];
5127 }
5128 clear() {
5129 for (const id in this.cache) {
5130 const canvasEntry = this.cache[id];
5131 this.canvasFactory.destroy(canvasEntry);
5132 delete this.cache[id];
5133 }
5134 }
5135}
5136function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
5137 const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
5138 if (b === 0 && c === 0) {
5139 const tlX = destX * a + tx;
5140 const rTlX = Math.round(tlX);
5141 const tlY = destY * d + ty;
5142 const rTlY = Math.round(tlY);
5143 const brX = (destX + destW) * a + tx;
5144 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
5145 const brY = (destY + destH) * d + ty;
5146 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
5147 ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
5148 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
5149 ctx.setTransform(a, b, c, d, tx, ty);
5150 return [rWidth, rHeight];
5151 }
5152 if (a === 0 && d === 0) {
5153 const tlX = destY * c + tx;
5154 const rTlX = Math.round(tlX);
5155 const tlY = destX * b + ty;
5156 const rTlY = Math.round(tlY);
5157 const brX = (destY + destH) * c + tx;
5158 const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
5159 const brY = (destX + destW) * b + ty;
5160 const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
5161 ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
5162 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
5163 ctx.setTransform(a, b, c, d, tx, ty);
5164 return [rHeight, rWidth];
5165 }
5166 ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
5167 const scaleX = Math.hypot(a, b);
5168 const scaleY = Math.hypot(c, d);
5169 return [scaleX * destW, scaleY * destH];
5170}
5171function compileType3Glyph(imgData) {
5172 const {
5173 width,
5174 height
5175 } = imgData;
5176 if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
5177 return null;
5178 }
5179 const POINT_TO_PROCESS_LIMIT = 1000;
5180 const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
5181 const width1 = width + 1;
5182 let points = new Uint8Array(width1 * (height + 1));
5183 let i, j, j0;
5184 const lineSize = width + 7 & ~7;
5185 let data = new Uint8Array(lineSize * height),
5186 pos = 0;
5187 for (const elem of imgData.data) {
5188 let mask = 128;
5189 while (mask > 0) {
5190 data[pos++] = elem & mask ? 0 : 255;
5191 mask >>= 1;
5192 }
5193 }
5194 let count = 0;
5195 pos = 0;
5196 if (data[pos] !== 0) {
5197 points[0] = 1;
5198 ++count;
5199 }
5200 for (j = 1; j < width; j++) {
5201 if (data[pos] !== data[pos + 1]) {
5202 points[j] = data[pos] ? 2 : 1;
5203 ++count;
5204 }
5205 pos++;
5206 }
5207 if (data[pos] !== 0) {
5208 points[j] = 2;
5209 ++count;
5210 }
5211 for (i = 1; i < height; i++) {
5212 pos = i * lineSize;
5213 j0 = i * width1;
5214 if (data[pos - lineSize] !== data[pos]) {
5215 points[j0] = data[pos] ? 1 : 8;
5216 ++count;
5217 }
5218 let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
5219 for (j = 1; j < width; j++) {
5220 sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
5221 if (POINT_TYPES[sum]) {
5222 points[j0 + j] = POINT_TYPES[sum];
5223 ++count;
5224 }
5225 pos++;
5226 }
5227 if (data[pos - lineSize] !== data[pos]) {
5228 points[j0 + j] = data[pos] ? 2 : 4;
5229 ++count;
5230 }
5231 if (count > POINT_TO_PROCESS_LIMIT) {
5232 return null;
5233 }
5234 }
5235 pos = lineSize * (height - 1);
5236 j0 = i * width1;
5237 if (data[pos] !== 0) {
5238 points[j0] = 8;
5239 ++count;
5240 }
5241 for (j = 1; j < width; j++) {
5242 if (data[pos] !== data[pos + 1]) {
5243 points[j0 + j] = data[pos] ? 4 : 8;
5244 ++count;
5245 }
5246 pos++;
5247 }
5248 if (data[pos] !== 0) {
5249 points[j0 + j] = 4;
5250 ++count;
5251 }
5252 if (count > POINT_TO_PROCESS_LIMIT) {
5253 return null;
5254 }
5255 const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
5256 const path = new Path2D();
5257 for (i = 0; count && i <= height; i++) {
5258 let p = i * width1;
5259 const end = p + width;
5260 while (p < end && !points[p]) {
5261 p++;
5262 }
5263 if (p === end) {
5264 continue;
5265 }
5266 path.moveTo(p % width1, i);
5267 const p0 = p;
5268 let type = points[p];
5269 do {
5270 const step = steps[type];
5271 do {
5272 p += step;
5273 } while (!points[p]);
5274 const pp = points[p];
5275 if (pp !== 5 && pp !== 10) {
5276 type = pp;
5277 points[p] = 0;
5278 } else {
5279 type = pp & 0x33 * type >> 4;
5280 points[p] &= type >> 2 | type << 2;
5281 }
5282 path.lineTo(p % width1, p / width1 | 0);
5283 if (!points[p]) {
5284 --count;
5285 }
5286 } while (p0 !== p);
5287 --i;
5288 }
5289 data = null;
5290 points = null;
5291 const drawOutline = function (c) {
5292 c.save();
5293 c.scale(1 / width, -1 / height);
5294 c.translate(0, -height);
5295 c.fill(path);
5296 c.beginPath();
5297 c.restore();
5298 };
5299 return drawOutline;
5300}
5301class CanvasExtraState {
5302 constructor(width, height) {
5303 this.alphaIsShape = false;
5304 this.fontSize = 0;
5305 this.fontSizeScale = 1;
5306 this.textMatrix = _util.IDENTITY_MATRIX;
5307 this.textMatrixScale = 1;
5308 this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
5309 this.leading = 0;
5310 this.x = 0;
5311 this.y = 0;
5312 this.lineX = 0;
5313 this.lineY = 0;
5314 this.charSpacing = 0;
5315 this.wordSpacing = 0;
5316 this.textHScale = 1;
5317 this.textRenderingMode = _util.TextRenderingMode.FILL;
5318 this.textRise = 0;
5319 this.fillColor = "#000000";
5320 this.strokeColor = "#000000";
5321 this.patternFill = false;
5322 this.fillAlpha = 1;
5323 this.strokeAlpha = 1;
5324 this.lineWidth = 1;
5325 this.activeSMask = null;
5326 this.transferMaps = null;
5327 this.startNewPathAndClipBox([0, 0, width, height]);
5328 }
5329 clone() {
5330 const clone = Object.create(this);
5331 clone.clipBox = this.clipBox.slice();
5332 return clone;
5333 }
5334 setCurrentPoint(x, y) {
5335 this.x = x;
5336 this.y = y;
5337 }
5338 updatePathMinMax(transform, x, y) {
5339 [x, y] = _util.Util.applyTransform([x, y], transform);
5340 this.minX = Math.min(this.minX, x);
5341 this.minY = Math.min(this.minY, y);
5342 this.maxX = Math.max(this.maxX, x);
5343 this.maxY = Math.max(this.maxY, y);
5344 }
5345 updateRectMinMax(transform, rect) {
5346 const p1 = _util.Util.applyTransform(rect, transform);
5347 const p2 = _util.Util.applyTransform(rect.slice(2), transform);
5348 this.minX = Math.min(this.minX, p1[0], p2[0]);
5349 this.minY = Math.min(this.minY, p1[1], p2[1]);
5350 this.maxX = Math.max(this.maxX, p1[0], p2[0]);
5351 this.maxY = Math.max(this.maxY, p1[1], p2[1]);
5352 }
5353 updateScalingPathMinMax(transform, minMax) {
5354 _util.Util.scaleMinMax(transform, minMax);
5355 this.minX = Math.min(this.minX, minMax[0]);
5356 this.maxX = Math.max(this.maxX, minMax[1]);
5357 this.minY = Math.min(this.minY, minMax[2]);
5358 this.maxY = Math.max(this.maxY, minMax[3]);
5359 }
5360 updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
5361 const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
5362 if (minMax) {
5363 minMax[0] = Math.min(minMax[0], box[0], box[2]);
5364 minMax[1] = Math.max(minMax[1], box[0], box[2]);
5365 minMax[2] = Math.min(minMax[2], box[1], box[3]);
5366 minMax[3] = Math.max(minMax[3], box[1], box[3]);
5367 return;
5368 }
5369 this.updateRectMinMax(transform, box);
5370 }
5371 getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5372 const box = [this.minX, this.minY, this.maxX, this.maxY];
5373 if (pathType === _pattern_helper.PathType.STROKE) {
5374 if (!transform) {
5375 (0, _util.unreachable)("Stroke bounding box must include transform.");
5376 }
5377 const scale = _util.Util.singularValueDecompose2dScale(transform);
5378 const xStrokePad = scale[0] * this.lineWidth / 2;
5379 const yStrokePad = scale[1] * this.lineWidth / 2;
5380 box[0] -= xStrokePad;
5381 box[1] -= yStrokePad;
5382 box[2] += xStrokePad;
5383 box[3] += yStrokePad;
5384 }
5385 return box;
5386 }
5387 updateClipFromPath() {
5388 const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
5389 this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
5390 }
5391 isEmptyClip() {
5392 return this.minX === Infinity;
5393 }
5394 startNewPathAndClipBox(box) {
5395 this.clipBox = box;
5396 this.minX = Infinity;
5397 this.minY = Infinity;
5398 this.maxX = 0;
5399 this.maxY = 0;
5400 }
5401 getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5402 return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
5403 }
5404}
5405function putBinaryImageData(ctx, imgData, transferMaps = null) {
5406 if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
5407 ctx.putImageData(imgData, 0, 0);
5408 return;
5409 }
5410 const height = imgData.height,
5411 width = imgData.width;
5412 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5413 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5414 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5415 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5416 let srcPos = 0,
5417 destPos;
5418 const src = imgData.data;
5419 const dest = chunkImgData.data;
5420 let i, j, thisChunkHeight, elemsInThisChunk;
5421 let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
5422 if (transferMaps) {
5423 switch (transferMaps.length) {
5424 case 1:
5425 transferMapRed = transferMaps[0];
5426 transferMapGreen = transferMaps[0];
5427 transferMapBlue = transferMaps[0];
5428 transferMapGray = transferMaps[0];
5429 break;
5430 case 4:
5431 transferMapRed = transferMaps[0];
5432 transferMapGreen = transferMaps[1];
5433 transferMapBlue = transferMaps[2];
5434 transferMapGray = transferMaps[3];
5435 break;
5436 }
5437 }
5438 if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
5439 const srcLength = src.byteLength;
5440 const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
5441 const dest32DataLength = dest32.length;
5442 const fullSrcDiff = width + 7 >> 3;
5443 let white = 0xffffffff;
5444 let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
5445 if (transferMapGray) {
5446 if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
5447 [white, black] = [black, white];
5448 }
5449 }
5450 for (i = 0; i < totalChunks; i++) {
5451 thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5452 destPos = 0;
5453 for (j = 0; j < thisChunkHeight; j++) {
5454 const srcDiff = srcLength - srcPos;
5455 let k = 0;
5456 const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
5457 const kEndUnrolled = kEnd & ~7;
5458 let mask = 0;
5459 let srcByte = 0;
5460 for (; k < kEndUnrolled; k += 8) {
5461 srcByte = src[srcPos++];
5462 dest32[destPos++] = srcByte & 128 ? white : black;
5463 dest32[destPos++] = srcByte & 64 ? white : black;
5464 dest32[destPos++] = srcByte & 32 ? white : black;
5465 dest32[destPos++] = srcByte & 16 ? white : black;
5466 dest32[destPos++] = srcByte & 8 ? white : black;
5467 dest32[destPos++] = srcByte & 4 ? white : black;
5468 dest32[destPos++] = srcByte & 2 ? white : black;
5469 dest32[destPos++] = srcByte & 1 ? white : black;
5470 }
5471 for (; k < kEnd; k++) {
5472 if (mask === 0) {
5473 srcByte = src[srcPos++];
5474 mask = 128;
5475 }
5476 dest32[destPos++] = srcByte & mask ? white : black;
5477 mask >>= 1;
5478 }
5479 }
5480 while (destPos < dest32DataLength) {
5481 dest32[destPos++] = 0;
5482 }
5483 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5484 }
5485 } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
5486 const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5487 j = 0;
5488 elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
5489 for (i = 0; i < fullChunks; i++) {
5490 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5491 srcPos += elemsInThisChunk;
5492 if (hasTransferMaps) {
5493 for (let k = 0; k < elemsInThisChunk; k += 4) {
5494 if (transferMapRed) {
5495 dest[k + 0] = transferMapRed[dest[k + 0]];
5496 }
5497 if (transferMapGreen) {
5498 dest[k + 1] = transferMapGreen[dest[k + 1]];
5499 }
5500 if (transferMapBlue) {
5501 dest[k + 2] = transferMapBlue[dest[k + 2]];
5502 }
5503 }
5504 }
5505 ctx.putImageData(chunkImgData, 0, j);
5506 j += FULL_CHUNK_HEIGHT;
5507 }
5508 if (i < totalChunks) {
5509 elemsInThisChunk = width * partialChunkHeight * 4;
5510 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5511 if (hasTransferMaps) {
5512 for (let k = 0; k < elemsInThisChunk; k += 4) {
5513 if (transferMapRed) {
5514 dest[k + 0] = transferMapRed[dest[k + 0]];
5515 }
5516 if (transferMapGreen) {
5517 dest[k + 1] = transferMapGreen[dest[k + 1]];
5518 }
5519 if (transferMapBlue) {
5520 dest[k + 2] = transferMapBlue[dest[k + 2]];
5521 }
5522 }
5523 }
5524 ctx.putImageData(chunkImgData, 0, j);
5525 }
5526 } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
5527 const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5528 thisChunkHeight = FULL_CHUNK_HEIGHT;
5529 elemsInThisChunk = width * thisChunkHeight;
5530 for (i = 0; i < totalChunks; i++) {
5531 if (i >= fullChunks) {
5532 thisChunkHeight = partialChunkHeight;
5533 elemsInThisChunk = width * thisChunkHeight;
5534 }
5535 destPos = 0;
5536 for (j = elemsInThisChunk; j--;) {
5537 dest[destPos++] = src[srcPos++];
5538 dest[destPos++] = src[srcPos++];
5539 dest[destPos++] = src[srcPos++];
5540 dest[destPos++] = 255;
5541 }
5542 if (hasTransferMaps) {
5543 for (let k = 0; k < destPos; k += 4) {
5544 if (transferMapRed) {
5545 dest[k + 0] = transferMapRed[dest[k + 0]];
5546 }
5547 if (transferMapGreen) {
5548 dest[k + 1] = transferMapGreen[dest[k + 1]];
5549 }
5550 if (transferMapBlue) {
5551 dest[k + 2] = transferMapBlue[dest[k + 2]];
5552 }
5553 }
5554 }
5555 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5556 }
5557 } else {
5558 throw new Error(`bad image kind: ${imgData.kind}`);
5559 }
5560}
5561function putBinaryImageMask(ctx, imgData) {
5562 if (imgData.bitmap) {
5563 ctx.drawImage(imgData.bitmap, 0, 0);
5564 return;
5565 }
5566 const height = imgData.height,
5567 width = imgData.width;
5568 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5569 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5570 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5571 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5572 let srcPos = 0;
5573 const src = imgData.data;
5574 const dest = chunkImgData.data;
5575 for (let i = 0; i < totalChunks; i++) {
5576 const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5577 ({
5578 srcPos
5579 } = (0, _image_utils.applyMaskImageData)({
5580 src,
5581 srcPos,
5582 dest,
5583 width,
5584 height: thisChunkHeight
5585 }));
5586 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5587 }
5588}
5589function copyCtxState(sourceCtx, destCtx) {
5590 const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
5591 for (const property of properties) {
5592 if (sourceCtx[property] !== undefined) {
5593 destCtx[property] = sourceCtx[property];
5594 }
5595 }
5596 if (sourceCtx.setLineDash !== undefined) {
5597 destCtx.setLineDash(sourceCtx.getLineDash());
5598 destCtx.lineDashOffset = sourceCtx.lineDashOffset;
5599 }
5600}
5601function resetCtxToDefault(ctx, foregroundColor) {
5602 ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
5603 ctx.fillRule = "nonzero";
5604 ctx.globalAlpha = 1;
5605 ctx.lineWidth = 1;
5606 ctx.lineCap = "butt";
5607 ctx.lineJoin = "miter";
5608 ctx.miterLimit = 10;
5609 ctx.globalCompositeOperation = "source-over";
5610 ctx.font = "10px sans-serif";
5611 if (ctx.setLineDash !== undefined) {
5612 ctx.setLineDash([]);
5613 ctx.lineDashOffset = 0;
5614 }
5615}
5616function composeSMaskBackdrop(bytes, r0, g0, b0) {
5617 const length = bytes.length;
5618 for (let i = 3; i < length; i += 4) {
5619 const alpha = bytes[i];
5620 if (alpha === 0) {
5621 bytes[i - 3] = r0;
5622 bytes[i - 2] = g0;
5623 bytes[i - 1] = b0;
5624 } else if (alpha < 255) {
5625 const alpha_ = 255 - alpha;
5626 bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
5627 bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
5628 bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
5629 }
5630 }
5631}
5632function composeSMaskAlpha(maskData, layerData, transferMap) {
5633 const length = maskData.length;
5634 const scale = 1 / 255;
5635 for (let i = 3; i < length; i += 4) {
5636 const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
5637 layerData[i] = layerData[i] * alpha * scale | 0;
5638 }
5639}
5640function composeSMaskLuminosity(maskData, layerData, transferMap) {
5641 const length = maskData.length;
5642 for (let i = 3; i < length; i += 4) {
5643 const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
5644 layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
5645 }
5646}
5647function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
5648 const hasBackdrop = !!backdrop;
5649 const r0 = hasBackdrop ? backdrop[0] : 0;
5650 const g0 = hasBackdrop ? backdrop[1] : 0;
5651 const b0 = hasBackdrop ? backdrop[2] : 0;
5652 let composeFn;
5653 if (subtype === "Luminosity") {
5654 composeFn = composeSMaskLuminosity;
5655 } else {
5656 composeFn = composeSMaskAlpha;
5657 }
5658 const PIXELS_TO_PROCESS = 1048576;
5659 const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
5660 for (let row = 0; row < height; row += chunkSize) {
5661 const chunkHeight = Math.min(chunkSize, height - row);
5662 const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
5663 const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
5664 if (hasBackdrop) {
5665 composeSMaskBackdrop(maskData.data, r0, g0, b0);
5666 }
5667 composeFn(maskData.data, layerData.data, transferMap);
5668 layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
5669 }
5670}
5671function composeSMask(ctx, smask, layerCtx, layerBox) {
5672 const layerOffsetX = layerBox[0];
5673 const layerOffsetY = layerBox[1];
5674 const layerWidth = layerBox[2] - layerOffsetX;
5675 const layerHeight = layerBox[3] - layerOffsetY;
5676 if (layerWidth === 0 || layerHeight === 0) {
5677 return;
5678 }
5679 genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
5680 ctx.save();
5681 ctx.globalAlpha = 1;
5682 ctx.globalCompositeOperation = "source-over";
5683 ctx.setTransform(1, 0, 0, 1, 0, 0);
5684 ctx.drawImage(layerCtx.canvas, 0, 0);
5685 ctx.restore();
5686}
5687function getImageSmoothingEnabled(transform, interpolate) {
5688 const scale = _util.Util.singularValueDecompose2dScale(transform);
5689 scale[0] = Math.fround(scale[0]);
5690 scale[1] = Math.fround(scale[1]);
5691 const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
5692 if (interpolate !== undefined) {
5693 return interpolate;
5694 } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
5695 return true;
5696 }
5697 return false;
5698}
5699const LINE_CAP_STYLES = ["butt", "round", "square"];
5700const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
5701const NORMAL_CLIP = {};
5702const EO_CLIP = {};
5703class CanvasGraphics {
5704 constructor(canvasCtx, commonObjs, objs, canvasFactory, {
5705 optionalContentConfig,
5706 markedContentStack = null
5707 }, annotationCanvasMap, pageColors) {
5708 this.ctx = canvasCtx;
5709 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
5710 this.stateStack = [];
5711 this.pendingClip = null;
5712 this.pendingEOFill = false;
5713 this.res = null;
5714 this.xobjs = null;
5715 this.commonObjs = commonObjs;
5716 this.objs = objs;
5717 this.canvasFactory = canvasFactory;
5718 this.groupStack = [];
5719 this.processingType3 = null;
5720 this.baseTransform = null;
5721 this.baseTransformStack = [];
5722 this.groupLevel = 0;
5723 this.smaskStack = [];
5724 this.smaskCounter = 0;
5725 this.tempSMask = null;
5726 this.suspendedCtx = null;
5727 this.contentVisible = true;
5728 this.markedContentStack = markedContentStack || [];
5729 this.optionalContentConfig = optionalContentConfig;
5730 this.cachedCanvases = new CachedCanvases(this.canvasFactory);
5731 this.cachedPatterns = new Map();
5732 this.annotationCanvasMap = annotationCanvasMap;
5733 this.viewportScale = 1;
5734 this.outputScaleX = 1;
5735 this.outputScaleY = 1;
5736 this.backgroundColor = pageColors?.background || null;
5737 this.foregroundColor = pageColors?.foreground || null;
5738 this._cachedScaleForStroking = null;
5739 this._cachedGetSinglePixelWidth = null;
5740 this._cachedBitmapsMap = new Map();
5741 }
5742 getObject(data, fallback = null) {
5743 if (typeof data === "string") {
5744 return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
5745 }
5746 return fallback;
5747 }
5748 beginDrawing({
5749 transform,
5750 viewport,
5751 transparency = false,
5752 background = null,
5753 backgroundColorToReplace = null
5754 }) {
5755 const width = this.ctx.canvas.width;
5756 const height = this.ctx.canvas.height;
5757 const defaultBackgroundColor = background || "#ffffff";
5758 this.ctx.save();
5759 if (typeof background === "function") {
5760 background({
5761 context: this.ctx,
5762 width,
5763 height
5764 });
5765 } else if (this.foregroundColor && this.backgroundColor) {
5766 this.ctx.fillStyle = this.foregroundColor;
5767 const fg = this.foregroundColor = this.ctx.fillStyle;
5768 this.ctx.fillStyle = this.backgroundColor;
5769 const bg = this.backgroundColor = this.ctx.fillStyle;
5770 let isValidDefaultBg = true;
5771 let defaultBg = defaultBackgroundColor;
5772 this.ctx.fillStyle = defaultBackgroundColor;
5773 defaultBg = this.ctx.fillStyle;
5774 isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
5775 if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
5776 this.foregroundColor = this.backgroundColor = null;
5777 } else {
5778 const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
5779 const newComp = x => {
5780 x /= 255;
5781 return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
5782 };
5783 const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
5784 this.selectColor = (r, g, b) => {
5785 const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
5786 return Math.round(lumC) === lumB ? bg : fg;
5787 };
5788 }
5789 } else {
5790 if (background) this.background = background;
5791 this.backgroundColor = background;
5792 }
5793 if (typeof background !== "function") {
5794 this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
5795 this.ctx.fillRect(0, 0, width, height);
5796 }
5797 this.ctx.restore();
5798 this.backgroundColorToReplace = backgroundColorToReplace;
5799 if (transparency) {
5800 const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
5801 this.compositeCtx = this.ctx;
5802 this.transparentCanvas = transparentCanvas.canvas;
5803 this.ctx = transparentCanvas.context;
5804 this.ctx.save();
5805 this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
5806 }
5807 this.ctx.save();
5808 resetCtxToDefault(this.ctx, this.foregroundColor);
5809 if (transform) {
5810 this.ctx.transform(...transform);
5811 this.outputScaleX = transform[0];
5812 this.outputScaleY = transform[0];
5813 }
5814 this.ctx.transform(...viewport.transform);
5815 this.viewportScale = viewport.scale;
5816 this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
5817 }
5818 executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
5819 const argsArray = operatorList.argsArray;
5820 const fnArray = operatorList.fnArray;
5821 let i = executionStartIdx || 0;
5822 const argsArrayLen = argsArray.length;
5823 if (argsArrayLen === i) {
5824 return i;
5825 }
5826 const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
5827 const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
5828 let steps = 0;
5829 const commonObjs = this.commonObjs;
5830 const objs = this.objs;
5831 let fnId;
5832 while (true) {
5833 if (stepper !== undefined && i === stepper.nextBreakPoint) {
5834 stepper.breakIt(i, continueCallback);
5835 return i;
5836 }
5837 fnId = fnArray[i];
5838 if (fnId !== _util.OPS.dependency) {
5839 this[fnId].apply(this, argsArray[i]);
5840 } else {
5841 for (const depObjId of argsArray[i]) {
5842 const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
5843 if (!objsPool.has(depObjId)) {
5844 objsPool.get(depObjId, continueCallback);
5845 return i;
5846 }
5847 }
5848 }
5849 i++;
5850 if (i === argsArrayLen) {
5851 return i;
5852 }
5853 if (chunkOperations && ++steps > EXECUTION_STEPS) {
5854 if (Date.now() > endTime) {
5855 continueCallback();
5856 return i;
5857 }
5858 steps = 0;
5859 }
5860 }
5861 }
5862 #restoreInitialState() {
5863 while (this.stateStack.length || this.inSMaskMode) {
5864 this.restore();
5865 }
5866 this.ctx.restore();
5867 if (this.transparentCanvas) {
5868 this.ctx = this.compositeCtx;
5869 this.ctx.save();
5870 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
5871 this.ctx.drawImage(this.transparentCanvas, 0, 0);
5872 this.ctx.restore();
5873 this.transparentCanvas = null;
5874 }
5875 }
5876 endDrawing() {
5877 this.#restoreInitialState();
5878 this.cachedCanvases.clear();
5879 this.cachedPatterns.clear();
5880 for (const cache of this._cachedBitmapsMap.values()) {
5881 for (const canvas of cache.values()) {
5882 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
5883 canvas.width = canvas.height = 0;
5884 }
5885 }
5886 cache.clear();
5887 }
5888 this._cachedBitmapsMap.clear();
5889 }
5890 _scaleImage(img, inverseTransform) {
5891 const width = img.width;
5892 const height = img.height;
5893 let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
5894 let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
5895 let paintWidth = width,
5896 paintHeight = height;
5897 let tmpCanvasId = "prescale1";
5898 let tmpCanvas, tmpCtx;
5899 while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
5900 let newWidth = paintWidth,
5901 newHeight = paintHeight;
5902 if (widthScale > 2 && paintWidth > 1) {
5903 newWidth = Math.ceil(paintWidth / 2);
5904 widthScale /= paintWidth / newWidth;
5905 }
5906 if (heightScale > 2 && paintHeight > 1) {
5907 newHeight = Math.ceil(paintHeight / 2);
5908 heightScale /= paintHeight / newHeight;
5909 }
5910 tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
5911 tmpCtx = tmpCanvas.context;
5912 tmpCtx.clearRect(0, 0, newWidth, newHeight);
5913 tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
5914 img = tmpCanvas.canvas;
5915 paintWidth = newWidth;
5916 paintHeight = newHeight;
5917 tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
5918 }
5919 return {
5920 img,
5921 paintWidth,
5922 paintHeight
5923 };
5924 }
5925 _createMaskCanvas(img) {
5926 const ctx = this.ctx;
5927 const {
5928 width,
5929 height
5930 } = img;
5931 const fillColor = this.current.fillColor;
5932 const isPatternFill = this.current.patternFill;
5933 const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
5934 let cache, cacheKey, scaled, maskCanvas;
5935 if ((img.bitmap || img.data) && img.count > 1) {
5936 const mainKey = img.bitmap || img.data.buffer;
5937 cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
5938 cache = this._cachedBitmapsMap.get(mainKey);
5939 if (!cache) {
5940 cache = new Map();
5941 this._cachedBitmapsMap.set(mainKey, cache);
5942 }
5943 const cachedImage = cache.get(cacheKey);
5944 if (cachedImage && !isPatternFill) {
5945 const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
5946 const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
5947 return {
5948 canvas: cachedImage,
5949 offsetX,
5950 offsetY
5951 };
5952 }
5953 scaled = cachedImage;
5954 }
5955 if (!scaled) {
5956 maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
5957 putBinaryImageMask(maskCanvas.context, img);
5958 }
5959 let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
5960 maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
5961 const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
5962 const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
5963 const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
5964 const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
5965 const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
5966 const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
5967 const fillCtx = fillCanvas.context;
5968 const offsetX = Math.min(cord1[0], cord2[0]);
5969 const offsetY = Math.min(cord1[1], cord2[1]);
5970 fillCtx.translate(-offsetX, -offsetY);
5971 fillCtx.transform(...maskToCanvas);
5972 if (!scaled) {
5973 scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
5974 scaled = scaled.img;
5975 if (cache && isPatternFill) {
5976 cache.set(cacheKey, scaled);
5977 }
5978 }
5979 fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
5980 drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
5981 fillCtx.globalCompositeOperation = "source-in";
5982 const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
5983 fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
5984 fillCtx.fillRect(0, 0, width, height);
5985 if (cache && !isPatternFill) {
5986 this.cachedCanvases.delete("fillCanvas");
5987 cache.set(cacheKey, fillCanvas.canvas);
5988 }
5989 return {
5990 canvas: fillCanvas.canvas,
5991 offsetX: Math.round(offsetX),
5992 offsetY: Math.round(offsetY)
5993 };
5994 }
5995 setLineWidth(width) {
5996 if (width !== this.current.lineWidth) {
5997 this._cachedScaleForStroking = null;
5998 }
5999 this.current.lineWidth = width;
6000 this.ctx.lineWidth = width;
6001 }
6002 setLineCap(style) {
6003 this.ctx.lineCap = LINE_CAP_STYLES[style];
6004 }
6005 setLineJoin(style) {
6006 this.ctx.lineJoin = LINE_JOIN_STYLES[style];
6007 }
6008 setMiterLimit(limit) {
6009 this.ctx.miterLimit = limit;
6010 }
6011 setDash(dashArray, dashPhase) {
6012 const ctx = this.ctx;
6013 if (ctx.setLineDash !== undefined) {
6014 ctx.setLineDash(dashArray);
6015 ctx.lineDashOffset = dashPhase;
6016 }
6017 }
6018 setRenderingIntent(intent) {}
6019 setFlatness(flatness) {}
6020 setGState(states) {
6021 for (const [key, value] of states) {
6022 switch (key) {
6023 case "LW":
6024 this.setLineWidth(value);
6025 break;
6026 case "LC":
6027 this.setLineCap(value);
6028 break;
6029 case "LJ":
6030 this.setLineJoin(value);
6031 break;
6032 case "ML":
6033 this.setMiterLimit(value);
6034 break;
6035 case "D":
6036 this.setDash(value[0], value[1]);
6037 break;
6038 case "RI":
6039 this.setRenderingIntent(value);
6040 break;
6041 case "FL":
6042 this.setFlatness(value);
6043 break;
6044 case "Font":
6045 this.setFont(value[0], value[1]);
6046 break;
6047 case "CA":
6048 this.current.strokeAlpha = value;
6049 break;
6050 case "ca":
6051 this.current.fillAlpha = value;
6052 this.ctx.globalAlpha = value;
6053 break;
6054 case "BM":
6055 this.ctx.globalCompositeOperation = value;
6056 break;
6057 case "SMask":
6058 this.current.activeSMask = value ? this.tempSMask : null;
6059 this.tempSMask = null;
6060 this.checkSMaskState();
6061 break;
6062 case "TR":
6063 this.current.transferMaps = value;
6064 }
6065 }
6066 }
6067 get inSMaskMode() {
6068 return !!this.suspendedCtx;
6069 }
6070 checkSMaskState() {
6071 const inSMaskMode = this.inSMaskMode;
6072 if (this.current.activeSMask && !inSMaskMode) {
6073 this.beginSMaskMode();
6074 } else if (!this.current.activeSMask && inSMaskMode) {
6075 this.endSMaskMode();
6076 }
6077 }
6078 beginSMaskMode() {
6079 if (this.inSMaskMode) {
6080 throw new Error("beginSMaskMode called while already in smask mode");
6081 }
6082 const drawnWidth = this.ctx.canvas.width;
6083 const drawnHeight = this.ctx.canvas.height;
6084 const cacheId = "smaskGroupAt" + this.groupLevel;
6085 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
6086 this.suspendedCtx = this.ctx;
6087 this.ctx = scratchCanvas.context;
6088 const ctx = this.ctx;
6089 ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
6090 copyCtxState(this.suspendedCtx, ctx);
6091 mirrorContextOperations(ctx, this.suspendedCtx);
6092 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
6093 }
6094 endSMaskMode() {
6095 if (!this.inSMaskMode) {
6096 throw new Error("endSMaskMode called while not in smask mode");
6097 }
6098 this.ctx._removeMirroring();
6099 copyCtxState(this.ctx, this.suspendedCtx);
6100 this.ctx = this.suspendedCtx;
6101 this.suspendedCtx = null;
6102 }
6103 compose(dirtyBox) {
6104 if (!this.current.activeSMask) {
6105 return;
6106 }
6107 if (!dirtyBox) {
6108 dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
6109 } else {
6110 dirtyBox[0] = Math.floor(dirtyBox[0]);
6111 dirtyBox[1] = Math.floor(dirtyBox[1]);
6112 dirtyBox[2] = Math.ceil(dirtyBox[2]);
6113 dirtyBox[3] = Math.ceil(dirtyBox[3]);
6114 }
6115 const smask = this.current.activeSMask;
6116 const suspendedCtx = this.suspendedCtx;
6117 composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
6118 this.ctx.save();
6119 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
6120 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
6121 this.ctx.restore();
6122 }
6123 save() {
6124 if (this.inSMaskMode) {
6125 copyCtxState(this.ctx, this.suspendedCtx);
6126 this.suspendedCtx.save();
6127 } else {
6128 this.ctx.save();
6129 }
6130 const old = this.current;
6131 this.stateStack.push(old);
6132 this.current = old.clone();
6133 }
6134 restore() {
6135 if (this.stateStack.length === 0 && this.inSMaskMode) {
6136 this.endSMaskMode();
6137 }
6138 if (this.stateStack.length !== 0) {
6139 this.current = this.stateStack.pop();
6140 if (this.inSMaskMode) {
6141 this.suspendedCtx.restore();
6142 copyCtxState(this.suspendedCtx, this.ctx);
6143 } else {
6144 this.ctx.restore();
6145 }
6146 this.checkSMaskState();
6147 this.pendingClip = null;
6148 this._cachedScaleForStroking = null;
6149 this._cachedGetSinglePixelWidth = null;
6150 }
6151 }
6152 transform(a, b, c, d, e, f) {
6153 this.ctx.transform(a, b, c, d, e, f);
6154 this._cachedScaleForStroking = null;
6155 this._cachedGetSinglePixelWidth = null;
6156 }
6157 constructPath(ops, args, minMax) {
6158 const ctx = this.ctx;
6159 const current = this.current;
6160 let x = current.x,
6161 y = current.y;
6162 let startX, startY;
6163 const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
6164 const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
6165 const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
6166 for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
6167 switch (ops[i] | 0) {
6168 case _util.OPS.rectangle:
6169 x = args[j++];
6170 y = args[j++];
6171 const width = args[j++];
6172 const height = args[j++];
6173 const xw = x + width;
6174 const yh = y + height;
6175 ctx.moveTo(x, y);
6176 if (width === 0 || height === 0) {
6177 ctx.lineTo(xw, yh);
6178 } else {
6179 ctx.lineTo(xw, y);
6180 ctx.lineTo(xw, yh);
6181 ctx.lineTo(x, yh);
6182 }
6183 if (!isScalingMatrix) {
6184 current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
6185 }
6186 ctx.closePath();
6187 break;
6188 case _util.OPS.moveTo:
6189 x = args[j++];
6190 y = args[j++];
6191 ctx.moveTo(x, y);
6192 if (!isScalingMatrix) {
6193 current.updatePathMinMax(currentTransform, x, y);
6194 }
6195 break;
6196 case _util.OPS.lineTo:
6197 x = args[j++];
6198 y = args[j++];
6199 ctx.lineTo(x, y);
6200 if (!isScalingMatrix) {
6201 current.updatePathMinMax(currentTransform, x, y);
6202 }
6203 break;
6204 case _util.OPS.curveTo:
6205 startX = x;
6206 startY = y;
6207 x = args[j + 4];
6208 y = args[j + 5];
6209 ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
6210 current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
6211 j += 6;
6212 break;
6213 case _util.OPS.curveTo2:
6214 startX = x;
6215 startY = y;
6216 ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
6217 current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
6218 x = args[j + 2];
6219 y = args[j + 3];
6220 j += 4;
6221 break;
6222 case _util.OPS.curveTo3:
6223 startX = x;
6224 startY = y;
6225 x = args[j + 2];
6226 y = args[j + 3];
6227 ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
6228 current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
6229 j += 4;
6230 break;
6231 case _util.OPS.closePath:
6232 ctx.closePath();
6233 break;
6234 }
6235 }
6236 if (isScalingMatrix) {
6237 current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
6238 }
6239 current.setCurrentPoint(x, y);
6240 }
6241 closePath() {
6242 this.ctx.closePath();
6243 }
6244 stroke(consumePath = true) {
6245 const ctx = this.ctx;
6246 const strokeColor = this.current.strokeColor;
6247 ctx.globalAlpha = this.current.strokeAlpha;
6248 if (this.contentVisible) {
6249 if (typeof strokeColor === "object" && strokeColor?.getPattern) {
6250 ctx.save();
6251 ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
6252 this.rescaleAndStroke(false);
6253 ctx.restore();
6254 } else {
6255 this.rescaleAndStroke(true);
6256 }
6257 }
6258 if (consumePath) {
6259 this.consumePath(this.current.getClippedPathBoundingBox());
6260 }
6261 ctx.globalAlpha = this.current.fillAlpha;
6262 }
6263 closeStroke() {
6264 this.closePath();
6265 this.stroke();
6266 }
6267 fill(consumePath = true) {
6268 const ctx = this.ctx;
6269 let draw = true;
6270 let fillColor = this.current.fillColor;
6271 if (this.backgroundColorToReplace) {
6272 if (fillColor === this.backgroundColorToReplace) {
6273 if (this.background && typeof this.background !== 'function') {
6274 fillColor = this.background;
6275 } else {
6276 draw = false;
6277 }
6278 }
6279 }
6280 const isPatternFill = this.current.patternFill;
6281 let needRestore = false;
6282 if (isPatternFill) {
6283 ctx.save();
6284 ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
6285 needRestore = true;
6286 }
6287 const intersect = this.current.getClippedPathBoundingBox();
6288 if (draw) {
6289 if (this.contentVisible && intersect !== null) {
6290 if (this.pendingEOFill) {
6291 ctx.fill("evenodd");
6292 this.pendingEOFill = false;
6293 } else {
6294 ctx.fill();
6295 }
6296 }
6297 }
6298 if (needRestore) {
6299 ctx.restore();
6300 }
6301 if (consumePath) {
6302 this.consumePath(intersect);
6303 }
6304 }
6305 eoFill() {
6306 this.pendingEOFill = true;
6307 this.fill();
6308 }
6309 fillStroke() {
6310 this.fill(false);
6311 this.stroke(false);
6312 this.consumePath();
6313 }
6314 eoFillStroke() {
6315 this.pendingEOFill = true;
6316 this.fillStroke();
6317 }
6318 closeFillStroke() {
6319 this.closePath();
6320 this.fillStroke();
6321 }
6322 closeEOFillStroke() {
6323 this.pendingEOFill = true;
6324 this.closePath();
6325 this.fillStroke();
6326 }
6327 endPath() {
6328 this.consumePath();
6329 }
6330 clip() {
6331 this.pendingClip = NORMAL_CLIP;
6332 }
6333 eoClip() {
6334 this.pendingClip = EO_CLIP;
6335 }
6336 beginText() {
6337 this.current.textMatrix = _util.IDENTITY_MATRIX;
6338 this.current.textMatrixScale = 1;
6339 this.current.x = this.current.lineX = 0;
6340 this.current.y = this.current.lineY = 0;
6341 }
6342 endText() {
6343 const paths = this.pendingTextPaths;
6344 const ctx = this.ctx;
6345 if (paths === undefined) {
6346 ctx.beginPath();
6347 return;
6348 }
6349 ctx.save();
6350 ctx.beginPath();
6351 for (const path of paths) {
6352 ctx.setTransform(...path.transform);
6353 ctx.translate(path.x, path.y);
6354 path.addToPath(ctx, path.fontSize);
6355 }
6356 ctx.restore();
6357 ctx.clip();
6358 ctx.beginPath();
6359 delete this.pendingTextPaths;
6360 }
6361 setCharSpacing(spacing) {
6362 this.current.charSpacing = spacing;
6363 }
6364 setWordSpacing(spacing) {
6365 this.current.wordSpacing = spacing;
6366 }
6367 setHScale(scale) {
6368 this.current.textHScale = scale / 100;
6369 }
6370 setLeading(leading) {
6371 this.current.leading = -leading;
6372 }
6373 setFont(fontRefName, size) {
6374 const fontObj = this.commonObjs.get(fontRefName);
6375 const current = this.current;
6376 if (!fontObj) {
6377 throw new Error(`Can't find font for ${fontRefName}`);
6378 }
6379 current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6380 if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
6381 (0, _util.warn)("Invalid font matrix for font " + fontRefName);
6382 }
6383 if (size < 0) {
6384 size = -size;
6385 current.fontDirection = -1;
6386 } else {
6387 current.fontDirection = 1;
6388 }
6389 this.current.font = fontObj;
6390 this.current.fontSize = size;
6391 if (fontObj.isType3Font) {
6392 return;
6393 }
6394 const name = fontObj.loadedName || "sans-serif";
6395 let bold = "normal";
6396 if (fontObj.black) {
6397 bold = "900";
6398 } else if (fontObj.bold) {
6399 bold = "bold";
6400 }
6401 const italic = fontObj.italic ? "italic" : "normal";
6402 const typeface = `"${name}", ${fontObj.fallbackName}`;
6403 let browserFontSize = size;
6404 if (size < MIN_FONT_SIZE) {
6405 browserFontSize = MIN_FONT_SIZE;
6406 } else if (size > MAX_FONT_SIZE) {
6407 browserFontSize = MAX_FONT_SIZE;
6408 }
6409 this.current.fontSizeScale = size / browserFontSize;
6410 this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
6411 }
6412 setTextRenderingMode(mode) {
6413 this.current.textRenderingMode = mode;
6414 }
6415 setTextRise(rise) {
6416 this.current.textRise = rise;
6417 }
6418 moveText(x, y) {
6419 this.current.x = this.current.lineX += x;
6420 this.current.y = this.current.lineY += y;
6421 }
6422 setLeadingMoveText(x, y) {
6423 this.setLeading(-y);
6424 this.moveText(x, y);
6425 }
6426 setTextMatrix(a, b, c, d, e, f) {
6427 this.current.textMatrix = [a, b, c, d, e, f];
6428 this.current.textMatrixScale = Math.hypot(a, b);
6429 this.current.x = this.current.lineX = 0;
6430 this.current.y = this.current.lineY = 0;
6431 }
6432 nextLine() {
6433 this.moveText(0, this.current.leading);
6434 }
6435 paintChar(character, x, y, patternTransform) {
6436 const ctx = this.ctx;
6437 const current = this.current;
6438 const font = current.font;
6439 const textRenderingMode = current.textRenderingMode;
6440 const fontSize = current.fontSize / current.fontSizeScale;
6441 const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6442 const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
6443 const patternFill = current.patternFill && !font.missingFile;
6444 let addToPath;
6445 if (font.disableFontFace || isAddToPathSet || patternFill) {
6446 addToPath = font.getPathGenerator(this.commonObjs, character);
6447 }
6448 if (font.disableFontFace || patternFill) {
6449 ctx.save();
6450 ctx.translate(x, y);
6451 ctx.beginPath();
6452 addToPath(ctx, fontSize);
6453 if (patternTransform) {
6454 ctx.setTransform(...patternTransform);
6455 }
6456 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6457 ctx.fill();
6458 }
6459 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6460 ctx.stroke();
6461 }
6462 ctx.restore();
6463 } else {
6464 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6465 ctx.fillText(character, x, y);
6466 }
6467 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6468 ctx.strokeText(character, x, y);
6469 }
6470 }
6471 if (isAddToPathSet) {
6472 const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
6473 paths.push({
6474 transform: (0, _display_utils.getCurrentTransform)(ctx),
6475 x,
6476 y,
6477 fontSize,
6478 addToPath
6479 });
6480 }
6481 }
6482 get isFontSubpixelAAEnabled() {
6483 const {
6484 context: ctx
6485 } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
6486 ctx.scale(1.5, 1);
6487 ctx.fillText("I", 0, 10);
6488 const data = ctx.getImageData(0, 0, 10, 10).data;
6489 let enabled = false;
6490 for (let i = 3; i < data.length; i += 4) {
6491 if (data[i] > 0 && data[i] < 255) {
6492 enabled = true;
6493 break;
6494 }
6495 }
6496 return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
6497 }
6498 showText(glyphs) {
6499 const current = this.current;
6500 const font = current.font;
6501 if (font.isType3Font) {
6502 return this.showType3Text(glyphs);
6503 }
6504 const fontSize = current.fontSize;
6505 if (fontSize === 0) {
6506 return undefined;
6507 }
6508 const ctx = this.ctx;
6509 const fontSizeScale = current.fontSizeScale;
6510 const charSpacing = current.charSpacing;
6511 const wordSpacing = current.wordSpacing;
6512 const fontDirection = current.fontDirection;
6513 const textHScale = current.textHScale * fontDirection;
6514 const glyphsLength = glyphs.length;
6515 const vertical = font.vertical;
6516 const spacingDir = vertical ? 1 : -1;
6517 const defaultVMetrics = font.defaultVMetrics;
6518 const widthAdvanceScale = fontSize * current.fontMatrix[0];
6519 const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
6520 ctx.save();
6521 ctx.transform(...current.textMatrix);
6522 ctx.translate(current.x, current.y + current.textRise);
6523 if (fontDirection > 0) {
6524 ctx.scale(textHScale, -1);
6525 } else {
6526 ctx.scale(textHScale, 1);
6527 }
6528 let patternTransform;
6529 if (current.patternFill) {
6530 ctx.save();
6531 const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
6532 patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
6533 ctx.restore();
6534 ctx.fillStyle = pattern;
6535 }
6536 let lineWidth = current.lineWidth;
6537 const scale = current.textMatrixScale;
6538 if (scale === 0 || lineWidth === 0) {
6539 const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6540 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6541 lineWidth = this.getSinglePixelWidth();
6542 }
6543 } else {
6544 lineWidth /= scale;
6545 }
6546 if (fontSizeScale !== 1.0) {
6547 ctx.scale(fontSizeScale, fontSizeScale);
6548 lineWidth /= fontSizeScale;
6549 }
6550 ctx.lineWidth = lineWidth;
6551 if (font.isInvalidPDFjsFont) {
6552 const chars = [];
6553 let width = 0;
6554 for (const glyph of glyphs) {
6555 chars.push(glyph.unicode);
6556 width += glyph.width;
6557 }
6558 ctx.fillText(chars.join(""), 0, 0);
6559 current.x += width * widthAdvanceScale * textHScale;
6560 ctx.restore();
6561 this.compose();
6562 return undefined;
6563 }
6564 let x = 0,
6565 i;
6566 for (i = 0; i < glyphsLength; ++i) {
6567 const glyph = glyphs[i];
6568 if (typeof glyph === "number") {
6569 x += spacingDir * glyph * fontSize / 1000;
6570 continue;
6571 }
6572 let restoreNeeded = false;
6573 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6574 const character = glyph.fontChar;
6575 const accent = glyph.accent;
6576 let scaledX, scaledY;
6577 let width = glyph.width;
6578 if (vertical) {
6579 const vmetric = glyph.vmetric || defaultVMetrics;
6580 const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
6581 const vy = vmetric[2] * widthAdvanceScale;
6582 width = vmetric ? -vmetric[0] : width;
6583 scaledX = vx / fontSizeScale;
6584 scaledY = (x + vy) / fontSizeScale;
6585 } else {
6586 scaledX = x / fontSizeScale;
6587 scaledY = 0;
6588 }
6589 if (font.remeasure && width > 0) {
6590 const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
6591 if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
6592 const characterScaleX = width / measuredWidth;
6593 restoreNeeded = true;
6594 ctx.save();
6595 ctx.scale(characterScaleX, 1);
6596 scaledX /= characterScaleX;
6597 } else if (width !== measuredWidth) {
6598 scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
6599 }
6600 }
6601 if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
6602 if (simpleFillText && !accent) {
6603 ctx.fillText(character, scaledX, scaledY);
6604 } else {
6605 this.paintChar(character, scaledX, scaledY, patternTransform);
6606 if (accent) {
6607 const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
6608 const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
6609 this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
6610 }
6611 }
6612 }
6613 let charWidth;
6614 if (vertical) {
6615 charWidth = width * widthAdvanceScale - spacing * fontDirection;
6616 } else {
6617 charWidth = width * widthAdvanceScale + spacing * fontDirection;
6618 }
6619 x += charWidth;
6620 if (restoreNeeded) {
6621 ctx.restore();
6622 }
6623 }
6624 if (vertical) {
6625 current.y -= x;
6626 } else {
6627 current.x += x * textHScale;
6628 }
6629 ctx.restore();
6630 this.compose();
6631 return undefined;
6632 }
6633 showType3Text(glyphs) {
6634 const ctx = this.ctx;
6635 const current = this.current;
6636 const font = current.font;
6637 const fontSize = current.fontSize;
6638 const fontDirection = current.fontDirection;
6639 const spacingDir = font.vertical ? 1 : -1;
6640 const charSpacing = current.charSpacing;
6641 const wordSpacing = current.wordSpacing;
6642 const textHScale = current.textHScale * fontDirection;
6643 const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6644 const glyphsLength = glyphs.length;
6645 const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
6646 let i, glyph, width, spacingLength;
6647 if (isTextInvisible || fontSize === 0) {
6648 return;
6649 }
6650 this._cachedScaleForStroking = null;
6651 this._cachedGetSinglePixelWidth = null;
6652 ctx.save();
6653 ctx.transform(...current.textMatrix);
6654 ctx.translate(current.x, current.y);
6655 ctx.scale(textHScale, fontDirection);
6656 for (i = 0; i < glyphsLength; ++i) {
6657 glyph = glyphs[i];
6658 if (typeof glyph === "number") {
6659 spacingLength = spacingDir * glyph * fontSize / 1000;
6660 this.ctx.translate(spacingLength, 0);
6661 current.x += spacingLength * textHScale;
6662 continue;
6663 }
6664 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6665 const operatorList = font.charProcOperatorList[glyph.operatorListId];
6666 if (!operatorList) {
6667 (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
6668 continue;
6669 }
6670 if (this.contentVisible) {
6671 this.processingType3 = glyph;
6672 this.save();
6673 ctx.scale(fontSize, fontSize);
6674 ctx.transform(...fontMatrix);
6675 this.executeOperatorList(operatorList);
6676 this.restore();
6677 }
6678 const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
6679 width = transformed[0] * fontSize + spacing;
6680 ctx.translate(width, 0);
6681 current.x += width * textHScale;
6682 }
6683 ctx.restore();
6684 this.processingType3 = null;
6685 }
6686 setCharWidth(xWidth, yWidth) {}
6687 setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
6688 this.ctx.rect(llx, lly, urx - llx, ury - lly);
6689 this.ctx.clip();
6690 this.endPath();
6691 }
6692 getColorN_Pattern(IR) {
6693 let pattern;
6694 if (IR[0] === "TilingPattern") {
6695 const color = IR[1];
6696 const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
6697 const canvasGraphicsFactory = {
6698 createCanvasGraphics: ctx => {
6699 return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, {
6700 optionalContentConfig: this.optionalContentConfig,
6701 markedContentStack: this.markedContentStack
6702 });
6703 }
6704 };
6705 pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
6706 } else {
6707 pattern = this._getPattern(IR[1], IR[2]);
6708 }
6709 return pattern;
6710 }
6711 setStrokeColorN() {
6712 this.current.strokeColor = this.getColorN_Pattern(arguments);
6713 }
6714 setFillColorN() {
6715 this.current.fillColor = this.getColorN_Pattern(arguments);
6716 this.current.patternFill = true;
6717 }
6718 setStrokeRGBColor(r, g, b) {
6719 const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
6720 this.ctx.strokeStyle = color;
6721 this.current.strokeColor = color;
6722 }
6723 setFillRGBColor(r, g, b) {
6724 let color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
6725 if (this.backgroundColorToReplace) {
6726 if (color === this.backgroundColorToReplace) {
6727 if (this.background && typeof this.background !== 'function') {
6728 color = this.background;
6729 } else {}
6730 }
6731 }
6732 this.ctx.fillStyle = color;
6733 this.current.fillColor = color;
6734 this.current.patternFill = false;
6735 }
6736 _getPattern(objId, matrix = null) {
6737 let pattern;
6738 if (this.cachedPatterns.has(objId)) {
6739 pattern = this.cachedPatterns.get(objId);
6740 } else {
6741 pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
6742 this.cachedPatterns.set(objId, pattern);
6743 }
6744 if (matrix) {
6745 pattern.matrix = matrix;
6746 }
6747 return pattern;
6748 }
6749 shadingFill(objId) {
6750 if (!this.contentVisible) {
6751 return;
6752 }
6753 const ctx = this.ctx;
6754 this.save();
6755 const pattern = this._getPattern(objId);
6756 ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
6757 const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
6758 if (inv) {
6759 const canvas = ctx.canvas;
6760 const width = canvas.width;
6761 const height = canvas.height;
6762 const bl = _util.Util.applyTransform([0, 0], inv);
6763 const br = _util.Util.applyTransform([0, height], inv);
6764 const ul = _util.Util.applyTransform([width, 0], inv);
6765 const ur = _util.Util.applyTransform([width, height], inv);
6766 const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
6767 const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
6768 const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
6769 const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
6770 this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
6771 } else {
6772 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
6773 }
6774 this.compose(this.current.getClippedPathBoundingBox());
6775 this.restore();
6776 }
6777 beginInlineImage() {
6778 (0, _util.unreachable)("Should not call beginInlineImage");
6779 }
6780 beginImageData() {
6781 (0, _util.unreachable)("Should not call beginImageData");
6782 }
6783 paintFormXObjectBegin(matrix, bbox) {
6784 if (!this.contentVisible) {
6785 return;
6786 }
6787 this.save();
6788 this.baseTransformStack.push(this.baseTransform);
6789 if (Array.isArray(matrix) && matrix.length === 6) {
6790 this.transform(...matrix);
6791 }
6792 this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
6793 if (bbox) {
6794 const width = bbox[2] - bbox[0];
6795 const height = bbox[3] - bbox[1];
6796 this.ctx.rect(bbox[0], bbox[1], width, height);
6797 this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
6798 this.clip();
6799 this.endPath();
6800 }
6801 }
6802 paintFormXObjectEnd() {
6803 if (!this.contentVisible) {
6804 return;
6805 }
6806 this.restore();
6807 this.baseTransform = this.baseTransformStack.pop();
6808 }
6809 beginGroup(group) {
6810 if (!this.contentVisible) {
6811 return;
6812 }
6813 this.save();
6814 if (this.inSMaskMode) {
6815 this.endSMaskMode();
6816 this.current.activeSMask = null;
6817 }
6818 const currentCtx = this.ctx;
6819 if (!group.isolated) {
6820 (0, _util.info)("TODO: Support non-isolated groups.");
6821 }
6822 if (group.knockout) {
6823 (0, _util.warn)("Knockout groups not supported.");
6824 }
6825 const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
6826 if (group.matrix) {
6827 currentCtx.transform(...group.matrix);
6828 }
6829 if (!group.bbox) {
6830 throw new Error("Bounding box is required.");
6831 }
6832 let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
6833 const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
6834 bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
6835 const offsetX = Math.floor(bounds[0]);
6836 const offsetY = Math.floor(bounds[1]);
6837 let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
6838 let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
6839 let scaleX = 1,
6840 scaleY = 1;
6841 if (drawnWidth > MAX_GROUP_SIZE) {
6842 scaleX = drawnWidth / MAX_GROUP_SIZE;
6843 drawnWidth = MAX_GROUP_SIZE;
6844 }
6845 if (drawnHeight > MAX_GROUP_SIZE) {
6846 scaleY = drawnHeight / MAX_GROUP_SIZE;
6847 drawnHeight = MAX_GROUP_SIZE;
6848 }
6849 this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
6850 let cacheId = "groupAt" + this.groupLevel;
6851 if (group.smask) {
6852 cacheId += "_smask_" + this.smaskCounter++ % 2;
6853 }
6854 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
6855 const groupCtx = scratchCanvas.context;
6856 groupCtx.scale(1 / scaleX, 1 / scaleY);
6857 groupCtx.translate(-offsetX, -offsetY);
6858 groupCtx.transform(...currentTransform);
6859 if (group.smask) {
6860 this.smaskStack.push({
6861 canvas: scratchCanvas.canvas,
6862 context: groupCtx,
6863 offsetX,
6864 offsetY,
6865 scaleX,
6866 scaleY,
6867 subtype: group.smask.subtype,
6868 backdrop: group.smask.backdrop,
6869 transferMap: group.smask.transferMap || null,
6870 startTransformInverse: null
6871 });
6872 } else {
6873 currentCtx.setTransform(1, 0, 0, 1, 0, 0);
6874 currentCtx.translate(offsetX, offsetY);
6875 currentCtx.scale(scaleX, scaleY);
6876 currentCtx.save();
6877 }
6878 copyCtxState(currentCtx, groupCtx);
6879 this.ctx = groupCtx;
6880 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
6881 this.groupStack.push(currentCtx);
6882 this.groupLevel++;
6883 }
6884 endGroup(group) {
6885 if (!this.contentVisible) {
6886 return;
6887 }
6888 this.groupLevel--;
6889 const groupCtx = this.ctx;
6890 const ctx = this.groupStack.pop();
6891 this.ctx = ctx;
6892 this.ctx.imageSmoothingEnabled = false;
6893 if (group.smask) {
6894 this.tempSMask = this.smaskStack.pop();
6895 this.restore();
6896 } else {
6897 this.ctx.restore();
6898 const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
6899 this.restore();
6900 this.ctx.save();
6901 this.ctx.setTransform(...currentMtx);
6902 const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
6903 this.ctx.drawImage(groupCtx.canvas, 0, 0);
6904 this.ctx.restore();
6905 this.compose(dirtyBox);
6906 }
6907 }
6908 beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
6909 this.#restoreInitialState();
6910 resetCtxToDefault(this.ctx, this.foregroundColor);
6911 this.ctx.save();
6912 this.save();
6913 if (this.baseTransform) {
6914 this.ctx.setTransform(...this.baseTransform);
6915 }
6916 if (Array.isArray(rect) && rect.length === 4) {
6917 const width = rect[2] - rect[0];
6918 const height = rect[3] - rect[1];
6919 if (hasOwnCanvas && this.annotationCanvasMap) {
6920 transform = transform.slice();
6921 transform[4] -= rect[0];
6922 transform[5] -= rect[1];
6923 rect = rect.slice();
6924 rect[0] = rect[1] = 0;
6925 rect[2] = width;
6926 rect[3] = height;
6927 const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
6928 const {
6929 viewportScale
6930 } = this;
6931 const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
6932 const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
6933 this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
6934 const {
6935 canvas,
6936 context
6937 } = this.annotationCanvas;
6938 this.annotationCanvasMap.set(id, canvas);
6939 this.annotationCanvas.savedCtx = this.ctx;
6940 this.ctx = context;
6941 this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
6942 resetCtxToDefault(this.ctx, this.foregroundColor);
6943 } else {
6944 resetCtxToDefault(this.ctx, this.foregroundColor);
6945 this.ctx.rect(rect[0], rect[1], width, height);
6946 this.ctx.clip();
6947 this.endPath();
6948 }
6949 }
6950 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
6951 this.transform(...transform);
6952 this.transform(...matrix);
6953 }
6954 endAnnotation() {
6955 if (this.annotationCanvas) {
6956 this.ctx = this.annotationCanvas.savedCtx;
6957 delete this.annotationCanvas.savedCtx;
6958 delete this.annotationCanvas;
6959 }
6960 }
6961 paintImageMaskXObject(img) {
6962 if (!this.contentVisible) {
6963 return;
6964 }
6965 const count = img.count;
6966 img = this.getObject(img.data, img);
6967 img.count = count;
6968 const ctx = this.ctx;
6969 const glyph = this.processingType3;
6970 if (glyph) {
6971 if (glyph.compiled === undefined) {
6972 glyph.compiled = compileType3Glyph(img);
6973 }
6974 if (glyph.compiled) {
6975 glyph.compiled(ctx);
6976 return;
6977 }
6978 }
6979 const mask = this._createMaskCanvas(img);
6980 const maskCanvas = mask.canvas;
6981 ctx.save();
6982 ctx.setTransform(1, 0, 0, 1, 0, 0);
6983 ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
6984 ctx.restore();
6985 this.compose();
6986 }
6987 paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
6988 if (!this.contentVisible) {
6989 return;
6990 }
6991 img = this.getObject(img.data, img);
6992 const ctx = this.ctx;
6993 ctx.save();
6994 const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
6995 ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
6996 const mask = this._createMaskCanvas(img);
6997 ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
6998 for (let i = 0, ii = positions.length; i < ii; i += 2) {
6999 const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
7000 const [x, y] = _util.Util.applyTransform([0, 0], trans);
7001 ctx.drawImage(mask.canvas, x, y);
7002 }
7003 ctx.restore();
7004 this.compose();
7005 }
7006 paintImageMaskXObjectGroup(images) {
7007 if (!this.contentVisible) {
7008 return;
7009 }
7010 const ctx = this.ctx;
7011 const fillColor = this.current.fillColor;
7012 const isPatternFill = this.current.patternFill;
7013 for (const image of images) {
7014 const {
7015 data,
7016 width,
7017 height,
7018 transform
7019 } = image;
7020 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
7021 const maskCtx = maskCanvas.context;
7022 maskCtx.save();
7023 const img = this.getObject(data, image);
7024 putBinaryImageMask(maskCtx, img);
7025 maskCtx.globalCompositeOperation = "source-in";
7026 maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
7027 maskCtx.fillRect(0, 0, width, height);
7028 maskCtx.restore();
7029 ctx.save();
7030 ctx.transform(...transform);
7031 ctx.scale(1, -1);
7032 drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
7033 ctx.restore();
7034 }
7035 this.compose();
7036 }
7037 paintImageXObject(objId) {
7038 if (!this.contentVisible) {
7039 return;
7040 }
7041 const imgData = this.getObject(objId);
7042 if (!imgData) {
7043 (0, _util.warn)("Dependent image isn't ready yet");
7044 return;
7045 }
7046 this.paintInlineImageXObject(imgData);
7047 }
7048 paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
7049 if (!this.contentVisible) {
7050 return;
7051 }
7052 const imgData = this.getObject(objId);
7053 if (!imgData) {
7054 (0, _util.warn)("Dependent image isn't ready yet");
7055 return;
7056 }
7057 const width = imgData.width;
7058 const height = imgData.height;
7059 const map = [];
7060 for (let i = 0, ii = positions.length; i < ii; i += 2) {
7061 map.push({
7062 transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
7063 x: 0,
7064 y: 0,
7065 w: width,
7066 h: height
7067 });
7068 }
7069 this.paintInlineImageXObjectGroup(imgData, map);
7070 }
7071 paintInlineImageXObject(imgData) {
7072 if (!this.contentVisible) {
7073 return;
7074 }
7075 const width = imgData.width;
7076 const height = imgData.height;
7077 const ctx = this.ctx;
7078 this.save();
7079 ctx.scale(1 / width, -1 / height);
7080 let imgToPaint;
7081 if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
7082 imgToPaint = imgData;
7083 } else {
7084 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
7085 const tmpCtx = tmpCanvas.context;
7086 putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
7087 imgToPaint = tmpCanvas.canvas;
7088 }
7089 const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
7090 ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
7091 drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
7092 this.compose();
7093 this.restore();
7094 }
7095 paintInlineImageXObjectGroup(imgData, map) {
7096 if (!this.contentVisible) {
7097 return;
7098 }
7099 const ctx = this.ctx;
7100 const w = imgData.width;
7101 const h = imgData.height;
7102 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
7103 const tmpCtx = tmpCanvas.context;
7104 putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
7105 for (const entry of map) {
7106 ctx.save();
7107 ctx.transform(...entry.transform);
7108 ctx.scale(1, -1);
7109 drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
7110 ctx.restore();
7111 }
7112 this.compose();
7113 }
7114 paintSolidColorImageMask() {
7115 if (!this.contentVisible) {
7116 return;
7117 }
7118 this.ctx.fillRect(0, 0, 1, 1);
7119 this.compose();
7120 }
7121 markPoint(tag) {}
7122 markPointProps(tag, properties) {}
7123 beginMarkedContent(tag) {
7124 this.markedContentStack.push({
7125 visible: true
7126 });
7127 }
7128 beginMarkedContentProps(tag, properties) {
7129 if (tag === "OC") {
7130 this.markedContentStack.push({
7131 visible: this.optionalContentConfig.isVisible(properties)
7132 });
7133 } else {
7134 this.markedContentStack.push({
7135 visible: true
7136 });
7137 }
7138 this.contentVisible = this.isContentVisible();
7139 }
7140 endMarkedContent() {
7141 this.markedContentStack.pop();
7142 this.contentVisible = this.isContentVisible();
7143 }
7144 beginCompat() {}
7145 endCompat() {}
7146 consumePath(clipBox) {
7147 const isEmpty = this.current.isEmptyClip();
7148 if (this.pendingClip) {
7149 this.current.updateClipFromPath();
7150 }
7151 if (!this.pendingClip) {
7152 this.compose(clipBox);
7153 }
7154 const ctx = this.ctx;
7155 if (this.pendingClip) {
7156 if (!isEmpty) {
7157 if (this.pendingClip === EO_CLIP) {
7158 ctx.clip("evenodd");
7159 } else {
7160 ctx.clip();
7161 }
7162 }
7163 this.pendingClip = null;
7164 }
7165 this.current.startNewPathAndClipBox(this.current.clipBox);
7166 ctx.beginPath();
7167 }
7168 getSinglePixelWidth() {
7169 if (!this._cachedGetSinglePixelWidth) {
7170 const m = (0, _display_utils.getCurrentTransform)(this.ctx);
7171 if (m[1] === 0 && m[2] === 0) {
7172 this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
7173 } else {
7174 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7175 const normX = Math.hypot(m[0], m[2]);
7176 const normY = Math.hypot(m[1], m[3]);
7177 this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
7178 }
7179 }
7180 return this._cachedGetSinglePixelWidth;
7181 }
7182 getScaleForStroking() {
7183 if (!this._cachedScaleForStroking) {
7184 const {
7185 lineWidth
7186 } = this.current;
7187 const m = (0, _display_utils.getCurrentTransform)(this.ctx);
7188 let scaleX, scaleY;
7189 if (m[1] === 0 && m[2] === 0) {
7190 const normX = Math.abs(m[0]);
7191 const normY = Math.abs(m[3]);
7192 if (lineWidth === 0) {
7193 scaleX = 1 / normX;
7194 scaleY = 1 / normY;
7195 } else {
7196 const scaledXLineWidth = normX * lineWidth;
7197 const scaledYLineWidth = normY * lineWidth;
7198 scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
7199 scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
7200 }
7201 } else {
7202 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7203 const normX = Math.hypot(m[0], m[1]);
7204 const normY = Math.hypot(m[2], m[3]);
7205 if (lineWidth === 0) {
7206 scaleX = normY / absDet;
7207 scaleY = normX / absDet;
7208 } else {
7209 const baseArea = lineWidth * absDet;
7210 scaleX = normY > baseArea ? normY / baseArea : 1;
7211 scaleY = normX > baseArea ? normX / baseArea : 1;
7212 }
7213 }
7214 this._cachedScaleForStroking = [scaleX, scaleY];
7215 }
7216 return this._cachedScaleForStroking;
7217 }
7218 rescaleAndStroke(saveRestore) {
7219 const {
7220 ctx
7221 } = this;
7222 const {
7223 lineWidth
7224 } = this.current;
7225 const [scaleX, scaleY] = this.getScaleForStroking();
7226 ctx.lineWidth = lineWidth || 1;
7227 if (scaleX === 1 && scaleY === 1) {
7228 ctx.stroke();
7229 return;
7230 }
7231 let savedMatrix, savedDashes, savedDashOffset;
7232 if (saveRestore) {
7233 savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
7234 savedDashes = ctx.getLineDash().slice();
7235 savedDashOffset = ctx.lineDashOffset;
7236 }
7237 ctx.scale(scaleX, scaleY);
7238 const scale = Math.max(scaleX, scaleY);
7239 ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
7240 ctx.lineDashOffset /= scale;
7241 ctx.stroke();
7242 if (saveRestore) {
7243 ctx.setTransform(...savedMatrix);
7244 ctx.setLineDash(savedDashes);
7245 ctx.lineDashOffset = savedDashOffset;
7246 }
7247 }
7248 isContentVisible() {
7249 for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
7250 if (!this.markedContentStack[i].visible) {
7251 return false;
7252 }
7253 }
7254 return true;
7255 }
7256}
7257exports.CanvasGraphics = CanvasGraphics;
7258for (const op in _util.OPS) {
7259 if (CanvasGraphics.prototype[op] !== undefined) {
7260 CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
7261 }
7262}
7263
7264/***/ }),
7265/* 12 */
7266/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7267
7268
7269
7270Object.defineProperty(exports, "__esModule", ({
7271 value: true
7272}));
7273exports.TilingPattern = exports.PathType = void 0;
7274exports.getShadingPattern = getShadingPattern;
7275var _util = __w_pdfjs_require__(1);
7276var _display_utils = __w_pdfjs_require__(6);
7277const PathType = {
7278 FILL: "Fill",
7279 STROKE: "Stroke",
7280 SHADING: "Shading"
7281};
7282exports.PathType = PathType;
7283function applyBoundingBox(ctx, bbox) {
7284 if (!bbox) {
7285 return;
7286 }
7287 const width = bbox[2] - bbox[0];
7288 const height = bbox[3] - bbox[1];
7289 const region = new Path2D();
7290 region.rect(bbox[0], bbox[1], width, height);
7291 ctx.clip(region);
7292}
7293class BaseShadingPattern {
7294 constructor() {
7295 if (this.constructor === BaseShadingPattern) {
7296 (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
7297 }
7298 }
7299 getPattern() {
7300 (0, _util.unreachable)("Abstract method `getPattern` called.");
7301 }
7302}
7303class RadialAxialShadingPattern extends BaseShadingPattern {
7304 constructor(IR) {
7305 super();
7306 this._type = IR[1];
7307 this._bbox = IR[2];
7308 this._colorStops = IR[3];
7309 this._p0 = IR[4];
7310 this._p1 = IR[5];
7311 this._r0 = IR[6];
7312 this._r1 = IR[7];
7313 this.matrix = null;
7314 }
7315 _createGradient(ctx) {
7316 let grad;
7317 if (this._type === "axial") {
7318 grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
7319 } else if (this._type === "radial") {
7320 grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
7321 }
7322 for (const colorStop of this._colorStops) {
7323 grad.addColorStop(colorStop[0], colorStop[1]);
7324 }
7325 return grad;
7326 }
7327 getPattern(ctx, owner, inverse, pathType) {
7328 let pattern;
7329 if (pathType === PathType.STROKE || pathType === PathType.FILL) {
7330 const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
7331 const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
7332 const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
7333 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
7334 const tmpCtx = tmpCanvas.context;
7335 tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7336 tmpCtx.beginPath();
7337 tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7338 tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
7339 inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
7340 tmpCtx.transform(...owner.baseTransform);
7341 if (this.matrix) {
7342 tmpCtx.transform(...this.matrix);
7343 }
7344 applyBoundingBox(tmpCtx, this._bbox);
7345 tmpCtx.fillStyle = this._createGradient(tmpCtx);
7346 tmpCtx.fill();
7347 pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
7348 const domMatrix = new DOMMatrix(inverse);
7349 pattern.setTransform(domMatrix);
7350 } else {
7351 applyBoundingBox(ctx, this._bbox);
7352 pattern = this._createGradient(ctx);
7353 }
7354 return pattern;
7355 }
7356}
7357function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
7358 const coords = context.coords,
7359 colors = context.colors;
7360 const bytes = data.data,
7361 rowSize = data.width * 4;
7362 let tmp;
7363 if (coords[p1 + 1] > coords[p2 + 1]) {
7364 tmp = p1;
7365 p1 = p2;
7366 p2 = tmp;
7367 tmp = c1;
7368 c1 = c2;
7369 c2 = tmp;
7370 }
7371 if (coords[p2 + 1] > coords[p3 + 1]) {
7372 tmp = p2;
7373 p2 = p3;
7374 p3 = tmp;
7375 tmp = c2;
7376 c2 = c3;
7377 c3 = tmp;
7378 }
7379 if (coords[p1 + 1] > coords[p2 + 1]) {
7380 tmp = p1;
7381 p1 = p2;
7382 p2 = tmp;
7383 tmp = c1;
7384 c1 = c2;
7385 c2 = tmp;
7386 }
7387 const x1 = (coords[p1] + context.offsetX) * context.scaleX;
7388 const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
7389 const x2 = (coords[p2] + context.offsetX) * context.scaleX;
7390 const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
7391 const x3 = (coords[p3] + context.offsetX) * context.scaleX;
7392 const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
7393 if (y1 >= y3) {
7394 return;
7395 }
7396 const c1r = colors[c1],
7397 c1g = colors[c1 + 1],
7398 c1b = colors[c1 + 2];
7399 const c2r = colors[c2],
7400 c2g = colors[c2 + 1],
7401 c2b = colors[c2 + 2];
7402 const c3r = colors[c3],
7403 c3g = colors[c3 + 1],
7404 c3b = colors[c3 + 2];
7405 const minY = Math.round(y1),
7406 maxY = Math.round(y3);
7407 let xa, car, cag, cab;
7408 let xb, cbr, cbg, cbb;
7409 for (let y = minY; y <= maxY; y++) {
7410 if (y < y2) {
7411 let k;
7412 if (y < y1) {
7413 k = 0;
7414 } else {
7415 k = (y1 - y) / (y1 - y2);
7416 }
7417 xa = x1 - (x1 - x2) * k;
7418 car = c1r - (c1r - c2r) * k;
7419 cag = c1g - (c1g - c2g) * k;
7420 cab = c1b - (c1b - c2b) * k;
7421 } else {
7422 let k;
7423 if (y > y3) {
7424 k = 1;
7425 } else if (y2 === y3) {
7426 k = 0;
7427 } else {
7428 k = (y2 - y) / (y2 - y3);
7429 }
7430 xa = x2 - (x2 - x3) * k;
7431 car = c2r - (c2r - c3r) * k;
7432 cag = c2g - (c2g - c3g) * k;
7433 cab = c2b - (c2b - c3b) * k;
7434 }
7435 let k;
7436 if (y < y1) {
7437 k = 0;
7438 } else if (y > y3) {
7439 k = 1;
7440 } else {
7441 k = (y1 - y) / (y1 - y3);
7442 }
7443 xb = x1 - (x1 - x3) * k;
7444 cbr = c1r - (c1r - c3r) * k;
7445 cbg = c1g - (c1g - c3g) * k;
7446 cbb = c1b - (c1b - c3b) * k;
7447 const x1_ = Math.round(Math.min(xa, xb));
7448 const x2_ = Math.round(Math.max(xa, xb));
7449 let j = rowSize * y + x1_ * 4;
7450 for (let x = x1_; x <= x2_; x++) {
7451 k = (xa - x) / (xa - xb);
7452 if (k < 0) {
7453 k = 0;
7454 } else if (k > 1) {
7455 k = 1;
7456 }
7457 bytes[j++] = car - (car - cbr) * k | 0;
7458 bytes[j++] = cag - (cag - cbg) * k | 0;
7459 bytes[j++] = cab - (cab - cbb) * k | 0;
7460 bytes[j++] = 255;
7461 }
7462 }
7463}
7464function drawFigure(data, figure, context) {
7465 const ps = figure.coords;
7466 const cs = figure.colors;
7467 let i, ii;
7468 switch (figure.type) {
7469 case "lattice":
7470 const verticesPerRow = figure.verticesPerRow;
7471 const rows = Math.floor(ps.length / verticesPerRow) - 1;
7472 const cols = verticesPerRow - 1;
7473 for (i = 0; i < rows; i++) {
7474 let q = i * verticesPerRow;
7475 for (let j = 0; j < cols; j++, q++) {
7476 drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
7477 drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
7478 }
7479 }
7480 break;
7481 case "triangles":
7482 for (i = 0, ii = ps.length; i < ii; i += 3) {
7483 drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
7484 }
7485 break;
7486 default:
7487 throw new Error("illegal figure");
7488 }
7489}
7490class MeshShadingPattern extends BaseShadingPattern {
7491 constructor(IR) {
7492 super();
7493 this._coords = IR[2];
7494 this._colors = IR[3];
7495 this._figures = IR[4];
7496 this._bounds = IR[5];
7497 this._bbox = IR[7];
7498 this._background = IR[8];
7499 this.matrix = null;
7500 }
7501 _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
7502 const EXPECTED_SCALE = 1.1;
7503 const MAX_PATTERN_SIZE = 3000;
7504 const BORDER_SIZE = 2;
7505 const offsetX = Math.floor(this._bounds[0]);
7506 const offsetY = Math.floor(this._bounds[1]);
7507 const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
7508 const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
7509 const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7510 const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7511 const scaleX = boundsWidth / width;
7512 const scaleY = boundsHeight / height;
7513 const context = {
7514 coords: this._coords,
7515 colors: this._colors,
7516 offsetX: -offsetX,
7517 offsetY: -offsetY,
7518 scaleX: 1 / scaleX,
7519 scaleY: 1 / scaleY
7520 };
7521 const paddedWidth = width + BORDER_SIZE * 2;
7522 const paddedHeight = height + BORDER_SIZE * 2;
7523 const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
7524 const tmpCtx = tmpCanvas.context;
7525 const data = tmpCtx.createImageData(width, height);
7526 if (backgroundColor) {
7527 const bytes = data.data;
7528 for (let i = 0, ii = bytes.length; i < ii; i += 4) {
7529 bytes[i] = backgroundColor[0];
7530 bytes[i + 1] = backgroundColor[1];
7531 bytes[i + 2] = backgroundColor[2];
7532 bytes[i + 3] = 255;
7533 }
7534 }
7535 for (const figure of this._figures) {
7536 drawFigure(data, figure, context);
7537 }
7538 tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
7539 const canvas = tmpCanvas.canvas;
7540 return {
7541 canvas,
7542 offsetX: offsetX - BORDER_SIZE * scaleX,
7543 offsetY: offsetY - BORDER_SIZE * scaleY,
7544 scaleX,
7545 scaleY
7546 };
7547 }
7548 getPattern(ctx, owner, inverse, pathType) {
7549 applyBoundingBox(ctx, this._bbox);
7550 let scale;
7551 if (pathType === PathType.SHADING) {
7552 scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
7553 } else {
7554 scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
7555 if (this.matrix) {
7556 const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7557 scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
7558 }
7559 }
7560 const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
7561 if (pathType !== PathType.SHADING) {
7562 ctx.setTransform(...owner.baseTransform);
7563 if (this.matrix) {
7564 ctx.transform(...this.matrix);
7565 }
7566 }
7567 ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
7568 ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
7569 return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
7570 }
7571}
7572class DummyShadingPattern extends BaseShadingPattern {
7573 getPattern() {
7574 return "hotpink";
7575 }
7576}
7577function getShadingPattern(IR) {
7578 switch (IR[0]) {
7579 case "RadialAxial":
7580 return new RadialAxialShadingPattern(IR);
7581 case "Mesh":
7582 return new MeshShadingPattern(IR);
7583 case "Dummy":
7584 return new DummyShadingPattern();
7585 }
7586 throw new Error(`Unknown IR type: ${IR[0]}`);
7587}
7588const PaintType = {
7589 COLORED: 1,
7590 UNCOLORED: 2
7591};
7592class TilingPattern {
7593 static get MAX_PATTERN_SIZE() {
7594 return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
7595 }
7596 constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
7597 this.operatorList = IR[2];
7598 this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
7599 this.bbox = IR[4];
7600 this.xstep = IR[5];
7601 this.ystep = IR[6];
7602 this.paintType = IR[7];
7603 this.tilingType = IR[8];
7604 this.color = color;
7605 this.ctx = ctx;
7606 this.canvasGraphicsFactory = canvasGraphicsFactory;
7607 this.baseTransform = baseTransform;
7608 }
7609 createPatternCanvas(owner) {
7610 const operatorList = this.operatorList;
7611 const bbox = this.bbox;
7612 const xstep = this.xstep;
7613 const ystep = this.ystep;
7614 const paintType = this.paintType;
7615 const tilingType = this.tilingType;
7616 const color = this.color;
7617 const canvasGraphicsFactory = this.canvasGraphicsFactory;
7618 (0, _util.info)("TilingType: " + tilingType);
7619 const x0 = bbox[0],
7620 y0 = bbox[1],
7621 x1 = bbox[2],
7622 y1 = bbox[3];
7623 const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7624 const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
7625 const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
7626 const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
7627 const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
7628 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
7629 const tmpCtx = tmpCanvas.context;
7630 const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
7631 graphics.groupLevel = owner.groupLevel;
7632 this.setFillAndStrokeStyleToContext(graphics, paintType, color);
7633 let adjustedX0 = x0;
7634 let adjustedY0 = y0;
7635 let adjustedX1 = x1;
7636 let adjustedY1 = y1;
7637 if (x0 < 0) {
7638 adjustedX0 = 0;
7639 adjustedX1 += Math.abs(x0);
7640 }
7641 if (y0 < 0) {
7642 adjustedY0 = 0;
7643 adjustedY1 += Math.abs(y0);
7644 }
7645 tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
7646 graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
7647 tmpCtx.save();
7648 this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
7649 graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
7650 graphics.executeOperatorList(operatorList);
7651 graphics.endDrawing();
7652 return {
7653 canvas: tmpCanvas.canvas,
7654 scaleX: dimx.scale,
7655 scaleY: dimy.scale,
7656 offsetX: adjustedX0,
7657 offsetY: adjustedY0
7658 };
7659 }
7660 getSizeAndScale(step, realOutputSize, scale) {
7661 step = Math.abs(step);
7662 const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
7663 let size = Math.ceil(step * scale);
7664 if (size >= maxSize) {
7665 size = maxSize;
7666 } else {
7667 scale = size / step;
7668 }
7669 return {
7670 scale,
7671 size
7672 };
7673 }
7674 clipBbox(graphics, x0, y0, x1, y1) {
7675 const bboxWidth = x1 - x0;
7676 const bboxHeight = y1 - y0;
7677 graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
7678 graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
7679 graphics.clip();
7680 graphics.endPath();
7681 }
7682 setFillAndStrokeStyleToContext(graphics, paintType, color) {
7683 const context = graphics.ctx,
7684 current = graphics.current;
7685 switch (paintType) {
7686 case PaintType.COLORED:
7687 const ctx = this.ctx;
7688 context.fillStyle = ctx.fillStyle;
7689 context.strokeStyle = ctx.strokeStyle;
7690 current.fillColor = ctx.fillStyle;
7691 current.strokeColor = ctx.strokeStyle;
7692 break;
7693 case PaintType.UNCOLORED:
7694 const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
7695 context.fillStyle = cssColor;
7696 context.strokeStyle = cssColor;
7697 current.fillColor = cssColor;
7698 current.strokeColor = cssColor;
7699 break;
7700 default:
7701 throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
7702 }
7703 }
7704 getPattern(ctx, owner, inverse, pathType) {
7705 let matrix = inverse;
7706 if (pathType !== PathType.SHADING) {
7707 matrix = _util.Util.transform(matrix, owner.baseTransform);
7708 if (this.matrix) {
7709 matrix = _util.Util.transform(matrix, this.matrix);
7710 }
7711 }
7712 const temporaryPatternCanvas = this.createPatternCanvas(owner);
7713 let domMatrix = new DOMMatrix(matrix);
7714 domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
7715 domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
7716 const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
7717 pattern.setTransform(domMatrix);
7718 return pattern;
7719 }
7720}
7721exports.TilingPattern = TilingPattern;
7722
7723/***/ }),
7724/* 13 */
7725/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7726
7727
7728
7729Object.defineProperty(exports, "__esModule", ({
7730 value: true
7731}));
7732exports.applyMaskImageData = applyMaskImageData;
7733var _util = __w_pdfjs_require__(1);
7734function applyMaskImageData({
7735 src,
7736 srcPos = 0,
7737 dest,
7738 destPos = 0,
7739 width,
7740 height,
7741 inverseDecode = false
7742}) {
7743 const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
7744 const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
7745 const widthInSource = width >> 3;
7746 const widthRemainder = width & 7;
7747 const srcLength = src.length;
7748 dest = new Uint32Array(dest.buffer);
7749 for (let i = 0; i < height; i++) {
7750 for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
7751 const elem = srcPos < srcLength ? src[srcPos] : 255;
7752 dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
7753 dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
7754 dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
7755 dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
7756 dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
7757 dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
7758 dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
7759 dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
7760 }
7761 if (widthRemainder === 0) {
7762 continue;
7763 }
7764 const elem = srcPos < srcLength ? src[srcPos++] : 255;
7765 for (let j = 0; j < widthRemainder; j++) {
7766 dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
7767 }
7768 }
7769 return {
7770 srcPos,
7771 destPos
7772 };
7773}
7774
7775/***/ }),
7776/* 14 */
7777/***/ ((__unused_webpack_module, exports) => {
7778
7779
7780
7781Object.defineProperty(exports, "__esModule", ({
7782 value: true
7783}));
7784exports.GlobalWorkerOptions = void 0;
7785const GlobalWorkerOptions = Object.create(null);
7786exports.GlobalWorkerOptions = GlobalWorkerOptions;
7787GlobalWorkerOptions.workerPort = null;
7788GlobalWorkerOptions.workerSrc = "";
7789
7790/***/ }),
7791/* 15 */
7792/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7793
7794
7795
7796Object.defineProperty(exports, "__esModule", ({
7797 value: true
7798}));
7799exports.MessageHandler = void 0;
7800var _util = __w_pdfjs_require__(1);
7801const CallbackKind = {
7802 UNKNOWN: 0,
7803 DATA: 1,
7804 ERROR: 2
7805};
7806const StreamKind = {
7807 UNKNOWN: 0,
7808 CANCEL: 1,
7809 CANCEL_COMPLETE: 2,
7810 CLOSE: 3,
7811 ENQUEUE: 4,
7812 ERROR: 5,
7813 PULL: 6,
7814 PULL_COMPLETE: 7,
7815 START_COMPLETE: 8
7816};
7817function wrapReason(reason) {
7818 if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
7819 (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
7820 }
7821 switch (reason.name) {
7822 case "AbortException":
7823 return new _util.AbortException(reason.message);
7824 case "MissingPDFException":
7825 return new _util.MissingPDFException(reason.message);
7826 case "PasswordException":
7827 return new _util.PasswordException(reason.message, reason.code);
7828 case "UnexpectedResponseException":
7829 return new _util.UnexpectedResponseException(reason.message, reason.status);
7830 case "UnknownErrorException":
7831 return new _util.UnknownErrorException(reason.message, reason.details);
7832 default:
7833 return new _util.UnknownErrorException(reason.message, reason.toString());
7834 }
7835}
7836class MessageHandler {
7837 constructor(sourceName, targetName, comObj) {
7838 this.sourceName = sourceName;
7839 this.targetName = targetName;
7840 this.comObj = comObj;
7841 this.callbackId = 1;
7842 this.streamId = 1;
7843 this.streamSinks = Object.create(null);
7844 this.streamControllers = Object.create(null);
7845 this.callbackCapabilities = Object.create(null);
7846 this.actionHandler = Object.create(null);
7847 this._onComObjOnMessage = event => {
7848 const data = event.data;
7849 if (data.targetName !== this.sourceName) {
7850 return;
7851 }
7852 if (data.stream) {
7853 this._processStreamMessage(data);
7854 return;
7855 }
7856 if (data.callback) {
7857 const callbackId = data.callbackId;
7858 const capability = this.callbackCapabilities[callbackId];
7859 if (!capability) {
7860 throw new Error(`Cannot resolve callback ${callbackId}`);
7861 }
7862 delete this.callbackCapabilities[callbackId];
7863 if (data.callback === CallbackKind.DATA) {
7864 capability.resolve(data.data);
7865 } else if (data.callback === CallbackKind.ERROR) {
7866 capability.reject(wrapReason(data.reason));
7867 } else {
7868 throw new Error("Unexpected callback case");
7869 }
7870 return;
7871 }
7872 const action = this.actionHandler[data.action];
7873 if (!action) {
7874 throw new Error(`Unknown action from worker: ${data.action}`);
7875 }
7876 if (data.callbackId) {
7877 const cbSourceName = this.sourceName;
7878 const cbTargetName = data.sourceName;
7879 new Promise(function (resolve) {
7880 resolve(action(data.data));
7881 }).then(function (result) {
7882 comObj.postMessage({
7883 sourceName: cbSourceName,
7884 targetName: cbTargetName,
7885 callback: CallbackKind.DATA,
7886 callbackId: data.callbackId,
7887 data: result
7888 });
7889 }, function (reason) {
7890 comObj.postMessage({
7891 sourceName: cbSourceName,
7892 targetName: cbTargetName,
7893 callback: CallbackKind.ERROR,
7894 callbackId: data.callbackId,
7895 reason: wrapReason(reason)
7896 });
7897 });
7898 return;
7899 }
7900 if (data.streamId) {
7901 this._createStreamSink(data);
7902 return;
7903 }
7904 action(data.data);
7905 };
7906 comObj.addEventListener("message", this._onComObjOnMessage);
7907 }
7908 on(actionName, handler) {
7909 const ah = this.actionHandler;
7910 if (ah[actionName]) {
7911 throw new Error(`There is already an actionName called "${actionName}"`);
7912 }
7913 ah[actionName] = handler;
7914 }
7915 send(actionName, data, transfers) {
7916 this.comObj.postMessage({
7917 sourceName: this.sourceName,
7918 targetName: this.targetName,
7919 action: actionName,
7920 data
7921 }, transfers);
7922 }
7923 sendWithPromise(actionName, data, transfers) {
7924 const callbackId = this.callbackId++;
7925 const capability = (0, _util.createPromiseCapability)();
7926 this.callbackCapabilities[callbackId] = capability;
7927 try {
7928 this.comObj.postMessage({
7929 sourceName: this.sourceName,
7930 targetName: this.targetName,
7931 action: actionName,
7932 callbackId,
7933 data
7934 }, transfers);
7935 } catch (ex) {
7936 capability.reject(ex);
7937 }
7938 return capability.promise;
7939 }
7940 sendWithStream(actionName, data, queueingStrategy, transfers) {
7941 const streamId = this.streamId++,
7942 sourceName = this.sourceName,
7943 targetName = this.targetName,
7944 comObj = this.comObj;
7945 return new ReadableStream({
7946 start: controller => {
7947 const startCapability = (0, _util.createPromiseCapability)();
7948 this.streamControllers[streamId] = {
7949 controller,
7950 startCall: startCapability,
7951 pullCall: null,
7952 cancelCall: null,
7953 isClosed: false
7954 };
7955 comObj.postMessage({
7956 sourceName,
7957 targetName,
7958 action: actionName,
7959 streamId,
7960 data,
7961 desiredSize: controller.desiredSize
7962 }, transfers);
7963 return startCapability.promise;
7964 },
7965 pull: controller => {
7966 const pullCapability = (0, _util.createPromiseCapability)();
7967 this.streamControllers[streamId].pullCall = pullCapability;
7968 comObj.postMessage({
7969 sourceName,
7970 targetName,
7971 stream: StreamKind.PULL,
7972 streamId,
7973 desiredSize: controller.desiredSize
7974 });
7975 return pullCapability.promise;
7976 },
7977 cancel: reason => {
7978 (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
7979 const cancelCapability = (0, _util.createPromiseCapability)();
7980 this.streamControllers[streamId].cancelCall = cancelCapability;
7981 this.streamControllers[streamId].isClosed = true;
7982 comObj.postMessage({
7983 sourceName,
7984 targetName,
7985 stream: StreamKind.CANCEL,
7986 streamId,
7987 reason: wrapReason(reason)
7988 });
7989 return cancelCapability.promise;
7990 }
7991 }, queueingStrategy);
7992 }
7993 _createStreamSink(data) {
7994 const streamId = data.streamId,
7995 sourceName = this.sourceName,
7996 targetName = data.sourceName,
7997 comObj = this.comObj;
7998 const self = this,
7999 action = this.actionHandler[data.action];
8000 const streamSink = {
8001 enqueue(chunk, size = 1, transfers) {
8002 if (this.isCancelled) {
8003 return;
8004 }
8005 const lastDesiredSize = this.desiredSize;
8006 this.desiredSize -= size;
8007 if (lastDesiredSize > 0 && this.desiredSize <= 0) {
8008 this.sinkCapability = (0, _util.createPromiseCapability)();
8009 this.ready = this.sinkCapability.promise;
8010 }
8011 comObj.postMessage({
8012 sourceName,
8013 targetName,
8014 stream: StreamKind.ENQUEUE,
8015 streamId,
8016 chunk
8017 }, transfers);
8018 },
8019 close() {
8020 if (this.isCancelled) {
8021 return;
8022 }
8023 this.isCancelled = true;
8024 comObj.postMessage({
8025 sourceName,
8026 targetName,
8027 stream: StreamKind.CLOSE,
8028 streamId
8029 });
8030 delete self.streamSinks[streamId];
8031 },
8032 error(reason) {
8033 (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
8034 if (this.isCancelled) {
8035 return;
8036 }
8037 this.isCancelled = true;
8038 comObj.postMessage({
8039 sourceName,
8040 targetName,
8041 stream: StreamKind.ERROR,
8042 streamId,
8043 reason: wrapReason(reason)
8044 });
8045 },
8046 sinkCapability: (0, _util.createPromiseCapability)(),
8047 onPull: null,
8048 onCancel: null,
8049 isCancelled: false,
8050 desiredSize: data.desiredSize,
8051 ready: null
8052 };
8053 streamSink.sinkCapability.resolve();
8054 streamSink.ready = streamSink.sinkCapability.promise;
8055 this.streamSinks[streamId] = streamSink;
8056 new Promise(function (resolve) {
8057 resolve(action(data.data, streamSink));
8058 }).then(function () {
8059 comObj.postMessage({
8060 sourceName,
8061 targetName,
8062 stream: StreamKind.START_COMPLETE,
8063 streamId,
8064 success: true
8065 });
8066 }, function (reason) {
8067 comObj.postMessage({
8068 sourceName,
8069 targetName,
8070 stream: StreamKind.START_COMPLETE,
8071 streamId,
8072 reason: wrapReason(reason)
8073 });
8074 });
8075 }
8076 _processStreamMessage(data) {
8077 const streamId = data.streamId,
8078 sourceName = this.sourceName,
8079 targetName = data.sourceName,
8080 comObj = this.comObj;
8081 const streamController = this.streamControllers[streamId],
8082 streamSink = this.streamSinks[streamId];
8083 switch (data.stream) {
8084 case StreamKind.START_COMPLETE:
8085 if (data.success) {
8086 streamController.startCall.resolve();
8087 } else {
8088 streamController.startCall.reject(wrapReason(data.reason));
8089 }
8090 break;
8091 case StreamKind.PULL_COMPLETE:
8092 if (data.success) {
8093 streamController.pullCall.resolve();
8094 } else {
8095 streamController.pullCall.reject(wrapReason(data.reason));
8096 }
8097 break;
8098 case StreamKind.PULL:
8099 if (!streamSink) {
8100 comObj.postMessage({
8101 sourceName,
8102 targetName,
8103 stream: StreamKind.PULL_COMPLETE,
8104 streamId,
8105 success: true
8106 });
8107 break;
8108 }
8109 if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
8110 streamSink.sinkCapability.resolve();
8111 }
8112 streamSink.desiredSize = data.desiredSize;
8113 new Promise(function (resolve) {
8114 resolve(streamSink.onPull && streamSink.onPull());
8115 }).then(function () {
8116 comObj.postMessage({
8117 sourceName,
8118 targetName,
8119 stream: StreamKind.PULL_COMPLETE,
8120 streamId,
8121 success: true
8122 });
8123 }, function (reason) {
8124 comObj.postMessage({
8125 sourceName,
8126 targetName,
8127 stream: StreamKind.PULL_COMPLETE,
8128 streamId,
8129 reason: wrapReason(reason)
8130 });
8131 });
8132 break;
8133 case StreamKind.ENQUEUE:
8134 (0, _util.assert)(streamController, "enqueue should have stream controller");
8135 if (streamController.isClosed) {
8136 break;
8137 }
8138 streamController.controller.enqueue(data.chunk);
8139 break;
8140 case StreamKind.CLOSE:
8141 (0, _util.assert)(streamController, "close should have stream controller");
8142 if (streamController.isClosed) {
8143 break;
8144 }
8145 streamController.isClosed = true;
8146 streamController.controller.close();
8147 this._deleteStreamController(streamController, streamId);
8148 break;
8149 case StreamKind.ERROR:
8150 (0, _util.assert)(streamController, "error should have stream controller");
8151 streamController.controller.error(wrapReason(data.reason));
8152 this._deleteStreamController(streamController, streamId);
8153 break;
8154 case StreamKind.CANCEL_COMPLETE:
8155 if (data.success) {
8156 streamController.cancelCall.resolve();
8157 } else {
8158 streamController.cancelCall.reject(wrapReason(data.reason));
8159 }
8160 this._deleteStreamController(streamController, streamId);
8161 break;
8162 case StreamKind.CANCEL:
8163 if (!streamSink) {
8164 break;
8165 }
8166 new Promise(function (resolve) {
8167 resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
8168 }).then(function () {
8169 comObj.postMessage({
8170 sourceName,
8171 targetName,
8172 stream: StreamKind.CANCEL_COMPLETE,
8173 streamId,
8174 success: true
8175 });
8176 }, function (reason) {
8177 comObj.postMessage({
8178 sourceName,
8179 targetName,
8180 stream: StreamKind.CANCEL_COMPLETE,
8181 streamId,
8182 reason: wrapReason(reason)
8183 });
8184 });
8185 streamSink.sinkCapability.reject(wrapReason(data.reason));
8186 streamSink.isCancelled = true;
8187 delete this.streamSinks[streamId];
8188 break;
8189 default:
8190 throw new Error("Unexpected stream case");
8191 }
8192 }
8193 async _deleteStreamController(streamController, streamId) {
8194 await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
8195 delete this.streamControllers[streamId];
8196 }
8197 destroy() {
8198 this.comObj.removeEventListener("message", this._onComObjOnMessage);
8199 }
8200}
8201exports.MessageHandler = MessageHandler;
8202
8203/***/ }),
8204/* 16 */
8205/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8206
8207
8208
8209Object.defineProperty(exports, "__esModule", ({
8210 value: true
8211}));
8212exports.Metadata = void 0;
8213var _util = __w_pdfjs_require__(1);
8214class Metadata {
8215 #metadataMap;
8216 #data;
8217 constructor({
8218 parsedData,
8219 rawData
8220 }) {
8221 this.#metadataMap = parsedData;
8222 this.#data = rawData;
8223 }
8224 getRaw() {
8225 return this.#data;
8226 }
8227 get(name) {
8228 return this.#metadataMap.get(name) ?? null;
8229 }
8230 getAll() {
8231 return (0, _util.objectFromMap)(this.#metadataMap);
8232 }
8233 has(name) {
8234 return this.#metadataMap.has(name);
8235 }
8236}
8237exports.Metadata = Metadata;
8238
8239/***/ }),
8240/* 17 */
8241/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8242
8243
8244
8245Object.defineProperty(exports, "__esModule", ({
8246 value: true
8247}));
8248exports.OptionalContentConfig = void 0;
8249var _util = __w_pdfjs_require__(1);
8250var _murmurhash = __w_pdfjs_require__(8);
8251const INTERNAL = Symbol("INTERNAL");
8252class OptionalContentGroup {
8253 #visible = true;
8254 constructor(name, intent) {
8255 this.name = name;
8256 this.intent = intent;
8257 }
8258 get visible() {
8259 return this.#visible;
8260 }
8261 _setVisible(internal, visible) {
8262 if (internal !== INTERNAL) {
8263 (0, _util.unreachable)("Internal method `_setVisible` called.");
8264 }
8265 this.#visible = visible;
8266 }
8267}
8268class OptionalContentConfig {
8269 #cachedGetHash = null;
8270 #groups = new Map();
8271 #initialHash = null;
8272 #order = null;
8273 constructor(data) {
8274 this.name = null;
8275 this.creator = null;
8276 if (data === null) {
8277 return;
8278 }
8279 this.name = data.name;
8280 this.creator = data.creator;
8281 this.#order = data.order;
8282 for (const group of data.groups) {
8283 this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
8284 }
8285 if (data.baseState === "OFF") {
8286 for (const group of this.#groups.values()) {
8287 group._setVisible(INTERNAL, false);
8288 }
8289 }
8290 for (const on of data.on) {
8291 this.#groups.get(on)._setVisible(INTERNAL, true);
8292 }
8293 for (const off of data.off) {
8294 this.#groups.get(off)._setVisible(INTERNAL, false);
8295 }
8296 this.#initialHash = this.getHash();
8297 }
8298 #evaluateVisibilityExpression(array) {
8299 const length = array.length;
8300 if (length < 2) {
8301 return true;
8302 }
8303 const operator = array[0];
8304 for (let i = 1; i < length; i++) {
8305 const element = array[i];
8306 let state;
8307 if (Array.isArray(element)) {
8308 state = this.#evaluateVisibilityExpression(element);
8309 } else if (this.#groups.has(element)) {
8310 state = this.#groups.get(element).visible;
8311 } else {
8312 (0, _util.warn)(`Optional content group not found: ${element}`);
8313 return true;
8314 }
8315 switch (operator) {
8316 case "And":
8317 if (!state) {
8318 return false;
8319 }
8320 break;
8321 case "Or":
8322 if (state) {
8323 return true;
8324 }
8325 break;
8326 case "Not":
8327 return !state;
8328 default:
8329 return true;
8330 }
8331 }
8332 return operator === "And";
8333 }
8334 isVisible(group) {
8335 if (this.#groups.size === 0) {
8336 return true;
8337 }
8338 if (!group) {
8339 (0, _util.warn)("Optional content group not defined.");
8340 return true;
8341 }
8342 if (group.type === "OCG") {
8343 if (!this.#groups.has(group.id)) {
8344 (0, _util.warn)(`Optional content group not found: ${group.id}`);
8345 return true;
8346 }
8347 return this.#groups.get(group.id).visible;
8348 } else if (group.type === "OCMD") {
8349 if (group.expression) {
8350 return this.#evaluateVisibilityExpression(group.expression);
8351 }
8352 if (!group.policy || group.policy === "AnyOn") {
8353 for (const id of group.ids) {
8354 if (!this.#groups.has(id)) {
8355 (0, _util.warn)(`Optional content group not found: ${id}`);
8356 return true;
8357 }
8358 if (this.#groups.get(id).visible) {
8359 return true;
8360 }
8361 }
8362 return false;
8363 } else if (group.policy === "AllOn") {
8364 for (const id of group.ids) {
8365 if (!this.#groups.has(id)) {
8366 (0, _util.warn)(`Optional content group not found: ${id}`);
8367 return true;
8368 }
8369 if (!this.#groups.get(id).visible) {
8370 return false;
8371 }
8372 }
8373 return true;
8374 } else if (group.policy === "AnyOff") {
8375 for (const id of group.ids) {
8376 if (!this.#groups.has(id)) {
8377 (0, _util.warn)(`Optional content group not found: ${id}`);
8378 return true;
8379 }
8380 if (!this.#groups.get(id).visible) {
8381 return true;
8382 }
8383 }
8384 return false;
8385 } else if (group.policy === "AllOff") {
8386 for (const id of group.ids) {
8387 if (!this.#groups.has(id)) {
8388 (0, _util.warn)(`Optional content group not found: ${id}`);
8389 return true;
8390 }
8391 if (this.#groups.get(id).visible) {
8392 return false;
8393 }
8394 }
8395 return true;
8396 }
8397 (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
8398 return true;
8399 }
8400 (0, _util.warn)(`Unknown group type ${group.type}.`);
8401 return true;
8402 }
8403 setVisibility(id, visible = true) {
8404 if (!this.#groups.has(id)) {
8405 (0, _util.warn)(`Optional content group not found: ${id}`);
8406 return;
8407 }
8408 this.#groups.get(id)._setVisible(INTERNAL, !!visible);
8409 this.#cachedGetHash = null;
8410 }
8411 get hasInitialVisibility() {
8412 return this.getHash() === this.#initialHash;
8413 }
8414 getOrder() {
8415 if (!this.#groups.size) {
8416 return null;
8417 }
8418 if (this.#order) {
8419 return this.#order.slice();
8420 }
8421 return [...this.#groups.keys()];
8422 }
8423 getGroups() {
8424 return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
8425 }
8426 getGroup(id) {
8427 return this.#groups.get(id) || null;
8428 }
8429 getHash() {
8430 if (this.#cachedGetHash !== null) {
8431 return this.#cachedGetHash;
8432 }
8433 const hash = new _murmurhash.MurmurHash3_64();
8434 for (const [id, group] of this.#groups) {
8435 hash.update(`${id}:${group.visible}`);
8436 }
8437 return this.#cachedGetHash = hash.hexdigest();
8438 }
8439}
8440exports.OptionalContentConfig = OptionalContentConfig;
8441
8442/***/ }),
8443/* 18 */
8444/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8445
8446
8447
8448Object.defineProperty(exports, "__esModule", ({
8449 value: true
8450}));
8451exports.PDFDataTransportStream = void 0;
8452var _util = __w_pdfjs_require__(1);
8453var _display_utils = __w_pdfjs_require__(6);
8454class PDFDataTransportStream {
8455 constructor({
8456 length,
8457 initialData,
8458 progressiveDone = false,
8459 contentDispositionFilename = null,
8460 disableRange = false,
8461 disableStream = false
8462 }, pdfDataRangeTransport) {
8463 (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
8464 this._queuedChunks = [];
8465 this._progressiveDone = progressiveDone;
8466 this._contentDispositionFilename = contentDispositionFilename;
8467 if (initialData?.length > 0) {
8468 const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
8469 this._queuedChunks.push(buffer);
8470 }
8471 this._pdfDataRangeTransport = pdfDataRangeTransport;
8472 this._isStreamingSupported = !disableStream;
8473 this._isRangeSupported = !disableRange;
8474 this._contentLength = length;
8475 this._fullRequestReader = null;
8476 this._rangeReaders = [];
8477 this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
8478 this._onReceiveData({
8479 begin,
8480 chunk
8481 });
8482 });
8483 this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
8484 this._onProgress({
8485 loaded,
8486 total
8487 });
8488 });
8489 this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
8490 this._onReceiveData({
8491 chunk
8492 });
8493 });
8494 this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
8495 this._onProgressiveDone();
8496 });
8497 this._pdfDataRangeTransport.transportReady();
8498 }
8499 _onReceiveData({
8500 begin,
8501 chunk
8502 }) {
8503 const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
8504 if (begin === undefined) {
8505 if (this._fullRequestReader) {
8506 this._fullRequestReader._enqueue(buffer);
8507 } else {
8508 this._queuedChunks.push(buffer);
8509 }
8510 } else {
8511 const found = this._rangeReaders.some(function (rangeReader) {
8512 if (rangeReader._begin !== begin) {
8513 return false;
8514 }
8515 rangeReader._enqueue(buffer);
8516 return true;
8517 });
8518 (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
8519 }
8520 }
8521 get _progressiveDataLength() {
8522 return this._fullRequestReader?._loaded ?? 0;
8523 }
8524 _onProgress(evt) {
8525 if (evt.total === undefined) {
8526 this._rangeReaders[0]?.onProgress?.({
8527 loaded: evt.loaded
8528 });
8529 } else {
8530 this._fullRequestReader?.onProgress?.({
8531 loaded: evt.loaded,
8532 total: evt.total
8533 });
8534 }
8535 }
8536 _onProgressiveDone() {
8537 this._fullRequestReader?.progressiveDone();
8538 this._progressiveDone = true;
8539 }
8540 _removeRangeReader(reader) {
8541 const i = this._rangeReaders.indexOf(reader);
8542 if (i >= 0) {
8543 this._rangeReaders.splice(i, 1);
8544 }
8545 }
8546 getFullReader() {
8547 (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
8548 const queuedChunks = this._queuedChunks;
8549 this._queuedChunks = null;
8550 return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
8551 }
8552 getRangeReader(begin, end) {
8553 if (end <= this._progressiveDataLength) {
8554 return null;
8555 }
8556 const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
8557 this._pdfDataRangeTransport.requestDataRange(begin, end);
8558 this._rangeReaders.push(reader);
8559 return reader;
8560 }
8561 cancelAllRequests(reason) {
8562 this._fullRequestReader?.cancel(reason);
8563 for (const reader of this._rangeReaders.slice(0)) {
8564 reader.cancel(reason);
8565 }
8566 this._pdfDataRangeTransport.abort();
8567 }
8568}
8569exports.PDFDataTransportStream = PDFDataTransportStream;
8570class PDFDataTransportStreamReader {
8571 constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
8572 this._stream = stream;
8573 this._done = progressiveDone || false;
8574 this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
8575 this._queuedChunks = queuedChunks || [];
8576 this._loaded = 0;
8577 for (const chunk of this._queuedChunks) {
8578 this._loaded += chunk.byteLength;
8579 }
8580 this._requests = [];
8581 this._headersReady = Promise.resolve();
8582 stream._fullRequestReader = this;
8583 this.onProgress = null;
8584 }
8585 _enqueue(chunk) {
8586 if (this._done) {
8587 return;
8588 }
8589 if (this._requests.length > 0) {
8590 const requestCapability = this._requests.shift();
8591 requestCapability.resolve({
8592 value: chunk,
8593 done: false
8594 });
8595 } else {
8596 this._queuedChunks.push(chunk);
8597 }
8598 this._loaded += chunk.byteLength;
8599 }
8600 get headersReady() {
8601 return this._headersReady;
8602 }
8603 get filename() {
8604 return this._filename;
8605 }
8606 get isRangeSupported() {
8607 return this._stream._isRangeSupported;
8608 }
8609 get isStreamingSupported() {
8610 return this._stream._isStreamingSupported;
8611 }
8612 get contentLength() {
8613 return this._stream._contentLength;
8614 }
8615 async read() {
8616 if (this._queuedChunks.length > 0) {
8617 const chunk = this._queuedChunks.shift();
8618 return {
8619 value: chunk,
8620 done: false
8621 };
8622 }
8623 if (this._done) {
8624 return {
8625 value: undefined,
8626 done: true
8627 };
8628 }
8629 const requestCapability = (0, _util.createPromiseCapability)();
8630 this._requests.push(requestCapability);
8631 return requestCapability.promise;
8632 }
8633 cancel(reason) {
8634 this._done = true;
8635 for (const requestCapability of this._requests) {
8636 requestCapability.resolve({
8637 value: undefined,
8638 done: true
8639 });
8640 }
8641 this._requests.length = 0;
8642 }
8643 progressiveDone() {
8644 if (this._done) {
8645 return;
8646 }
8647 this._done = true;
8648 }
8649}
8650class PDFDataTransportStreamRangeReader {
8651 constructor(stream, begin, end) {
8652 this._stream = stream;
8653 this._begin = begin;
8654 this._end = end;
8655 this._queuedChunk = null;
8656 this._requests = [];
8657 this._done = false;
8658 this.onProgress = null;
8659 }
8660 _enqueue(chunk) {
8661 if (this._done) {
8662 return;
8663 }
8664 if (this._requests.length === 0) {
8665 this._queuedChunk = chunk;
8666 } else {
8667 const requestsCapability = this._requests.shift();
8668 requestsCapability.resolve({
8669 value: chunk,
8670 done: false
8671 });
8672 for (const requestCapability of this._requests) {
8673 requestCapability.resolve({
8674 value: undefined,
8675 done: true
8676 });
8677 }
8678 this._requests.length = 0;
8679 }
8680 this._done = true;
8681 this._stream._removeRangeReader(this);
8682 }
8683 get isStreamingSupported() {
8684 return false;
8685 }
8686 async read() {
8687 if (this._queuedChunk) {
8688 const chunk = this._queuedChunk;
8689 this._queuedChunk = null;
8690 return {
8691 value: chunk,
8692 done: false
8693 };
8694 }
8695 if (this._done) {
8696 return {
8697 value: undefined,
8698 done: true
8699 };
8700 }
8701 const requestCapability = (0, _util.createPromiseCapability)();
8702 this._requests.push(requestCapability);
8703 return requestCapability.promise;
8704 }
8705 cancel(reason) {
8706 this._done = true;
8707 for (const requestCapability of this._requests) {
8708 requestCapability.resolve({
8709 value: undefined,
8710 done: true
8711 });
8712 }
8713 this._requests.length = 0;
8714 this._stream._removeRangeReader(this);
8715 }
8716}
8717
8718/***/ }),
8719/* 19 */
8720/***/ ((__unused_webpack_module, exports) => {
8721
8722
8723
8724Object.defineProperty(exports, "__esModule", ({
8725 value: true
8726}));
8727exports.XfaText = void 0;
8728class XfaText {
8729 static textContent(xfa) {
8730 const items = [];
8731 const output = {
8732 items,
8733 styles: Object.create(null)
8734 };
8735 function walk(node) {
8736 if (!node) {
8737 return;
8738 }
8739 let str = null;
8740 const name = node.name;
8741 if (name === "#text") {
8742 str = node.value;
8743 } else if (!XfaText.shouldBuildText(name)) {
8744 return;
8745 } else if (node?.attributes?.textContent) {
8746 str = node.attributes.textContent;
8747 } else if (node.value) {
8748 str = node.value;
8749 }
8750 if (str !== null) {
8751 items.push({
8752 str
8753 });
8754 }
8755 if (!node.children) {
8756 return;
8757 }
8758 for (const child of node.children) {
8759 walk(child);
8760 }
8761 }
8762 walk(xfa);
8763 return output;
8764 }
8765 static shouldBuildText(name) {
8766 return !(name === "textarea" || name === "input" || name === "option" || name === "select");
8767 }
8768}
8769exports.XfaText = XfaText;
8770
8771/***/ }),
8772/* 20 */
8773/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8774
8775
8776
8777Object.defineProperty(exports, "__esModule", ({
8778 value: true
8779}));
8780exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
8781var _base_factory = __w_pdfjs_require__(7);
8782;
8783const fetchData = function (url) {
8784 return new Promise((resolve, reject) => {
8785 const fs = require("fs");
8786 fs.readFile(url, (error, data) => {
8787 if (error || !data) {
8788 reject(new Error(error));
8789 return;
8790 }
8791 resolve(new Uint8Array(data));
8792 });
8793 });
8794};
8795class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
8796 _createCanvas(width, height) {
8797 const Canvas = require("canvas");
8798 return Canvas.createCanvas(width, height);
8799 }
8800}
8801exports.NodeCanvasFactory = NodeCanvasFactory;
8802class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
8803 _fetchData(url, compressionType) {
8804 return fetchData(url).then(data => {
8805 return {
8806 cMapData: data,
8807 compressionType
8808 };
8809 });
8810 }
8811}
8812exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
8813class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
8814 _fetchData(url) {
8815 return fetchData(url);
8816 }
8817}
8818exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
8819
8820/***/ }),
8821/* 21 */
8822/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8823
8824
8825
8826Object.defineProperty(exports, "__esModule", ({
8827 value: true
8828}));
8829exports.PDFNodeStream = void 0;
8830var _util = __w_pdfjs_require__(1);
8831var _network_utils = __w_pdfjs_require__(22);
8832;
8833const fs = require("fs");
8834const http = require("http");
8835const https = require("https");
8836const url = require("url");
8837const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
8838function parseUrl(sourceUrl) {
8839 const parsedUrl = url.parse(sourceUrl);
8840 if (parsedUrl.protocol === "file:" || parsedUrl.host) {
8841 return parsedUrl;
8842 }
8843 if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
8844 return url.parse(`file:///${sourceUrl}`);
8845 }
8846 if (!parsedUrl.host) {
8847 parsedUrl.protocol = "file:";
8848 }
8849 return parsedUrl;
8850}
8851class PDFNodeStream {
8852 constructor(source) {
8853 this.source = source;
8854 this.url = parseUrl(source.url);
8855 this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:" || this.url.protocol === "capacitor:";
8856 this.isFsUrl = this.url.protocol === "file:";
8857 this.httpHeaders = this.isHttp && source.httpHeaders || {};
8858 this._fullRequestReader = null;
8859 this._rangeRequestReaders = [];
8860 }
8861 get _progressiveDataLength() {
8862 return this._fullRequestReader?._loaded ?? 0;
8863 }
8864 getFullReader() {
8865 (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
8866 this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
8867 return this._fullRequestReader;
8868 }
8869 getRangeReader(start, end) {
8870 if (end <= this._progressiveDataLength) {
8871 return null;
8872 }
8873 const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
8874 this._rangeRequestReaders.push(rangeReader);
8875 return rangeReader;
8876 }
8877 cancelAllRequests(reason) {
8878 this._fullRequestReader?.cancel(reason);
8879 for (const reader of this._rangeRequestReaders.slice(0)) {
8880 reader.cancel(reason);
8881 }
8882 }
8883}
8884exports.PDFNodeStream = PDFNodeStream;
8885class BaseFullReader {
8886 constructor(stream) {
8887 this._url = stream.url;
8888 this._done = false;
8889 this._storedError = null;
8890 this.onProgress = null;
8891 const source = stream.source;
8892 this._contentLength = source.length;
8893 this._loaded = 0;
8894 this._filename = null;
8895 this._disableRange = source.disableRange || false;
8896 this._rangeChunkSize = source.rangeChunkSize;
8897 if (!this._rangeChunkSize && !this._disableRange) {
8898 this._disableRange = true;
8899 }
8900 this._isStreamingSupported = !source.disableStream;
8901 this._isRangeSupported = !source.disableRange;
8902 this._readableStream = null;
8903 this._readCapability = (0, _util.createPromiseCapability)();
8904 this._headersCapability = (0, _util.createPromiseCapability)();
8905 }
8906 get headersReady() {
8907 return this._headersCapability.promise;
8908 }
8909 get filename() {
8910 return this._filename;
8911 }
8912 get contentLength() {
8913 return this._contentLength;
8914 }
8915 get isRangeSupported() {
8916 return this._isRangeSupported;
8917 }
8918 get isStreamingSupported() {
8919 return this._isStreamingSupported;
8920 }
8921 async read() {
8922 await this._readCapability.promise;
8923 if (this._done) {
8924 return {
8925 value: undefined,
8926 done: true
8927 };
8928 }
8929 if (this._storedError) {
8930 throw this._storedError;
8931 }
8932 const chunk = this._readableStream.read();
8933 if (chunk === null) {
8934 this._readCapability = (0, _util.createPromiseCapability)();
8935 return this.read();
8936 }
8937 this._loaded += chunk.length;
8938 this.onProgress?.({
8939 loaded: this._loaded,
8940 total: this._contentLength
8941 });
8942 const buffer = new Uint8Array(chunk).buffer;
8943 return {
8944 value: buffer,
8945 done: false
8946 };
8947 }
8948 cancel(reason) {
8949 if (!this._readableStream) {
8950 this._error(reason);
8951 return;
8952 }
8953 this._readableStream.destroy(reason);
8954 }
8955 _error(reason) {
8956 this._storedError = reason;
8957 this._readCapability.resolve();
8958 }
8959 _setReadableStream(readableStream) {
8960 this._readableStream = readableStream;
8961 readableStream.on("readable", () => {
8962 this._readCapability.resolve();
8963 });
8964 readableStream.on("end", () => {
8965 readableStream.destroy();
8966 this._done = true;
8967 this._readCapability.resolve();
8968 });
8969 readableStream.on("error", reason => {
8970 this._error(reason);
8971 });
8972 if (!this._isStreamingSupported && this._isRangeSupported) {
8973 this._error(new _util.AbortException("streaming is disabled"));
8974 }
8975 if (this._storedError) {
8976 this._readableStream.destroy(this._storedError);
8977 }
8978 }
8979}
8980class BaseRangeReader {
8981 constructor(stream) {
8982 this._url = stream.url;
8983 this._done = false;
8984 this._storedError = null;
8985 this.onProgress = null;
8986 this._loaded = 0;
8987 this._readableStream = null;
8988 this._readCapability = (0, _util.createPromiseCapability)();
8989 const source = stream.source;
8990 this._isStreamingSupported = !source.disableStream;
8991 }
8992 get isStreamingSupported() {
8993 return this._isStreamingSupported;
8994 }
8995 async read() {
8996 await this._readCapability.promise;
8997 if (this._done) {
8998 return {
8999 value: undefined,
9000 done: true
9001 };
9002 }
9003 if (this._storedError) {
9004 throw this._storedError;
9005 }
9006 const chunk = this._readableStream.read();
9007 if (chunk === null) {
9008 this._readCapability = (0, _util.createPromiseCapability)();
9009 return this.read();
9010 }
9011 this._loaded += chunk.length;
9012 this.onProgress?.({
9013 loaded: this._loaded
9014 });
9015 const buffer = new Uint8Array(chunk).buffer;
9016 return {
9017 value: buffer,
9018 done: false
9019 };
9020 }
9021 cancel(reason) {
9022 if (!this._readableStream) {
9023 this._error(reason);
9024 return;
9025 }
9026 this._readableStream.destroy(reason);
9027 }
9028 _error(reason) {
9029 this._storedError = reason;
9030 this._readCapability.resolve();
9031 }
9032 _setReadableStream(readableStream) {
9033 this._readableStream = readableStream;
9034 readableStream.on("readable", () => {
9035 this._readCapability.resolve();
9036 });
9037 readableStream.on("end", () => {
9038 readableStream.destroy();
9039 this._done = true;
9040 this._readCapability.resolve();
9041 });
9042 readableStream.on("error", reason => {
9043 this._error(reason);
9044 });
9045 if (this._storedError) {
9046 this._readableStream.destroy(this._storedError);
9047 }
9048 }
9049}
9050function createRequestOptions(parsedUrl, headers) {
9051 return {
9052 protocol: parsedUrl.protocol,
9053 auth: parsedUrl.auth,
9054 host: parsedUrl.hostname,
9055 port: parsedUrl.port,
9056 path: parsedUrl.path,
9057 method: "GET",
9058 headers
9059 };
9060}
9061class PDFNodeStreamFullReader extends BaseFullReader {
9062 constructor(stream) {
9063 super(stream);
9064 const handleResponse = response => {
9065 if (response.statusCode === 404) {
9066 const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
9067 this._storedError = error;
9068 this._headersCapability.reject(error);
9069 return;
9070 }
9071 this._headersCapability.resolve();
9072 this._setReadableStream(response);
9073 const getResponseHeader = name => {
9074 return this._readableStream.headers[name.toLowerCase()];
9075 };
9076 const {
9077 allowRangeRequests,
9078 suggestedLength
9079 } = (0, _network_utils.validateRangeRequestCapabilities)({
9080 getResponseHeader,
9081 isHttp: stream.isHttp,
9082 rangeChunkSize: this._rangeChunkSize,
9083 disableRange: this._disableRange
9084 });
9085 this._isRangeSupported = allowRangeRequests;
9086 this._contentLength = suggestedLength || this._contentLength;
9087 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
9088 };
9089 this._request = null;
9090 if (this._url.protocol === "http:") {
9091 this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
9092 } else {
9093 this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
9094 }
9095 this._request.on("error", reason => {
9096 this._storedError = reason;
9097 this._headersCapability.reject(reason);
9098 });
9099 this._request.end();
9100 }
9101}
9102class PDFNodeStreamRangeReader extends BaseRangeReader {
9103 constructor(stream, start, end) {
9104 super(stream);
9105 this._httpHeaders = {};
9106 for (const property in stream.httpHeaders) {
9107 const value = stream.httpHeaders[property];
9108 if (value === undefined) {
9109 continue;
9110 }
9111 this._httpHeaders[property] = value;
9112 }
9113 this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
9114 const handleResponse = response => {
9115 if (response.statusCode === 404) {
9116 const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
9117 this._storedError = error;
9118 return;
9119 }
9120 this._setReadableStream(response);
9121 };
9122 this._request = null;
9123 if (this._url.protocol === "http:") {
9124 this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
9125 } else {
9126 this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
9127 }
9128 this._request.on("error", reason => {
9129 this._storedError = reason;
9130 });
9131 this._request.end();
9132 }
9133}
9134class PDFNodeStreamFsFullReader extends BaseFullReader {
9135 constructor(stream) {
9136 super(stream);
9137 let path = decodeURIComponent(this._url.path);
9138 if (fileUriRegex.test(this._url.href)) {
9139 path = path.replace(/^\//, "");
9140 }
9141 fs.lstat(path, (error, stat) => {
9142 if (error) {
9143 if (error.code === "ENOENT") {
9144 error = new _util.MissingPDFException(`Missing PDF "${path}".`);
9145 }
9146 this._storedError = error;
9147 this._headersCapability.reject(error);
9148 return;
9149 }
9150 this._contentLength = stat.size;
9151 this._setReadableStream(fs.createReadStream(path));
9152 this._headersCapability.resolve();
9153 });
9154 }
9155}
9156class PDFNodeStreamFsRangeReader extends BaseRangeReader {
9157 constructor(stream, start, end) {
9158 super(stream);
9159 let path = decodeURIComponent(this._url.path);
9160 if (fileUriRegex.test(this._url.href)) {
9161 path = path.replace(/^\//, "");
9162 }
9163 this._setReadableStream(fs.createReadStream(path, {
9164 start,
9165 end: end - 1
9166 }));
9167 }
9168}
9169
9170/***/ }),
9171/* 22 */
9172/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9173
9174
9175
9176Object.defineProperty(exports, "__esModule", ({
9177 value: true
9178}));
9179exports.createResponseStatusError = createResponseStatusError;
9180exports.extractFilenameFromHeader = extractFilenameFromHeader;
9181exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
9182exports.validateResponseStatus = validateResponseStatus;
9183var _util = __w_pdfjs_require__(1);
9184var _content_disposition = __w_pdfjs_require__(23);
9185var _display_utils = __w_pdfjs_require__(6);
9186function validateRangeRequestCapabilities({
9187 getResponseHeader,
9188 isHttp,
9189 rangeChunkSize,
9190 disableRange
9191}) {
9192 const returnValues = {
9193 allowRangeRequests: false,
9194 suggestedLength: undefined
9195 };
9196 const length = parseInt(getResponseHeader("Content-Length"), 10);
9197 if (!Number.isInteger(length)) {
9198 return returnValues;
9199 }
9200 returnValues.suggestedLength = length;
9201 if (length <= 2 * rangeChunkSize) {
9202 return returnValues;
9203 }
9204 if (disableRange || !isHttp) {
9205 return returnValues;
9206 }
9207 if (getResponseHeader("Accept-Ranges") !== "bytes") {
9208 return returnValues;
9209 }
9210 const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
9211 if (contentEncoding !== "identity") {
9212 return returnValues;
9213 }
9214 returnValues.allowRangeRequests = true;
9215 return returnValues;
9216}
9217function extractFilenameFromHeader(getResponseHeader) {
9218 const contentDisposition = getResponseHeader("Content-Disposition");
9219 if (contentDisposition) {
9220 let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
9221 if (filename.includes("%")) {
9222 try {
9223 filename = decodeURIComponent(filename);
9224 } catch (ex) {}
9225 }
9226 if ((0, _display_utils.isPdfFile)(filename)) {
9227 return filename;
9228 }
9229 }
9230 return null;
9231}
9232function createResponseStatusError(status, url) {
9233 if (status === 404 || status === 0 && url.startsWith("file:")) {
9234 return new _util.MissingPDFException('Missing PDF "' + url + '".');
9235 }
9236 return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
9237}
9238function validateResponseStatus(status) {
9239 return status === 200 || status === 206;
9240}
9241
9242/***/ }),
9243/* 23 */
9244/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9245
9246
9247
9248Object.defineProperty(exports, "__esModule", ({
9249 value: true
9250}));
9251exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
9252var _util = __w_pdfjs_require__(1);
9253function getFilenameFromContentDispositionHeader(contentDisposition) {
9254 let needsEncodingFixup = true;
9255 let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
9256 if (tmp) {
9257 tmp = tmp[1];
9258 let filename = rfc2616unquote(tmp);
9259 filename = unescape(filename);
9260 filename = rfc5987decode(filename);
9261 filename = rfc2047decode(filename);
9262 return fixupEncoding(filename);
9263 }
9264 tmp = rfc2231getparam(contentDisposition);
9265 if (tmp) {
9266 const filename = rfc2047decode(tmp);
9267 return fixupEncoding(filename);
9268 }
9269 tmp = toParamRegExp("filename", "i").exec(contentDisposition);
9270 if (tmp) {
9271 tmp = tmp[1];
9272 let filename = rfc2616unquote(tmp);
9273 filename = rfc2047decode(filename);
9274 return fixupEncoding(filename);
9275 }
9276 function toParamRegExp(attributePattern, flags) {
9277 return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
9278 }
9279 function textdecode(encoding, value) {
9280 if (encoding) {
9281 if (!/^[\x00-\xFF]+$/.test(value)) {
9282 return value;
9283 }
9284 try {
9285 const decoder = new TextDecoder(encoding, {
9286 fatal: true
9287 });
9288 const buffer = (0, _util.stringToBytes)(value);
9289 value = decoder.decode(buffer);
9290 needsEncodingFixup = false;
9291 } catch (e) {}
9292 }
9293 return value;
9294 }
9295 function fixupEncoding(value) {
9296 if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
9297 value = textdecode("utf-8", value);
9298 if (needsEncodingFixup) {
9299 value = textdecode("iso-8859-1", value);
9300 }
9301 }
9302 return value;
9303 }
9304 function rfc2231getparam(contentDispositionStr) {
9305 const matches = [];
9306 let match;
9307 const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
9308 while ((match = iter.exec(contentDispositionStr)) !== null) {
9309 let [, n, quot, part] = match;
9310 n = parseInt(n, 10);
9311 if (n in matches) {
9312 if (n === 0) {
9313 break;
9314 }
9315 continue;
9316 }
9317 matches[n] = [quot, part];
9318 }
9319 const parts = [];
9320 for (let n = 0; n < matches.length; ++n) {
9321 if (!(n in matches)) {
9322 break;
9323 }
9324 let [quot, part] = matches[n];
9325 part = rfc2616unquote(part);
9326 if (quot) {
9327 part = unescape(part);
9328 if (n === 0) {
9329 part = rfc5987decode(part);
9330 }
9331 }
9332 parts.push(part);
9333 }
9334 return parts.join("");
9335 }
9336 function rfc2616unquote(value) {
9337 if (value.startsWith('"')) {
9338 const parts = value.slice(1).split('\\"');
9339 for (let i = 0; i < parts.length; ++i) {
9340 const quotindex = parts[i].indexOf('"');
9341 if (quotindex !== -1) {
9342 parts[i] = parts[i].slice(0, quotindex);
9343 parts.length = i + 1;
9344 }
9345 parts[i] = parts[i].replace(/\\(.)/g, "$1");
9346 }
9347 value = parts.join('"');
9348 }
9349 return value;
9350 }
9351 function rfc5987decode(extvalue) {
9352 const encodingend = extvalue.indexOf("'");
9353 if (encodingend === -1) {
9354 return extvalue;
9355 }
9356 const encoding = extvalue.slice(0, encodingend);
9357 const langvalue = extvalue.slice(encodingend + 1);
9358 const value = langvalue.replace(/^[^']*'/, "");
9359 return textdecode(encoding, value);
9360 }
9361 function rfc2047decode(value) {
9362 if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
9363 return value;
9364 }
9365 return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
9366 if (encoding === "q" || encoding === "Q") {
9367 text = text.replace(/_/g, " ");
9368 text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
9369 return String.fromCharCode(parseInt(hex, 16));
9370 });
9371 return textdecode(charset, text);
9372 }
9373 try {
9374 text = atob(text);
9375 } catch (e) {}
9376 return textdecode(charset, text);
9377 });
9378 }
9379 return "";
9380}
9381
9382/***/ }),
9383/* 24 */
9384/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9385
9386
9387
9388Object.defineProperty(exports, "__esModule", ({
9389 value: true
9390}));
9391exports.PDFNetworkStream = void 0;
9392var _util = __w_pdfjs_require__(1);
9393var _network_utils = __w_pdfjs_require__(22);
9394;
9395const OK_RESPONSE = 200;
9396const PARTIAL_CONTENT_RESPONSE = 206;
9397function getArrayBuffer(xhr) {
9398 const data = xhr.response;
9399 if (typeof data !== "string") {
9400 return data;
9401 }
9402 return (0, _util.stringToBytes)(data).buffer;
9403}
9404class NetworkManager {
9405 constructor(url, args = {}) {
9406 this.url = url;
9407 this.isHttp = /^https?:/i.test(url);
9408 this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
9409 this.withCredentials = args.withCredentials || false;
9410 this.getXhr = args.getXhr || function NetworkManager_getXhr() {
9411 return new XMLHttpRequest();
9412 };
9413 this.currXhrId = 0;
9414 this.pendingRequests = Object.create(null);
9415 }
9416 requestRange(begin, end, listeners) {
9417 const args = {
9418 begin,
9419 end
9420 };
9421 for (const prop in listeners) {
9422 args[prop] = listeners[prop];
9423 }
9424 return this.request(args);
9425 }
9426 requestFull(listeners) {
9427 return this.request(listeners);
9428 }
9429 request(args) {
9430 const xhr = this.getXhr();
9431 const xhrId = this.currXhrId++;
9432 const pendingRequest = this.pendingRequests[xhrId] = {
9433 xhr
9434 };
9435 xhr.open("GET", this.url);
9436 xhr.withCredentials = this.withCredentials;
9437 for (const property in this.httpHeaders) {
9438 const value = this.httpHeaders[property];
9439 if (value === undefined) {
9440 continue;
9441 }
9442 xhr.setRequestHeader(property, value);
9443 }
9444 if (this.isHttp && "begin" in args && "end" in args) {
9445 xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
9446 pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
9447 } else {
9448 pendingRequest.expectedStatus = OK_RESPONSE;
9449 }
9450 xhr.responseType = "arraybuffer";
9451 if (args.onError) {
9452 xhr.onerror = function (evt) {
9453 args.onError(xhr.status);
9454 };
9455 }
9456 xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
9457 xhr.onprogress = this.onProgress.bind(this, xhrId);
9458 pendingRequest.onHeadersReceived = args.onHeadersReceived;
9459 pendingRequest.onDone = args.onDone;
9460 pendingRequest.onError = args.onError;
9461 pendingRequest.onProgress = args.onProgress;
9462 xhr.send(null);
9463 return xhrId;
9464 }
9465 onProgress(xhrId, evt) {
9466 const pendingRequest = this.pendingRequests[xhrId];
9467 if (!pendingRequest) {
9468 return;
9469 }
9470 pendingRequest.onProgress?.(evt);
9471 }
9472 onStateChange(xhrId, evt) {
9473 const pendingRequest = this.pendingRequests[xhrId];
9474 if (!pendingRequest) {
9475 return;
9476 }
9477 const xhr = pendingRequest.xhr;
9478 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
9479 pendingRequest.onHeadersReceived();
9480 delete pendingRequest.onHeadersReceived;
9481 }
9482 if (xhr.readyState !== 4) {
9483 return;
9484 }
9485 if (!(xhrId in this.pendingRequests)) {
9486 return;
9487 }
9488 delete this.pendingRequests[xhrId];
9489 if (xhr.status === 0 && this.isHttp) {
9490 pendingRequest.onError?.(xhr.status);
9491 return;
9492 }
9493 const xhrStatus = xhr.status || OK_RESPONSE;
9494 const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
9495 if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
9496 pendingRequest.onError?.(xhr.status);
9497 return;
9498 }
9499 const chunk = getArrayBuffer(xhr);
9500 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
9501 const rangeHeader = xhr.getResponseHeader("Content-Range");
9502 const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
9503 pendingRequest.onDone({
9504 begin: parseInt(matches[1], 10),
9505 chunk
9506 });
9507 } else if (chunk) {
9508 pendingRequest.onDone({
9509 begin: 0,
9510 chunk
9511 });
9512 } else {
9513 pendingRequest.onError?.(xhr.status);
9514 }
9515 }
9516 getRequestXhr(xhrId) {
9517 return this.pendingRequests[xhrId].xhr;
9518 }
9519 isPendingRequest(xhrId) {
9520 return xhrId in this.pendingRequests;
9521 }
9522 abortRequest(xhrId) {
9523 const xhr = this.pendingRequests[xhrId].xhr;
9524 delete this.pendingRequests[xhrId];
9525 xhr.abort();
9526 }
9527}
9528class PDFNetworkStream {
9529 constructor(source) {
9530 this._source = source;
9531 this._manager = new NetworkManager(source.url, {
9532 httpHeaders: source.httpHeaders,
9533 withCredentials: source.withCredentials
9534 });
9535 this._rangeChunkSize = source.rangeChunkSize;
9536 this._fullRequestReader = null;
9537 this._rangeRequestReaders = [];
9538 }
9539 _onRangeRequestReaderClosed(reader) {
9540 const i = this._rangeRequestReaders.indexOf(reader);
9541 if (i >= 0) {
9542 this._rangeRequestReaders.splice(i, 1);
9543 }
9544 }
9545 getFullReader() {
9546 (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
9547 this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
9548 return this._fullRequestReader;
9549 }
9550 getRangeReader(begin, end) {
9551 const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
9552 reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
9553 this._rangeRequestReaders.push(reader);
9554 return reader;
9555 }
9556 cancelAllRequests(reason) {
9557 this._fullRequestReader?.cancel(reason);
9558 for (const reader of this._rangeRequestReaders.slice(0)) {
9559 reader.cancel(reason);
9560 }
9561 }
9562}
9563exports.PDFNetworkStream = PDFNetworkStream;
9564class PDFNetworkStreamFullRequestReader {
9565 constructor(manager, source) {
9566 this._manager = manager;
9567 const args = {
9568 onHeadersReceived: this._onHeadersReceived.bind(this),
9569 onDone: this._onDone.bind(this),
9570 onError: this._onError.bind(this),
9571 onProgress: this._onProgress.bind(this)
9572 };
9573 this._url = source.url;
9574 this._fullRequestId = manager.requestFull(args);
9575 this._headersReceivedCapability = (0, _util.createPromiseCapability)();
9576 this._disableRange = source.disableRange || false;
9577 this._contentLength = source.length;
9578 this._rangeChunkSize = source.rangeChunkSize;
9579 if (!this._rangeChunkSize && !this._disableRange) {
9580 this._disableRange = true;
9581 }
9582 this._isStreamingSupported = false;
9583 this._isRangeSupported = false;
9584 this._cachedChunks = [];
9585 this._requests = [];
9586 this._done = false;
9587 this._storedError = undefined;
9588 this._filename = null;
9589 this.onProgress = null;
9590 }
9591 _onHeadersReceived() {
9592 const fullRequestXhrId = this._fullRequestId;
9593 const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
9594 const getResponseHeader = name => {
9595 return fullRequestXhr.getResponseHeader(name);
9596 };
9597 const {
9598 allowRangeRequests,
9599 suggestedLength
9600 } = (0, _network_utils.validateRangeRequestCapabilities)({
9601 getResponseHeader,
9602 isHttp: this._manager.isHttp,
9603 rangeChunkSize: this._rangeChunkSize,
9604 disableRange: this._disableRange
9605 });
9606 if (allowRangeRequests) {
9607 this._isRangeSupported = true;
9608 }
9609 this._contentLength = suggestedLength || this._contentLength;
9610 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
9611 if (this._isRangeSupported) {
9612 this._manager.abortRequest(fullRequestXhrId);
9613 }
9614 this._headersReceivedCapability.resolve();
9615 }
9616 _onDone(data) {
9617 if (data) {
9618 if (this._requests.length > 0) {
9619 const requestCapability = this._requests.shift();
9620 requestCapability.resolve({
9621 value: data.chunk,
9622 done: false
9623 });
9624 } else {
9625 this._cachedChunks.push(data.chunk);
9626 }
9627 }
9628 this._done = true;
9629 if (this._cachedChunks.length > 0) {
9630 return;
9631 }
9632 for (const requestCapability of this._requests) {
9633 requestCapability.resolve({
9634 value: undefined,
9635 done: true
9636 });
9637 }
9638 this._requests.length = 0;
9639 }
9640 _onError(status) {
9641 this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
9642 this._headersReceivedCapability.reject(this._storedError);
9643 for (const requestCapability of this._requests) {
9644 requestCapability.reject(this._storedError);
9645 }
9646 this._requests.length = 0;
9647 this._cachedChunks.length = 0;
9648 }
9649 _onProgress(evt) {
9650 this.onProgress?.({
9651 loaded: evt.loaded,
9652 total: evt.lengthComputable ? evt.total : this._contentLength
9653 });
9654 }
9655 get filename() {
9656 return this._filename;
9657 }
9658 get isRangeSupported() {
9659 return this._isRangeSupported;
9660 }
9661 get isStreamingSupported() {
9662 return this._isStreamingSupported;
9663 }
9664 get contentLength() {
9665 return this._contentLength;
9666 }
9667 get headersReady() {
9668 return this._headersReceivedCapability.promise;
9669 }
9670 async read() {
9671 if (this._storedError) {
9672 throw this._storedError;
9673 }
9674 if (this._cachedChunks.length > 0) {
9675 const chunk = this._cachedChunks.shift();
9676 return {
9677 value: chunk,
9678 done: false
9679 };
9680 }
9681 if (this._done) {
9682 return {
9683 value: undefined,
9684 done: true
9685 };
9686 }
9687 const requestCapability = (0, _util.createPromiseCapability)();
9688 this._requests.push(requestCapability);
9689 return requestCapability.promise;
9690 }
9691 cancel(reason) {
9692 this._done = true;
9693 this._headersReceivedCapability.reject(reason);
9694 for (const requestCapability of this._requests) {
9695 requestCapability.resolve({
9696 value: undefined,
9697 done: true
9698 });
9699 }
9700 this._requests.length = 0;
9701 if (this._manager.isPendingRequest(this._fullRequestId)) {
9702 this._manager.abortRequest(this._fullRequestId);
9703 }
9704 this._fullRequestReader = null;
9705 }
9706}
9707class PDFNetworkStreamRangeRequestReader {
9708 constructor(manager, begin, end) {
9709 this._manager = manager;
9710 const args = {
9711 onDone: this._onDone.bind(this),
9712 onError: this._onError.bind(this),
9713 onProgress: this._onProgress.bind(this)
9714 };
9715 this._url = manager.url;
9716 this._requestId = manager.requestRange(begin, end, args);
9717 this._requests = [];
9718 this._queuedChunk = null;
9719 this._done = false;
9720 this._storedError = undefined;
9721 this.onProgress = null;
9722 this.onClosed = null;
9723 }
9724 _close() {
9725 this.onClosed?.(this);
9726 }
9727 _onDone(data) {
9728 const chunk = data.chunk;
9729 if (this._requests.length > 0) {
9730 const requestCapability = this._requests.shift();
9731 requestCapability.resolve({
9732 value: chunk,
9733 done: false
9734 });
9735 } else {
9736 this._queuedChunk = chunk;
9737 }
9738 this._done = true;
9739 for (const requestCapability of this._requests) {
9740 requestCapability.resolve({
9741 value: undefined,
9742 done: true
9743 });
9744 }
9745 this._requests.length = 0;
9746 this._close();
9747 }
9748 _onError(status) {
9749 this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
9750 for (const requestCapability of this._requests) {
9751 requestCapability.reject(this._storedError);
9752 }
9753 this._requests.length = 0;
9754 this._queuedChunk = null;
9755 }
9756 _onProgress(evt) {
9757 if (!this.isStreamingSupported) {
9758 this.onProgress?.({
9759 loaded: evt.loaded
9760 });
9761 }
9762 }
9763 get isStreamingSupported() {
9764 return false;
9765 }
9766 async read() {
9767 if (this._storedError) {
9768 throw this._storedError;
9769 }
9770 if (this._queuedChunk !== null) {
9771 const chunk = this._queuedChunk;
9772 this._queuedChunk = null;
9773 return {
9774 value: chunk,
9775 done: false
9776 };
9777 }
9778 if (this._done) {
9779 return {
9780 value: undefined,
9781 done: true
9782 };
9783 }
9784 const requestCapability = (0, _util.createPromiseCapability)();
9785 this._requests.push(requestCapability);
9786 return requestCapability.promise;
9787 }
9788 cancel(reason) {
9789 this._done = true;
9790 for (const requestCapability of this._requests) {
9791 requestCapability.resolve({
9792 value: undefined,
9793 done: true
9794 });
9795 }
9796 this._requests.length = 0;
9797 if (this._manager.isPendingRequest(this._requestId)) {
9798 this._manager.abortRequest(this._requestId);
9799 }
9800 this._close();
9801 }
9802}
9803
9804/***/ }),
9805/* 25 */
9806/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9807
9808
9809
9810Object.defineProperty(exports, "__esModule", ({
9811 value: true
9812}));
9813exports.PDFFetchStream = void 0;
9814var _util = __w_pdfjs_require__(1);
9815var _network_utils = __w_pdfjs_require__(22);
9816;
9817function createFetchOptions(headers, withCredentials, abortController) {
9818 return {
9819 method: "GET",
9820 headers,
9821 signal: abortController.signal,
9822 mode: "cors",
9823 credentials: withCredentials ? "include" : "same-origin",
9824 redirect: "follow"
9825 };
9826}
9827function createHeaders(httpHeaders) {
9828 const headers = new Headers();
9829 for (const property in httpHeaders) {
9830 const value = httpHeaders[property];
9831 if (value === undefined) {
9832 continue;
9833 }
9834 headers.append(property, value);
9835 }
9836 return headers;
9837}
9838function getArrayBuffer(val) {
9839 if (val instanceof Uint8Array) {
9840 return val.buffer;
9841 }
9842 if (val instanceof ArrayBuffer) {
9843 return val;
9844 }
9845 (0, _util.warn)(`getArrayBuffer - unexpected data format: ${val}`);
9846 return new Uint8Array(val).buffer;
9847}
9848class PDFFetchStream {
9849 constructor(source) {
9850 this.source = source;
9851 this.isHttp = /^https?:/i.test(source.url);
9852 this.httpHeaders = this.isHttp && source.httpHeaders || {};
9853 this._fullRequestReader = null;
9854 this._rangeRequestReaders = [];
9855 }
9856 get _progressiveDataLength() {
9857 return this._fullRequestReader?._loaded ?? 0;
9858 }
9859 getFullReader() {
9860 (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
9861 this._fullRequestReader = new PDFFetchStreamReader(this);
9862 return this._fullRequestReader;
9863 }
9864 getRangeReader(begin, end) {
9865 if (end <= this._progressiveDataLength) {
9866 return null;
9867 }
9868 const reader = new PDFFetchStreamRangeReader(this, begin, end);
9869 this._rangeRequestReaders.push(reader);
9870 return reader;
9871 }
9872 cancelAllRequests(reason) {
9873 this._fullRequestReader?.cancel(reason);
9874 for (const reader of this._rangeRequestReaders.slice(0)) {
9875 reader.cancel(reason);
9876 }
9877 }
9878}
9879exports.PDFFetchStream = PDFFetchStream;
9880class PDFFetchStreamReader {
9881 constructor(stream) {
9882 this._stream = stream;
9883 this._reader = null;
9884 this._loaded = 0;
9885 this._filename = null;
9886 const source = stream.source;
9887 this._withCredentials = source.withCredentials || false;
9888 this._contentLength = source.length;
9889 this._headersCapability = (0, _util.createPromiseCapability)();
9890 this._disableRange = source.disableRange || false;
9891 this._rangeChunkSize = source.rangeChunkSize;
9892 if (!this._rangeChunkSize && !this._disableRange) {
9893 this._disableRange = true;
9894 }
9895 this._abortController = new AbortController();
9896 this._isStreamingSupported = !source.disableStream;
9897 this._isRangeSupported = !source.disableRange;
9898 this._headers = createHeaders(this._stream.httpHeaders);
9899 const url = source.url;
9900 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
9901 if (!(0, _network_utils.validateResponseStatus)(response.status)) {
9902 throw (0, _network_utils.createResponseStatusError)(response.status, url);
9903 }
9904 this._reader = response.body.getReader();
9905 this._headersCapability.resolve();
9906 const getResponseHeader = name => {
9907 return response.headers.get(name);
9908 };
9909 const {
9910 allowRangeRequests,
9911 suggestedLength
9912 } = (0, _network_utils.validateRangeRequestCapabilities)({
9913 getResponseHeader,
9914 isHttp: this._stream.isHttp,
9915 rangeChunkSize: this._rangeChunkSize,
9916 disableRange: this._disableRange
9917 });
9918 this._isRangeSupported = allowRangeRequests;
9919 this._contentLength = suggestedLength || this._contentLength;
9920 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
9921 if (!this._isStreamingSupported && this._isRangeSupported) {
9922 this.cancel(new _util.AbortException("Streaming is disabled."));
9923 }
9924 }).catch(this._headersCapability.reject);
9925 this.onProgress = null;
9926 }
9927 get headersReady() {
9928 return this._headersCapability.promise;
9929 }
9930 get filename() {
9931 return this._filename;
9932 }
9933 get contentLength() {
9934 return this._contentLength;
9935 }
9936 get isRangeSupported() {
9937 return this._isRangeSupported;
9938 }
9939 get isStreamingSupported() {
9940 return this._isStreamingSupported;
9941 }
9942 async read() {
9943 await this._headersCapability.promise;
9944 const {
9945 value,
9946 done
9947 } = await this._reader.read();
9948 if (done) {
9949 return {
9950 value,
9951 done
9952 };
9953 }
9954 this._loaded += value.byteLength;
9955 this.onProgress?.({
9956 loaded: this._loaded,
9957 total: this._contentLength
9958 });
9959 return {
9960 value: getArrayBuffer(value),
9961 done: false
9962 };
9963 }
9964 cancel(reason) {
9965 this._reader?.cancel(reason);
9966 this._abortController.abort();
9967 }
9968}
9969class PDFFetchStreamRangeReader {
9970 constructor(stream, begin, end) {
9971 this._stream = stream;
9972 this._reader = null;
9973 this._loaded = 0;
9974 const source = stream.source;
9975 this._withCredentials = source.withCredentials || false;
9976 this._readCapability = (0, _util.createPromiseCapability)();
9977 this._isStreamingSupported = !source.disableStream;
9978 this._abortController = new AbortController();
9979 this._headers = createHeaders(this._stream.httpHeaders);
9980 this._headers.append("Range", `bytes=${begin}-${end - 1}`);
9981 const url = source.url;
9982 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
9983 if (!(0, _network_utils.validateResponseStatus)(response.status)) {
9984 throw (0, _network_utils.createResponseStatusError)(response.status, url);
9985 }
9986 this._readCapability.resolve();
9987 this._reader = response.body.getReader();
9988 }).catch(this._readCapability.reject);
9989 this.onProgress = null;
9990 }
9991 get isStreamingSupported() {
9992 return this._isStreamingSupported;
9993 }
9994 async read() {
9995 await this._readCapability.promise;
9996 const {
9997 value,
9998 done
9999 } = await this._reader.read();
10000 if (done) {
10001 return {
10002 value,
10003 done
10004 };
10005 }
10006 this._loaded += value.byteLength;
10007 this.onProgress?.({
10008 loaded: this._loaded
10009 });
10010 return {
10011 value: getArrayBuffer(value),
10012 done: false
10013 };
10014 }
10015 cancel(reason) {
10016 this._reader?.cancel(reason);
10017 this._abortController.abort();
10018 }
10019}
10020
10021/***/ }),
10022/* 26 */
10023/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10024
10025
10026
10027Object.defineProperty(exports, "__esModule", ({
10028 value: true
10029}));
10030exports.TextLayerRenderTask = void 0;
10031exports.renderTextLayer = renderTextLayer;
10032exports.updateTextLayer = updateTextLayer;
10033var _util = __w_pdfjs_require__(1);
10034var _display_utils = __w_pdfjs_require__(6);
10035const MAX_TEXT_DIVS_TO_RENDER = 100000;
10036const DEFAULT_FONT_SIZE = 30;
10037const DEFAULT_FONT_ASCENT = 0.8;
10038const ascentCache = new Map();
10039function getCtx(size, isOffscreenCanvasSupported) {
10040 let ctx;
10041 const options = window.pdfDefaultOptions.activateWillReadFrequentlyFlag ? {
10042 willReadFrequently: true,
10043 alpha: false
10044 } : {
10045 alpha: false
10046 };
10047 if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
10048 ctx = new OffscreenCanvas(size, size).getContext("2d", options);
10049 } else {
10050 const canvas = document.createElement("canvas");
10051 canvas.width = canvas.height = size;
10052 ctx = canvas.getContext("2d", options);
10053 }
10054 return ctx;
10055}
10056function getAscent(fontFamily, isOffscreenCanvasSupported) {
10057 const cachedAscent = ascentCache.get(fontFamily);
10058 if (cachedAscent) {
10059 return cachedAscent;
10060 }
10061 const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported);
10062 ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
10063 const metrics = ctx.measureText("");
10064 let ascent = metrics?.fontBoundingBoxAscent;
10065 let descent = Math.abs(metrics?.fontBoundingBoxDescent);
10066 if (ascent) {
10067 const ratio = ascent / (ascent + descent);
10068 ascentCache.set(fontFamily, ratio);
10069 ctx.canvas.width = ctx.canvas.height = 0;
10070 return ratio;
10071 }
10072 ctx.strokeStyle = "red";
10073 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
10074 ctx.strokeText("g", 0, 0);
10075 let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
10076 descent = 0;
10077 for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
10078 if (pixels[i] > 0) {
10079 descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
10080 break;
10081 }
10082 }
10083 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
10084 ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
10085 pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
10086 ascent = 0;
10087 for (let i = 0, ii = pixels.length; i < ii; i += 4) {
10088 if (pixels[i] > 0) {
10089 ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
10090 break;
10091 }
10092 }
10093 ctx.canvas.width = ctx.canvas.height = 0;
10094 if (ascent) {
10095 const ratio = ascent / (ascent + descent);
10096 ascentCache.set(fontFamily, ratio);
10097 return ratio;
10098 }
10099 ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
10100 return DEFAULT_FONT_ASCENT;
10101}
10102function appendText(task, geom, styles) {
10103 const textDiv = document.createElement("span");
10104 const textDivProperties = {
10105 angle: 0,
10106 canvasWidth: 0,
10107 hasText: geom.str !== "",
10108 hasEOL: geom.hasEOL,
10109 fontSize: 0
10110 };
10111 task._textDivs.push(textDiv);
10112 const tx = _util.Util.transform(task._transform, geom.transform);
10113 let angle = Math.atan2(tx[1], tx[0]);
10114 const style = styles[geom.fontName];
10115 if (style.vertical) {
10116 angle += Math.PI / 2;
10117 }
10118 const fontHeight = Math.hypot(tx[2], tx[3]);
10119 const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported);
10120 let left, top;
10121 if (angle === 0) {
10122 left = tx[4];
10123 top = tx[5] - fontAscent;
10124 } else {
10125 left = tx[4] + fontAscent * Math.sin(angle);
10126 top = tx[5] - fontAscent * Math.cos(angle);
10127 }
10128 const scaleFactorStr = "calc(var(--scale-factor)*";
10129 const divStyle = textDiv.style;
10130 if (task._container === task._rootContainer) {
10131 divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`;
10132 divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`;
10133 } else {
10134 divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
10135 divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
10136 }
10137 divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
10138 divStyle.fontFamily = style.fontFamily;
10139 textDivProperties.fontSize = fontHeight;
10140 textDiv.setAttribute("role", "presentation");
10141 textDiv.textContent = geom.str;
10142 textDiv.dir = geom.dir;
10143 if (task._fontInspectorEnabled) {
10144 textDiv.dataset.fontName = geom.fontName;
10145 }
10146 if (angle !== 0) {
10147 textDivProperties.angle = angle * (180 / Math.PI);
10148 }
10149 let shouldScaleText = false;
10150 if (geom.str.length > 1) {
10151 shouldScaleText = true;
10152 } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
10153 const absScaleX = Math.abs(geom.transform[0]),
10154 absScaleY = Math.abs(geom.transform[3]);
10155 if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
10156 shouldScaleText = true;
10157 }
10158 }
10159 if (shouldScaleText) {
10160 textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
10161 }
10162 task._textDivProperties.set(textDiv, textDivProperties);
10163 if (task._isReadableStream) {
10164 task._layoutText(textDiv);
10165 }
10166}
10167function layout(params) {
10168 const {
10169 div,
10170 scale,
10171 properties,
10172 ctx,
10173 prevFontSize,
10174 prevFontFamily
10175 } = params;
10176 const {
10177 style
10178 } = div;
10179 let transform = "";
10180 if (properties.canvasWidth !== 0 && properties.hasText) {
10181 const {
10182 fontFamily
10183 } = style;
10184 const {
10185 canvasWidth,
10186 fontSize
10187 } = properties;
10188 if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
10189 ctx.font = `${fontSize * scale}px ${fontFamily}`;
10190 params.prevFontSize = fontSize;
10191 params.prevFontFamily = fontFamily;
10192 }
10193 try {
10194 const {
10195 width
10196 } = ctx.measureText(div.textContent);
10197 if (width > 0) {
10198 transform = `scaleX(${canvasWidth * scale / width})`;
10199 }
10200 } catch (fingerprintIsBlockedException) {}
10201 }
10202 if (properties.angle !== 0) {
10203 transform = `rotate(${properties.angle}deg) ${transform}`;
10204 }
10205 if (transform.length > 0) {
10206 style.transform = transform;
10207 }
10208}
10209function render(task) {
10210 if (task._canceled) {
10211 return;
10212 }
10213 const textDivs = task._textDivs;
10214 const capability = task._capability;
10215 const textDivsLength = textDivs.length;
10216 if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
10217 capability.resolve();
10218 return;
10219 }
10220 if (!task._isReadableStream) {
10221 for (const textDiv of textDivs) {
10222 task._layoutText(textDiv);
10223 }
10224 }
10225 capability.resolve();
10226}
10227class TextLayerRenderTask {
10228 constructor({
10229 textContentSource,
10230 container,
10231 viewport,
10232 textDivs,
10233 textDivProperties,
10234 textContentItemsStr,
10235 isOffscreenCanvasSupported
10236 }) {
10237 this._textContentSource = textContentSource;
10238 this._isReadableStream = textContentSource instanceof ReadableStream;
10239 this._container = this._rootContainer = container;
10240 this._textDivs = textDivs || [];
10241 this._textContentItemsStr = textContentItemsStr || [];
10242 this._isOffscreenCanvasSupported = isOffscreenCanvasSupported;
10243 this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
10244 this._reader = null;
10245 this._textDivProperties = textDivProperties || new WeakMap();
10246 this._canceled = false;
10247 this._capability = (0, _util.createPromiseCapability)();
10248 this._layoutTextParams = {
10249 prevFontSize: null,
10250 prevFontFamily: null,
10251 div: null,
10252 scale: viewport.scale * (globalThis.devicePixelRatio || 1),
10253 properties: null,
10254 ctx: getCtx(0, isOffscreenCanvasSupported)
10255 };
10256 const {
10257 pageWidth,
10258 pageHeight,
10259 pageX,
10260 pageY
10261 } = viewport.rawDims;
10262 this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
10263 this._pageWidth = pageWidth;
10264 this._pageHeight = pageHeight;
10265 (0, _display_utils.setLayerDimensions)(container, viewport);
10266 this._capability.promise.finally(() => {
10267 this._layoutTextParams = null;
10268 }).catch(() => {});
10269 }
10270 get promise() {
10271 return this._capability.promise;
10272 }
10273 cancel() {
10274 this._canceled = true;
10275 if (this._reader) {
10276 this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
10277 this._reader = null;
10278 }
10279 this._capability.reject(new _util.AbortException("TextLayer task cancelled."));
10280 }
10281 _processItems(items, styleCache) {
10282 for (const item of items) {
10283 if (item.str === undefined) {
10284 if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
10285 const parent = this._container;
10286 this._container = document.createElement("span");
10287 this._container.classList.add("markedContent");
10288 if (item.id !== null) {
10289 this._container.setAttribute("id", `${item.id}`);
10290 }
10291 parent.append(this._container);
10292 } else if (item.type === "endMarkedContent") {
10293 this._container = this._container.parentNode;
10294 }
10295 continue;
10296 }
10297 this._textContentItemsStr.push(item.str);
10298 appendText(this, item, styleCache);
10299 }
10300 }
10301 _layoutText(textDiv) {
10302 const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv);
10303 this._layoutTextParams.div = textDiv;
10304 layout(this._layoutTextParams);
10305 if (textDivProperties.hasText) {
10306 this._container.append(textDiv);
10307 }
10308 if (textDivProperties.hasEOL) {
10309 const br = document.createElement("br");
10310 br.setAttribute("role", "presentation");
10311 this._container.append(br);
10312 }
10313 }
10314 _render() {
10315 const capability = (0, _util.createPromiseCapability)();
10316 let styleCache = Object.create(null);
10317 if (this._isReadableStream) {
10318 const pump = () => {
10319 this._reader.read().then(({
10320 value,
10321 done
10322 }) => {
10323 if (done) {
10324 capability.resolve();
10325 return;
10326 }
10327 Object.assign(styleCache, value.styles);
10328 this._processItems(value.items, styleCache);
10329 pump();
10330 }, capability.reject);
10331 };
10332 this._reader = this._textContentSource.getReader();
10333 pump();
10334 } else if (this._textContentSource) {
10335 const {
10336 items,
10337 styles
10338 } = this._textContentSource;
10339 this._processItems(items, styles);
10340 capability.resolve();
10341 } else {
10342 throw new Error('No "textContentSource" parameter specified.');
10343 }
10344 capability.promise.then(() => {
10345 styleCache = null;
10346 render(this);
10347 }, this._capability.reject);
10348 }
10349}
10350exports.TextLayerRenderTask = TextLayerRenderTask;
10351function renderTextLayer(params) {
10352 if (!params.textContentSource && (params.textContent || params.textContentStream)) {
10353 (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead.");
10354 params.textContentSource = params.textContent || params.textContentStream;
10355 }
10356 const task = new TextLayerRenderTask(params);
10357 task._render();
10358 return task;
10359}
10360function updateTextLayer({
10361 container,
10362 viewport,
10363 textDivs,
10364 textDivProperties,
10365 isOffscreenCanvasSupported,
10366 mustRotate = true,
10367 mustRescale = true
10368}) {
10369 if (mustRotate) {
10370 (0, _display_utils.setLayerDimensions)(container, {
10371 rotation: viewport.rotation
10372 });
10373 }
10374 if (mustRescale) {
10375 const ctx = getCtx(0, isOffscreenCanvasSupported);
10376 const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
10377 const params = {
10378 prevFontSize: null,
10379 prevFontFamily: null,
10380 div: null,
10381 scale,
10382 properties: null,
10383 ctx
10384 };
10385 for (const div of textDivs) {
10386 params.properties = textDivProperties.get(div);
10387 params.div = div;
10388 layout(params);
10389 }
10390 }
10391}
10392
10393/***/ }),
10394/* 27 */
10395/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10396
10397
10398
10399Object.defineProperty(exports, "__esModule", ({
10400 value: true
10401}));
10402exports.AnnotationEditorLayer = void 0;
10403var _util = __w_pdfjs_require__(1);
10404var _tools = __w_pdfjs_require__(5);
10405var _freetext = __w_pdfjs_require__(28);
10406var _ink = __w_pdfjs_require__(29);
10407var _display_utils = __w_pdfjs_require__(6);
10408class AnnotationEditorLayer {
10409 #accessibilityManager;
10410 #allowClick = false;
10411 #boundPointerup = this.pointerup.bind(this);
10412 #boundPointerdown = this.pointerdown.bind(this);
10413 #editors = new Map();
10414 #hadPointerDown = false;
10415 #isCleaningUp = false;
10416 #uiManager;
10417 static _initialized = false;
10418 constructor(options) {
10419 if (!AnnotationEditorLayer._initialized) {
10420 AnnotationEditorLayer._initialized = true;
10421 _freetext.FreeTextEditor.initialize(options.l10n);
10422 _ink.InkEditor.initialize(options.l10n);
10423 }
10424 options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
10425 this.#uiManager = options.uiManager;
10426 this.pageIndex = options.pageIndex;
10427 this.div = options.div;
10428 this.#accessibilityManager = options.accessibilityManager;
10429 this.#uiManager.addLayer(this);
10430 }
10431 get isEmpty() {
10432 return this.#editors.size === 0;
10433 }
10434 updateToolbar(mode) {
10435 this.#uiManager.updateToolbar(mode);
10436 }
10437 updateMode(mode = this.#uiManager.getMode()) {
10438 this.#cleanup();
10439 if (mode === _util.AnnotationEditorType.INK) {
10440 this.addInkEditorIfNeeded(false);
10441 this.disableClick();
10442 } else {
10443 this.enableClick();
10444 }
10445 this.#uiManager.unselectAll();
10446 if (mode !== _util.AnnotationEditorType.NONE) {
10447 this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
10448 this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
10449 this.div.hidden = false;
10450 }
10451 }
10452 addInkEditorIfNeeded(isCommitting) {
10453 if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
10454 return;
10455 }
10456 if (!isCommitting) {
10457 for (const editor of this.#editors.values()) {
10458 if (editor.isEmpty()) {
10459 editor.setInBackground();
10460 return;
10461 }
10462 }
10463 }
10464 const editor = this.#createAndAddNewEditor({
10465 offsetX: 0,
10466 offsetY: 0
10467 });
10468 editor.setInBackground();
10469 }
10470 setEditingState(isEditing) {
10471 this.#uiManager.setEditingState(isEditing);
10472 }
10473 addCommands(params) {
10474 this.#uiManager.addCommands(params);
10475 }
10476 enable() {
10477 this.div.style.pointerEvents = "auto";
10478 for (const editor of this.#editors.values()) {
10479 editor.enableEditing();
10480 }
10481 }
10482 disable() {
10483 this.div.style.pointerEvents = "none";
10484 for (const editor of this.#editors.values()) {
10485 editor.disableEditing();
10486 }
10487 this.#cleanup();
10488 if (this.isEmpty) {
10489 this.div.hidden = true;
10490 }
10491 }
10492 setActiveEditor(editor) {
10493 const currentActive = this.#uiManager.getActive();
10494 if (currentActive === editor) {
10495 return;
10496 }
10497 this.#uiManager.setActiveEditor(editor);
10498 }
10499 enableClick() {
10500 this.div.addEventListener("pointerdown", this.#boundPointerdown);
10501 this.div.addEventListener("pointerup", this.#boundPointerup);
10502 }
10503 disableClick() {
10504 this.div.removeEventListener("pointerdown", this.#boundPointerdown);
10505 this.div.removeEventListener("pointerup", this.#boundPointerup);
10506 }
10507 attach(editor) {
10508 this.#editors.set(editor.id, editor);
10509 }
10510 detach(editor) {
10511 this.#editors.delete(editor.id);
10512 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
10513 }
10514 remove(editor) {
10515 this.#uiManager.removeEditor(editor);
10516 this.detach(editor);
10517 editor.div.style.display = "none";
10518 setTimeout(() => {
10519 editor.div.style.display = "";
10520 editor.div.remove();
10521 editor.isAttachedToDOM = false;
10522 if (document.activeElement === document.body) {
10523 this.#uiManager.focusMainContainer();
10524 }
10525 }, 0);
10526 if (!this.#isCleaningUp) {
10527 this.addInkEditorIfNeeded(false);
10528 }
10529 }
10530 #changeParent(editor) {
10531 if (editor.parent === this) {
10532 return;
10533 }
10534 this.attach(editor);
10535 editor.parent?.detach(editor);
10536 editor.setParent(this);
10537 if (editor.div && editor.isAttachedToDOM) {
10538 editor.div.remove();
10539 this.div.append(editor.div);
10540 }
10541 }
10542 add(editor) {
10543 this.#changeParent(editor);
10544 this.#uiManager.addEditor(editor);
10545 this.attach(editor);
10546 if (!editor.isAttachedToDOM) {
10547 const div = editor.render();
10548 this.div.append(div);
10549 editor.isAttachedToDOM = true;
10550 }
10551 this.moveEditorInDOM(editor);
10552 editor.onceAdded();
10553 this.#uiManager.addToAnnotationStorage(editor);
10554 }
10555 moveEditorInDOM(editor) {
10556 this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
10557 }
10558 addOrRebuild(editor) {
10559 if (editor.needsToBeRebuilt()) {
10560 editor.rebuild();
10561 } else {
10562 this.add(editor);
10563 }
10564 }
10565 addANewEditor(editor) {
10566 const cmd = () => {
10567 this.addOrRebuild(editor);
10568 };
10569 const undo = () => {
10570 editor.remove();
10571 };
10572 this.addCommands({
10573 cmd,
10574 undo,
10575 mustExec: true
10576 });
10577 }
10578 addUndoableEditor(editor) {
10579 const cmd = () => {
10580 this.addOrRebuild(editor);
10581 };
10582 const undo = () => {
10583 editor.remove();
10584 };
10585 this.addCommands({
10586 cmd,
10587 undo,
10588 mustExec: false
10589 });
10590 }
10591 getNextId() {
10592 return this.#uiManager.getId();
10593 }
10594 #createNewEditor(params) {
10595 switch (this.#uiManager.getMode()) {
10596 case _util.AnnotationEditorType.FREETEXT:
10597 return new _freetext.FreeTextEditor(params);
10598 case _util.AnnotationEditorType.INK:
10599 return new _ink.InkEditor(params);
10600 }
10601 return null;
10602 }
10603 deserialize(data) {
10604 switch (data.annotationType) {
10605 case _util.AnnotationEditorType.FREETEXT:
10606 return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager);
10607 case _util.AnnotationEditorType.INK:
10608 return _ink.InkEditor.deserialize(data, this, this.#uiManager);
10609 }
10610 return null;
10611 }
10612 #createAndAddNewEditor(event) {
10613 const id = this.getNextId();
10614 const editor = this.#createNewEditor({
10615 parent: this,
10616 id,
10617 x: event.offsetX,
10618 y: event.offsetY,
10619 uiManager: this.#uiManager
10620 });
10621 if (editor) {
10622 this.add(editor);
10623 }
10624 return editor;
10625 }
10626 setSelected(editor) {
10627 this.#uiManager.setSelected(editor);
10628 }
10629 toggleSelected(editor) {
10630 this.#uiManager.toggleSelected(editor);
10631 }
10632 isSelected(editor) {
10633 return this.#uiManager.isSelected(editor);
10634 }
10635 unselect(editor) {
10636 this.#uiManager.unselect(editor);
10637 }
10638 pointerup(event) {
10639 const {
10640 isMac
10641 } = _util.FeatureTest.platform;
10642 if (event.button !== 0 || event.ctrlKey && isMac) {
10643 return;
10644 }
10645 if (event.target !== this.div) {
10646 return;
10647 }
10648 if (!this.#hadPointerDown) {
10649 return;
10650 }
10651 this.#hadPointerDown = false;
10652 if (!this.#allowClick) {
10653 this.#allowClick = true;
10654 return;
10655 }
10656 this.#createAndAddNewEditor(event);
10657 }
10658 pointerdown(event) {
10659 const {
10660 isMac
10661 } = _util.FeatureTest.platform;
10662 if (event.button !== 0 || event.ctrlKey && isMac) {
10663 return;
10664 }
10665 if (event.target !== this.div) {
10666 return;
10667 }
10668 this.#hadPointerDown = true;
10669 const editor = this.#uiManager.getActive();
10670 this.#allowClick = !editor || editor.isEmpty();
10671 }
10672 drop(event) {
10673 const id = event.dataTransfer.getData("text/plain");
10674 const editor = this.#uiManager.getEditor(id);
10675 if (!editor) {
10676 return;
10677 }
10678 event.preventDefault();
10679 event.dataTransfer.dropEffect = "move";
10680 this.#changeParent(editor);
10681 const rect = this.div.getBoundingClientRect();
10682 const endX = event.clientX - rect.x;
10683 const endY = event.clientY - rect.y;
10684 editor.translate(endX - editor.startX, endY - editor.startY);
10685 this.moveEditorInDOM(editor);
10686 editor.div.focus();
10687 }
10688 dragover(event) {
10689 event.preventDefault();
10690 }
10691 destroy() {
10692 if (this.#uiManager.getActive()?.parent === this) {
10693 this.#uiManager.setActiveEditor(null);
10694 }
10695 for (const editor of this.#editors.values()) {
10696 this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
10697 editor.setParent(null);
10698 editor.isAttachedToDOM = false;
10699 editor.div.remove();
10700 }
10701 this.div = null;
10702 this.#editors.clear();
10703 this.#uiManager.removeLayer(this);
10704 }
10705 #cleanup() {
10706 this.#isCleaningUp = true;
10707 for (const editor of this.#editors.values()) {
10708 if (editor.isEmpty()) {
10709 editor.remove();
10710 }
10711 }
10712 this.#isCleaningUp = false;
10713 }
10714 render({
10715 viewport
10716 }) {
10717 this.viewport = viewport;
10718 (0, _display_utils.setLayerDimensions)(this.div, viewport);
10719 (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
10720 for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
10721 this.add(editor);
10722 }
10723 this.updateMode();
10724 }
10725 update({
10726 viewport
10727 }) {
10728 this.#uiManager.commitOrRemove();
10729 this.viewport = viewport;
10730 (0, _display_utils.setLayerDimensions)(this.div, {
10731 rotation: viewport.rotation
10732 });
10733 this.updateMode();
10734 }
10735 get pageDimensions() {
10736 const {
10737 pageWidth,
10738 pageHeight
10739 } = this.viewport.rawDims;
10740 return [pageWidth, pageHeight];
10741 }
10742}
10743exports.AnnotationEditorLayer = AnnotationEditorLayer;
10744
10745/***/ }),
10746/* 28 */
10747/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10748
10749
10750
10751Object.defineProperty(exports, "__esModule", ({
10752 value: true
10753}));
10754exports.FreeTextEditor = void 0;
10755var _util = __w_pdfjs_require__(1);
10756var _tools = __w_pdfjs_require__(5);
10757var _editor = __w_pdfjs_require__(4);
10758class FreeTextEditor extends _editor.AnnotationEditor {
10759 #boundEditorDivBlur = this.editorDivBlur.bind(this);
10760 #boundEditorDivFocus = this.editorDivFocus.bind(this);
10761 #boundEditorDivInput = this.editorDivInput.bind(this);
10762 #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
10763 #color;
10764 #content = "";
10765 #editorDivId = `${this.id}-editor`;
10766 #hasAlreadyBeenCommitted = false;
10767 #fontSize;
10768 static _freeTextDefaultContent = "";
10769 static _l10nPromise;
10770 static _internalPadding = 0;
10771 static _defaultColor = null;
10772 static _defaultFontSize = 10;
10773 static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
10774 static _type = "freetext";
10775 constructor(params) {
10776 super({
10777 ...params,
10778 name: "freeTextEditor"
10779 });
10780 this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
10781 this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
10782 }
10783 static initialize(l10n) {
10784 this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
10785 const style = getComputedStyle(document.documentElement);
10786 this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
10787 }
10788 static updateDefaultParams(type, value) {
10789 switch (type) {
10790 case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
10791 FreeTextEditor._defaultFontSize = value;
10792 break;
10793 case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
10794 FreeTextEditor._defaultColor = value;
10795 break;
10796 }
10797 }
10798 updateParams(type, value) {
10799 switch (type) {
10800 case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
10801 this.#updateFontSize(value);
10802 break;
10803 case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
10804 this.#updateColor(value);
10805 break;
10806 }
10807 }
10808 static get defaultPropertiesToUpdate() {
10809 return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
10810 }
10811 get propertiesToUpdate() {
10812 return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
10813 }
10814 #updateFontSize(fontSize) {
10815 const setFontsize = size => {
10816 this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
10817 this.translate(0, -(size - this.#fontSize) * this.parentScale);
10818 this.#fontSize = size;
10819 this.#setEditorDimensions();
10820 };
10821 const savedFontsize = this.#fontSize;
10822 this.addCommands({
10823 cmd: () => {
10824 setFontsize(fontSize);
10825 },
10826 undo: () => {
10827 setFontsize(savedFontsize);
10828 },
10829 mustExec: true,
10830 type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
10831 overwriteIfSameType: true,
10832 keepUndo: true
10833 });
10834 }
10835 #updateColor(color) {
10836 const savedColor = this.#color;
10837 this.addCommands({
10838 cmd: () => {
10839 this.#color = this.editorDiv.style.color = color;
10840 },
10841 undo: () => {
10842 this.#color = this.editorDiv.style.color = savedColor;
10843 },
10844 mustExec: true,
10845 type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
10846 overwriteIfSameType: true,
10847 keepUndo: true
10848 });
10849 }
10850 getInitialTranslation() {
10851 const scale = this.parentScale;
10852 return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
10853 }
10854 rebuild() {
10855 super.rebuild();
10856 if (this.div === null) {
10857 return;
10858 }
10859 if (!this.isAttachedToDOM) {
10860 this.parent.add(this);
10861 }
10862 }
10863 enableEditMode() {
10864 if (this.isInEditMode()) {
10865 return;
10866 }
10867 this.parent.setEditingState(false);
10868 this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
10869 super.enableEditMode();
10870 this.overlayDiv.classList.remove("enabled");
10871 this.editorDiv.contentEditable = true;
10872 this.div.draggable = false;
10873 this.div.removeAttribute("aria-activedescendant");
10874 this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
10875 this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
10876 this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
10877 this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
10878 }
10879 disableEditMode() {
10880 if (!this.isInEditMode()) {
10881 return;
10882 }
10883 this.parent.setEditingState(true);
10884 super.disableEditMode();
10885 this.overlayDiv.classList.add("enabled");
10886 this.editorDiv.contentEditable = false;
10887 this.div.setAttribute("aria-activedescendant", this.#editorDivId);
10888 this.div.draggable = true;
10889 this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
10890 this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
10891 this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
10892 this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
10893 this.div.focus({
10894 preventScroll: true
10895 });
10896 this.isEditing = false;
10897 this.parent.div.classList.add("freeTextEditing");
10898 }
10899 focusin(event) {
10900 super.focusin(event);
10901 if (event.target !== this.editorDiv) {
10902 this.editorDiv.focus();
10903 }
10904 }
10905 onceAdded() {
10906 if (this.width) {
10907 return;
10908 }
10909 this.enableEditMode();
10910 this.editorDiv.focus();
10911 }
10912 isEmpty() {
10913 return !this.editorDiv || this.editorDiv.innerText.trim() === "";
10914 }
10915 remove() {
10916 this.isEditing = false;
10917 this.parent.setEditingState(true);
10918 this.parent.div.classList.add("freeTextEditing");
10919 super.remove();
10920 }
10921 #extractText() {
10922 const divs = this.editorDiv.getElementsByTagName("div");
10923 if (divs.length === 0) {
10924 return this.editorDiv.innerText;
10925 }
10926 const buffer = [];
10927 for (const div of divs) {
10928 buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
10929 }
10930 return buffer.join("\n");
10931 }
10932 #setEditorDimensions() {
10933 const [parentWidth, parentHeight] = this.parentDimensions;
10934 let rect;
10935 if (this.isAttachedToDOM) {
10936 rect = this.div.getBoundingClientRect();
10937 } else {
10938 const {
10939 currentLayer,
10940 div
10941 } = this;
10942 const savedDisplay = div.style.display;
10943 div.style.display = "hidden";
10944 currentLayer.div.append(this.div);
10945 rect = div.getBoundingClientRect();
10946 div.remove();
10947 div.style.display = savedDisplay;
10948 }
10949 this.width = rect.width / parentWidth;
10950 this.height = rect.height / parentHeight;
10951 }
10952 commit() {
10953 if (!this.isInEditMode()) {
10954 return;
10955 }
10956 super.commit();
10957 if (!this.#hasAlreadyBeenCommitted) {
10958 this.#hasAlreadyBeenCommitted = true;
10959 this.parent.addUndoableEditor(this);
10960 }
10961 this.disableEditMode();
10962 this.#content = this.#extractText().trimEnd();
10963 this.#setEditorDimensions();
10964 }
10965 shouldGetKeyboardEvents() {
10966 return this.isInEditMode();
10967 }
10968 dblclick(event) {
10969 this.enableEditMode();
10970 this.editorDiv.focus();
10971 }
10972 keydown(event) {
10973 if (event.target === this.div && event.key === "Enter") {
10974 this.enableEditMode();
10975 this.editorDiv.focus();
10976 }
10977 }
10978 editorDivKeydown(event) {
10979 FreeTextEditor._keyboardManager.exec(this, event);
10980 }
10981 editorDivFocus(event) {
10982 this.isEditing = true;
10983 }
10984 editorDivBlur(event) {
10985 this.isEditing = false;
10986 }
10987 editorDivInput(event) {
10988 this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
10989 }
10990 disableEditing() {
10991 this.editorDiv.setAttribute("role", "comment");
10992 this.editorDiv.removeAttribute("aria-multiline");
10993 }
10994 enableEditing() {
10995 this.editorDiv.setAttribute("role", "textbox");
10996 this.editorDiv.setAttribute("aria-multiline", true);
10997 }
10998 render() {
10999 if (this.div) {
11000 return this.div;
11001 }
11002 let baseX, baseY;
11003 if (this.width) {
11004 baseX = this.x;
11005 baseY = this.y;
11006 }
11007 super.render();
11008 this.editorDiv = document.createElement("div");
11009 this.editorDiv.className = "internal";
11010 this.editorDiv.setAttribute("id", this.#editorDivId);
11011 this.enableEditing();
11012 FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
11013 FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
11014 this.editorDiv.contentEditable = true;
11015 const {
11016 style
11017 } = this.editorDiv;
11018 style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
11019 style.color = this.#color;
11020 this.div.append(this.editorDiv);
11021 this.overlayDiv = document.createElement("div");
11022 this.overlayDiv.classList.add("overlay", "enabled");
11023 this.div.append(this.overlayDiv);
11024 (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
11025 if (this.width) {
11026 const [parentWidth, parentHeight] = this.parentDimensions;
11027 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
11028 for (const line of this.#content.split("\n")) {
11029 const div = document.createElement("div");
11030 div.append(line ? document.createTextNode(line) : document.createElement("br"));
11031 this.editorDiv.append(div);
11032 }
11033 this.div.draggable = true;
11034 this.editorDiv.contentEditable = false;
11035 } else {
11036 this.div.draggable = false;
11037 this.editorDiv.contentEditable = true;
11038 }
11039 return this.div;
11040 }
11041 get contentDiv() {
11042 return this.editorDiv;
11043 }
11044 static deserialize(data, parent, uiManager) {
11045 const editor = super.deserialize(data, parent, uiManager);
11046 editor.#fontSize = data.fontSize;
11047 editor.#color = _util.Util.makeHexColor(...data.color);
11048 editor.#content = data.value;
11049 return editor;
11050 }
11051 serialize() {
11052 if (this.isEmpty()) {
11053 return null;
11054 }
11055 const padding = FreeTextEditor._internalPadding * this.parentScale;
11056 const rect = this.getRect(padding, padding);
11057 const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
11058 return {
11059 annotationType: _util.AnnotationEditorType.FREETEXT,
11060 color,
11061 fontSize: this.#fontSize,
11062 value: this.#content,
11063 pageIndex: this.pageIndex,
11064 rect,
11065 rotation: this.rotation
11066 };
11067 }
11068}
11069exports.FreeTextEditor = FreeTextEditor;
11070
11071/***/ }),
11072/* 29 */
11073/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11074
11075
11076
11077Object.defineProperty(exports, "__esModule", ({
11078 value: true
11079}));
11080exports.InkEditor = void 0;
11081Object.defineProperty(exports, "fitCurve", ({
11082 enumerable: true,
11083 get: function () {
11084 return _pdfjsFitCurve.fitCurve;
11085 }
11086}));
11087var _util = __w_pdfjs_require__(1);
11088var _editor = __w_pdfjs_require__(4);
11089var _pdfjsFitCurve = __w_pdfjs_require__(30);
11090var _tools = __w_pdfjs_require__(5);
11091const RESIZER_SIZE = 16;
11092const TIME_TO_WAIT_BEFORE_FIXING_DIMS = 100;
11093class InkEditor extends _editor.AnnotationEditor {
11094 #aspectRatio = 0;
11095 #baseHeight = 0;
11096 #baseWidth = 0;
11097 #boundCanvasPointermove = this.canvasPointermove.bind(this);
11098 #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
11099 #boundCanvasPointerup = this.canvasPointerup.bind(this);
11100 #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
11101 #disableEditing = false;
11102 #isCanvasInitialized = false;
11103 #lastPoint = null;
11104 #observer = null;
11105 #realWidth = 0;
11106 #realHeight = 0;
11107 #requestFrameCallback = null;
11108 static _defaultColor = null;
11109 static _defaultOpacity = 1;
11110 static _defaultThickness = 1;
11111 static _l10nPromise;
11112 static _type = "ink";
11113 constructor(params) {
11114 super({
11115 ...params,
11116 name: "inkEditor"
11117 });
11118 this.color = params.color || null;
11119 this.thickness = params.thickness || null;
11120 this.opacity = params.opacity || null;
11121 this.paths = [];
11122 this.bezierPath2D = [];
11123 this.currentPath = [];
11124 this.scaleFactor = 1;
11125 this.translationX = this.translationY = 0;
11126 this.x = 0;
11127 this.y = 0;
11128 }
11129 static initialize(l10n) {
11130 this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
11131 }
11132 static updateDefaultParams(type, value) {
11133 switch (type) {
11134 case _util.AnnotationEditorParamsType.INK_THICKNESS:
11135 InkEditor._defaultThickness = value;
11136 break;
11137 case _util.AnnotationEditorParamsType.INK_COLOR:
11138 InkEditor._defaultColor = value;
11139 break;
11140 case _util.AnnotationEditorParamsType.INK_OPACITY:
11141 InkEditor._defaultOpacity = value / 100;
11142 break;
11143 }
11144 }
11145 updateParams(type, value) {
11146 switch (type) {
11147 case _util.AnnotationEditorParamsType.INK_THICKNESS:
11148 this.#updateThickness(value);
11149 break;
11150 case _util.AnnotationEditorParamsType.INK_COLOR:
11151 this.#updateColor(value);
11152 break;
11153 case _util.AnnotationEditorParamsType.INK_OPACITY:
11154 this.#updateOpacity(value);
11155 break;
11156 }
11157 }
11158 static get defaultPropertiesToUpdate() {
11159 return [[_util.AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
11160 }
11161 get propertiesToUpdate() {
11162 return [[_util.AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
11163 }
11164 #updateThickness(thickness) {
11165 const savedThickness = this.thickness;
11166 this.addCommands({
11167 cmd: () => {
11168 this.thickness = thickness;
11169 this.#fitToContent();
11170 },
11171 undo: () => {
11172 this.thickness = savedThickness;
11173 this.#fitToContent();
11174 },
11175 mustExec: true,
11176 type: _util.AnnotationEditorParamsType.INK_THICKNESS,
11177 overwriteIfSameType: true,
11178 keepUndo: true
11179 });
11180 }
11181 #updateColor(color) {
11182 const savedColor = this.color;
11183 this.addCommands({
11184 cmd: () => {
11185 this.color = color;
11186 this.#redraw();
11187 },
11188 undo: () => {
11189 this.color = savedColor;
11190 this.#redraw();
11191 },
11192 mustExec: true,
11193 type: _util.AnnotationEditorParamsType.INK_COLOR,
11194 overwriteIfSameType: true,
11195 keepUndo: true
11196 });
11197 }
11198 #updateOpacity(opacity) {
11199 opacity /= 100;
11200 const savedOpacity = this.opacity;
11201 this.addCommands({
11202 cmd: () => {
11203 this.opacity = opacity;
11204 this.#redraw();
11205 },
11206 undo: () => {
11207 this.opacity = savedOpacity;
11208 this.#redraw();
11209 },
11210 mustExec: true,
11211 type: _util.AnnotationEditorParamsType.INK_OPACITY,
11212 overwriteIfSameType: true,
11213 keepUndo: true
11214 });
11215 }
11216 rebuild() {
11217 super.rebuild();
11218 if (this.div === null) {
11219 return;
11220 }
11221 if (!this.canvas) {
11222 this.#createCanvas();
11223 this.#createObserver();
11224 }
11225 if (!this.isAttachedToDOM) {
11226 this.parent.add(this);
11227 this.#setCanvasDims();
11228 }
11229 this.#fitToContent();
11230 }
11231 remove() {
11232 if (this.canvas === null) {
11233 return;
11234 }
11235 if (!this.isEmpty()) {
11236 this.commit();
11237 }
11238 this.canvas.width = this.canvas.height = 0;
11239 this.canvas.remove();
11240 this.canvas = null;
11241 this.#observer.disconnect();
11242 this.#observer = null;
11243 super.remove();
11244 }
11245 setParent(parent) {
11246 if (!this.parent && parent) {
11247 this._uiManager.removeShouldRescale(this);
11248 } else if (this.parent && parent === null) {
11249 this._uiManager.addShouldRescale(this);
11250 }
11251 super.setParent(parent);
11252 }
11253 onScaleChanging() {
11254 const [parentWidth, parentHeight] = this.parentDimensions;
11255 const width = this.width * parentWidth;
11256 const height = this.height * parentHeight;
11257 this.setDimensions(width, height);
11258 }
11259 enableEditMode() {
11260 if (this.#disableEditing || this.canvas === null) {
11261 return;
11262 }
11263 super.enableEditMode();
11264 this.div.draggable = false;
11265 this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
11266 this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
11267 }
11268 disableEditMode() {
11269 if (!this.isInEditMode() || this.canvas === null) {
11270 return;
11271 }
11272 super.disableEditMode();
11273 this.div.draggable = !this.isEmpty();
11274 this.div.classList.remove("editing");
11275 this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
11276 this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
11277 }
11278 onceAdded() {
11279 this.div.draggable = !this.isEmpty();
11280 }
11281 isEmpty() {
11282 return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
11283 }
11284 #getInitialBBox() {
11285 const {
11286 parentRotation,
11287 parentDimensions: [width, height]
11288 } = this;
11289 switch (parentRotation) {
11290 case 90:
11291 return [0, height, height, width];
11292 case 180:
11293 return [width, height, width, height];
11294 case 270:
11295 return [width, 0, height, width];
11296 default:
11297 return [0, 0, width, height];
11298 }
11299 }
11300 #setStroke() {
11301 const {
11302 ctx,
11303 color,
11304 opacity,
11305 thickness,
11306 parentScale,
11307 scaleFactor
11308 } = this;
11309 ctx.lineWidth = thickness * parentScale / scaleFactor;
11310 ctx.lineCap = "round";
11311 ctx.lineJoin = "round";
11312 ctx.miterLimit = 10;
11313 ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`;
11314 }
11315 #startDrawing(x, y) {
11316 this.isEditing = true;
11317 if (!this.#isCanvasInitialized) {
11318 this.#isCanvasInitialized = true;
11319 this.#setCanvasDims();
11320 this.thickness ||= InkEditor._defaultThickness;
11321 this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
11322 this.opacity ??= InkEditor._defaultOpacity;
11323 }
11324 this.currentPath.push([x, y]);
11325 this.#lastPoint = null;
11326 this.#setStroke();
11327 this.ctx.beginPath();
11328 this.ctx.moveTo(x, y);
11329 this.#requestFrameCallback = () => {
11330 if (!this.#requestFrameCallback) {
11331 return;
11332 }
11333 if (this.#lastPoint) {
11334 if (this.isEmpty()) {
11335 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
11336 this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
11337 } else {
11338 this.#redraw();
11339 }
11340 this.ctx.lineTo(...this.#lastPoint);
11341 this.#lastPoint = null;
11342 this.ctx.stroke();
11343 }
11344 window.requestAnimationFrame(this.#requestFrameCallback);
11345 };
11346 window.requestAnimationFrame(this.#requestFrameCallback);
11347 }
11348 #draw(x, y) {
11349 const [lastX, lastY] = this.currentPath.at(-1);
11350 if (x === lastX && y === lastY) {
11351 return;
11352 }
11353 this.currentPath.push([x, y]);
11354 this.#lastPoint = [x, y];
11355 }
11356 #stopDrawing(x, y) {
11357 this.ctx.closePath();
11358 this.#requestFrameCallback = null;
11359 x = Math.min(Math.max(x, 0), this.canvas.width);
11360 y = Math.min(Math.max(y, 0), this.canvas.height);
11361 const [lastX, lastY] = this.currentPath.at(-1);
11362 if (x !== lastX || y !== lastY) {
11363 this.currentPath.push([x, y]);
11364 }
11365 let bezier;
11366 if (this.currentPath.length !== 1) {
11367 bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
11368 } else {
11369 const xy = [x, y];
11370 bezier = [[xy, xy.slice(), xy.slice(), xy]];
11371 }
11372 const path2D = InkEditor.#buildPath2D(bezier);
11373 this.currentPath.length = 0;
11374 const cmd = () => {
11375 this.paths.push(bezier);
11376 this.bezierPath2D.push(path2D);
11377 this.rebuild();
11378 };
11379 const undo = () => {
11380 this.paths.pop();
11381 this.bezierPath2D.pop();
11382 if (this.paths.length === 0) {
11383 this.remove();
11384 } else {
11385 if (!this.canvas) {
11386 this.#createCanvas();
11387 this.#createObserver();
11388 }
11389 this.#fitToContent();
11390 }
11391 };
11392 this.addCommands({
11393 cmd,
11394 undo,
11395 mustExec: true
11396 });
11397 }
11398 #redraw() {
11399 if (this.isEmpty()) {
11400 this.#updateTransform();
11401 return;
11402 }
11403 this.#setStroke();
11404 const {
11405 canvas,
11406 ctx
11407 } = this;
11408 ctx.setTransform(1, 0, 0, 1, 0, 0);
11409 ctx.clearRect(0, 0, canvas.width, canvas.height);
11410 this.#updateTransform();
11411 for (const path of this.bezierPath2D) {
11412 ctx.stroke(path);
11413 }
11414 }
11415 commit() {
11416 if (this.#disableEditing) {
11417 return;
11418 }
11419 super.commit();
11420 this.isEditing = false;
11421 this.disableEditMode();
11422 this.setInForeground();
11423 this.#disableEditing = true;
11424 this.div.classList.add("disabled");
11425 this.#fitToContent(true);
11426 this.parent.addInkEditorIfNeeded(true);
11427 this.parent.moveEditorInDOM(this);
11428 this.div.focus({
11429 preventScroll: true
11430 });
11431 }
11432 focusin(event) {
11433 super.focusin(event);
11434 this.enableEditMode();
11435 }
11436 canvasPointerdown(event) {
11437 if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
11438 return;
11439 }
11440 this.setInForeground();
11441 if (event.type !== "mouse") {
11442 this.div.focus();
11443 }
11444 event.stopPropagation();
11445 this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
11446 this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
11447 this.#startDrawing(event.offsetX, event.offsetY);
11448 }
11449 canvasPointermove(event) {
11450 event.stopPropagation();
11451 this.#draw(event.offsetX, event.offsetY);
11452 }
11453 canvasPointerup(event) {
11454 if (event.button !== 0) {
11455 return;
11456 }
11457 if (this.isInEditMode() && this.currentPath.length !== 0) {
11458 event.stopPropagation();
11459 this.#endDrawing(event);
11460 this.setInBackground();
11461 }
11462 }
11463 canvasPointerleave(event) {
11464 this.#endDrawing(event);
11465 this.setInBackground();
11466 }
11467 #endDrawing(event) {
11468 this.#stopDrawing(event.offsetX, event.offsetY);
11469 this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
11470 this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
11471 this.addToAnnotationStorage();
11472 }
11473 #createCanvas() {
11474 this.canvas = document.createElement("canvas");
11475 this.canvas.width = this.canvas.height = 0;
11476 this.canvas.className = "inkEditorCanvas";
11477 InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
11478 this.div.append(this.canvas);
11479 const options = window.pdfDefaultOptions.activateWillReadFrequentlyFlag ? {
11480 willReadFrequently: true
11481 } : undefined;
11482 this.ctx = this.canvas.getContext("2d", options);
11483 }
11484 #createObserver() {
11485 let timeoutId = null;
11486 this.#observer = new ResizeObserver(entries => {
11487 const rect = entries[0].contentRect;
11488 if (rect.width && rect.height) {
11489 if (timeoutId !== null) {
11490 clearTimeout(timeoutId);
11491 }
11492 timeoutId = setTimeout(() => {
11493 this.fixDims();
11494 timeoutId = null;
11495 }, TIME_TO_WAIT_BEFORE_FIXING_DIMS);
11496 this.setDimensions(rect.width, rect.height);
11497 }
11498 });
11499 this.#observer.observe(this.div);
11500 }
11501 render() {
11502 if (this.div) {
11503 return this.div;
11504 }
11505 let baseX, baseY;
11506 if (this.width) {
11507 baseX = this.x;
11508 baseY = this.y;
11509 }
11510 super.render();
11511 InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
11512 const [x, y, w, h] = this.#getInitialBBox();
11513 this.setAt(x, y, 0, 0);
11514 this.setDims(w, h);
11515 this.#createCanvas();
11516 if (this.width) {
11517 const [parentWidth, parentHeight] = this.parentDimensions;
11518 this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
11519 this.#isCanvasInitialized = true;
11520 this.#setCanvasDims();
11521 this.setDims(this.width * parentWidth, this.height * parentHeight);
11522 this.#redraw();
11523 this.#setMinDims();
11524 this.div.classList.add("disabled");
11525 } else {
11526 this.div.classList.add("editing");
11527 this.enableEditMode();
11528 }
11529 this.#createObserver();
11530 return this.div;
11531 }
11532 #setCanvasDims() {
11533 if (!this.#isCanvasInitialized) {
11534 return;
11535 }
11536 const [parentWidth, parentHeight] = this.parentDimensions;
11537 this.canvas.width = Math.ceil(this.width * parentWidth);
11538 this.canvas.height = Math.ceil(this.height * parentHeight);
11539 this.#updateTransform();
11540 }
11541 setDimensions(width, height) {
11542 const roundedWidth = Math.round(width);
11543 const roundedHeight = Math.round(height);
11544 if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
11545 return;
11546 }
11547 this.#realWidth = roundedWidth;
11548 this.#realHeight = roundedHeight;
11549 this.canvas.style.visibility = "hidden";
11550 if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
11551 height = Math.ceil(width / this.#aspectRatio);
11552 this.setDims(width, height);
11553 }
11554 const [parentWidth, parentHeight] = this.parentDimensions;
11555 this.width = width / parentWidth;
11556 this.height = height / parentHeight;
11557 if (this.#disableEditing) {
11558 this.#setScaleFactor(width, height);
11559 }
11560 this.#setCanvasDims();
11561 this.#redraw();
11562 this.canvas.style.visibility = "visible";
11563 }
11564 #setScaleFactor(width, height) {
11565 const padding = this.#getPadding();
11566 const scaleFactorW = (width - padding) / this.#baseWidth;
11567 const scaleFactorH = (height - padding) / this.#baseHeight;
11568 this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
11569 }
11570 #updateTransform() {
11571 const padding = this.#getPadding() / 2;
11572 this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
11573 }
11574 static #buildPath2D(bezier) {
11575 const path2D = new Path2D();
11576 for (let i = 0, ii = bezier.length; i < ii; i++) {
11577 const [first, control1, control2, second] = bezier[i];
11578 if (i === 0) {
11579 path2D.moveTo(...first);
11580 }
11581 path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
11582 }
11583 return path2D;
11584 }
11585 #serializePaths(s, tx, ty, h) {
11586 const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
11587 const paths = [];
11588 const padding = this.thickness / 2;
11589 let buffer, points;
11590 for (const bezier of this.paths) {
11591 buffer = [];
11592 points = [];
11593 for (let i = 0, ii = bezier.length; i < ii; i++) {
11594 const [first, control1, control2, second] = bezier[i];
11595 const p10 = s * (first[0] + tx) + padding;
11596 const p11 = h - s * (first[1] + ty) - padding;
11597 const p20 = s * (control1[0] + tx) + padding;
11598 const p21 = h - s * (control1[1] + ty) - padding;
11599 const p30 = s * (control2[0] + tx) + padding;
11600 const p31 = h - s * (control2[1] + ty) - padding;
11601 const p40 = s * (second[0] + tx) + padding;
11602 const p41 = h - s * (second[1] + ty) - padding;
11603 if (i === 0) {
11604 buffer.push(p10, p11);
11605 points.push(p10, p11);
11606 }
11607 buffer.push(p20, p21, p30, p31, p40, p41);
11608 this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
11609 }
11610 paths.push({
11611 bezier: buffer,
11612 points
11613 });
11614 }
11615 return paths;
11616 }
11617 #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
11618 if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
11619 points.push(p40, p41);
11620 return;
11621 }
11622 for (let i = 1; i < n - 1; i++) {
11623 const t = i / n;
11624 const mt = 1 - t;
11625 let q10 = t * p10 + mt * p20;
11626 let q11 = t * p11 + mt * p21;
11627 let q20 = t * p20 + mt * p30;
11628 let q21 = t * p21 + mt * p31;
11629 const q30 = t * p30 + mt * p40;
11630 const q31 = t * p31 + mt * p41;
11631 q10 = t * q10 + mt * q20;
11632 q11 = t * q11 + mt * q21;
11633 q20 = t * q20 + mt * q30;
11634 q21 = t * q21 + mt * q31;
11635 q10 = t * q10 + mt * q20;
11636 q11 = t * q11 + mt * q21;
11637 points.push(q10, q11);
11638 }
11639 points.push(p40, p41);
11640 }
11641 #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
11642 const tol = 10;
11643 const ax = (3 * p20 - 2 * p10 - p40) ** 2;
11644 const ay = (3 * p21 - 2 * p11 - p41) ** 2;
11645 const bx = (3 * p30 - p10 - 2 * p40) ** 2;
11646 const by = (3 * p31 - p11 - 2 * p41) ** 2;
11647 return Math.max(ax, bx) + Math.max(ay, by) <= tol;
11648 }
11649 #getBbox() {
11650 let xMin = Infinity;
11651 let xMax = -Infinity;
11652 let yMin = Infinity;
11653 let yMax = -Infinity;
11654 for (const path of this.paths) {
11655 for (const [first, control1, control2, second] of path) {
11656 const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
11657 xMin = Math.min(xMin, bbox[0]);
11658 yMin = Math.min(yMin, bbox[1]);
11659 xMax = Math.max(xMax, bbox[2]);
11660 yMax = Math.max(yMax, bbox[3]);
11661 }
11662 }
11663 return [xMin, yMin, xMax, yMax];
11664 }
11665 #getPadding() {
11666 return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
11667 }
11668 #fitToContent(firstTime = false) {
11669 if (this.isEmpty()) {
11670 return;
11671 }
11672 if (!this.#disableEditing) {
11673 this.#redraw();
11674 return;
11675 }
11676 const bbox = this.#getBbox();
11677 const padding = this.#getPadding();
11678 this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
11679 this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
11680 const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
11681 const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
11682 const [parentWidth, parentHeight] = this.parentDimensions;
11683 this.width = width / parentWidth;
11684 this.height = height / parentHeight;
11685 this.#aspectRatio = width / height;
11686 this.#setMinDims();
11687 const prevTranslationX = this.translationX;
11688 const prevTranslationY = this.translationY;
11689 this.translationX = -bbox[0];
11690 this.translationY = -bbox[1];
11691 this.#setCanvasDims();
11692 this.#redraw();
11693 this.#realWidth = width;
11694 this.#realHeight = height;
11695 this.setDims(width, height);
11696 const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
11697 this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
11698 }
11699 #setMinDims() {
11700 const {
11701 style
11702 } = this.div;
11703 if (this.#aspectRatio >= 1) {
11704 style.minHeight = `${RESIZER_SIZE}px`;
11705 style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
11706 } else {
11707 style.minWidth = `${RESIZER_SIZE}px`;
11708 style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
11709 }
11710 }
11711 static deserialize(data, parent, uiManager) {
11712 const editor = super.deserialize(data, parent, uiManager);
11713 editor.thickness = data.thickness;
11714 editor.color = _util.Util.makeHexColor(...data.color);
11715 editor.opacity = data.opacity;
11716 const [pageWidth, pageHeight] = editor.pageDimensions;
11717 const width = editor.width * pageWidth;
11718 const height = editor.height * pageHeight;
11719 const scaleFactor = editor.parentScale;
11720 const padding = data.thickness / 2;
11721 editor.#aspectRatio = width / height;
11722 editor.#disableEditing = true;
11723 editor.#realWidth = Math.round(width);
11724 editor.#realHeight = Math.round(height);
11725 for (const {
11726 bezier
11727 } of data.paths) {
11728 const path = [];
11729 editor.paths.push(path);
11730 let p0 = scaleFactor * (bezier[0] - padding);
11731 let p1 = scaleFactor * (height - bezier[1] - padding);
11732 for (let i = 2, ii = bezier.length; i < ii; i += 6) {
11733 const p10 = scaleFactor * (bezier[i] - padding);
11734 const p11 = scaleFactor * (height - bezier[i + 1] - padding);
11735 const p20 = scaleFactor * (bezier[i + 2] - padding);
11736 const p21 = scaleFactor * (height - bezier[i + 3] - padding);
11737 const p30 = scaleFactor * (bezier[i + 4] - padding);
11738 const p31 = scaleFactor * (height - bezier[i + 5] - padding);
11739 path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
11740 p0 = p30;
11741 p1 = p31;
11742 }
11743 const path2D = this.#buildPath2D(path);
11744 editor.bezierPath2D.push(path2D);
11745 }
11746 const bbox = editor.#getBbox();
11747 editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
11748 editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
11749 editor.#setScaleFactor(width, height);
11750 return editor;
11751 }
11752 serialize() {
11753 if (this.isEmpty()) {
11754 return null;
11755 }
11756 const rect = this.getRect(0, 0);
11757 const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
11758 const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
11759 return {
11760 annotationType: _util.AnnotationEditorType.INK,
11761 color,
11762 thickness: this.thickness,
11763 opacity: this.opacity,
11764 paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, height),
11765 pageIndex: this.pageIndex,
11766 rect,
11767 rotation: this.rotation
11768 };
11769 }
11770}
11771exports.InkEditor = InkEditor;
11772
11773/***/ }),
11774/* 30 */
11775/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11776
11777
11778
11779Object.defineProperty(exports, "__esModule", ({
11780 value: true
11781}));
11782exports.fitCurve = void 0;
11783const fitCurve = __w_pdfjs_require__(31);
11784exports.fitCurve = fitCurve;
11785
11786/***/ }),
11787/* 31 */
11788/***/ ((module) => {
11789
11790
11791
11792function fitCurve(points, maxError, progressCallback) {
11793 if (!Array.isArray(points)) {
11794 throw new TypeError("First argument should be an array");
11795 }
11796 points.forEach(point => {
11797 if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
11798 throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
11799 }
11800 });
11801 points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
11802 if (points.length < 2) {
11803 return [];
11804 }
11805 const len = points.length;
11806 const leftTangent = createTangent(points[1], points[0]);
11807 const rightTangent = createTangent(points[len - 2], points[len - 1]);
11808 return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
11809}
11810function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
11811 const MaxIterations = 20;
11812 var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
11813 if (points.length === 2) {
11814 dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
11815 bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
11816 return [bezCurve];
11817 }
11818 u = chordLengthParameterize(points);
11819 [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
11820 if (maxError === 0 || maxError < error) {
11821 return [bezCurve];
11822 }
11823 if (maxError < error * error) {
11824 uPrime = u;
11825 prevErr = maxError;
11826 prevSplit = splitPoint;
11827 for (i = 0; i < MaxIterations; i++) {
11828 uPrime = reparameterize(bezCurve, points, uPrime);
11829 [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
11830 if (maxError < error) {
11831 return [bezCurve];
11832 } else if (splitPoint === prevSplit) {
11833 let errChange = maxError / prevErr;
11834 if (errChange > .9999 && errChange < 1.0001) {
11835 break;
11836 }
11837 }
11838 prevErr = maxError;
11839 prevSplit = splitPoint;
11840 }
11841 }
11842 beziers = [];
11843 centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
11844 if (centerVector.every(val => val === 0)) {
11845 centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
11846 [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
11847 }
11848 toCenterTangent = maths.normalize(centerVector);
11849 fromCenterTangent = maths.mulItems(toCenterTangent, -1);
11850 beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
11851 beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
11852 return beziers;
11853}
11854;
11855function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
11856 var bezCurve, maxError, splitPoint;
11857 bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
11858 [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
11859 if (progressCallback) {
11860 progressCallback({
11861 bez: bezCurve,
11862 points: points,
11863 params: paramsOrig,
11864 maxErr: maxError,
11865 maxPoint: splitPoint
11866 });
11867 }
11868 return [bezCurve, maxError, splitPoint];
11869}
11870function generateBezier(points, parameters, leftTangent, rightTangent) {
11871 var bezCurve,
11872 A,
11873 a,
11874 C,
11875 X,
11876 det_C0_C1,
11877 det_C0_X,
11878 det_X_C1,
11879 alpha_l,
11880 alpha_r,
11881 epsilon,
11882 segLength,
11883 i,
11884 len,
11885 tmp,
11886 u,
11887 ux,
11888 firstPoint = points[0],
11889 lastPoint = points[points.length - 1];
11890 bezCurve = [firstPoint, null, null, lastPoint];
11891 A = maths.zeros_Xx2x2(parameters.length);
11892 for (i = 0, len = parameters.length; i < len; i++) {
11893 u = parameters[i];
11894 ux = 1 - u;
11895 a = A[i];
11896 a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
11897 a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
11898 }
11899 C = [[0, 0], [0, 0]];
11900 X = [0, 0];
11901 for (i = 0, len = points.length; i < len; i++) {
11902 u = parameters[i];
11903 a = A[i];
11904 C[0][0] += maths.dot(a[0], a[0]);
11905 C[0][1] += maths.dot(a[0], a[1]);
11906 C[1][0] += maths.dot(a[0], a[1]);
11907 C[1][1] += maths.dot(a[1], a[1]);
11908 tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
11909 X[0] += maths.dot(a[0], tmp);
11910 X[1] += maths.dot(a[1], tmp);
11911 }
11912 det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
11913 det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
11914 det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
11915 alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
11916 alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
11917 segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
11918 epsilon = 1.0e-6 * segLength;
11919 if (alpha_l < epsilon || alpha_r < epsilon) {
11920 bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
11921 bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
11922 } else {
11923 bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
11924 bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
11925 }
11926 return bezCurve;
11927}
11928;
11929function reparameterize(bezier, points, parameters) {
11930 return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
11931}
11932;
11933function newtonRaphsonRootFind(bez, point, u) {
11934 var d = maths.subtract(bezier.q(bez, u), point),
11935 qprime = bezier.qprime(bez, u),
11936 numerator = maths.mulMatrix(d, qprime),
11937 denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
11938 if (denominator === 0) {
11939 return u;
11940 } else {
11941 return u - numerator / denominator;
11942 }
11943}
11944;
11945function chordLengthParameterize(points) {
11946 var u = [],
11947 currU,
11948 prevU,
11949 prevP;
11950 points.forEach((p, i) => {
11951 currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
11952 u.push(currU);
11953 prevU = currU;
11954 prevP = p;
11955 });
11956 u = u.map(x => x / prevU);
11957 return u;
11958}
11959;
11960function computeMaxError(points, bez, parameters) {
11961 var dist, maxDist, splitPoint, v, i, count, point, t;
11962 maxDist = 0;
11963 splitPoint = Math.floor(points.length / 2);
11964 const t_distMap = mapTtoRelativeDistances(bez, 10);
11965 for (i = 0, count = points.length; i < count; i++) {
11966 point = points[i];
11967 t = find_t(bez, parameters[i], t_distMap, 10);
11968 v = maths.subtract(bezier.q(bez, t), point);
11969 dist = v[0] * v[0] + v[1] * v[1];
11970 if (dist > maxDist) {
11971 maxDist = dist;
11972 splitPoint = i;
11973 }
11974 }
11975 return [maxDist, splitPoint];
11976}
11977;
11978var mapTtoRelativeDistances = function (bez, B_parts) {
11979 var B_t_curr;
11980 var B_t_dist = [0];
11981 var B_t_prev = bez[0];
11982 var sumLen = 0;
11983 for (var i = 1; i <= B_parts; i++) {
11984 B_t_curr = bezier.q(bez, i / B_parts);
11985 sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
11986 B_t_dist.push(sumLen);
11987 B_t_prev = B_t_curr;
11988 }
11989 B_t_dist = B_t_dist.map(x => x / sumLen);
11990 return B_t_dist;
11991};
11992function find_t(bez, param, t_distMap, B_parts) {
11993 if (param < 0) {
11994 return 0;
11995 }
11996 if (param > 1) {
11997 return 1;
11998 }
11999 var lenMax, lenMin, tMax, tMin, t;
12000 for (var i = 1; i <= B_parts; i++) {
12001 if (param <= t_distMap[i]) {
12002 tMin = (i - 1) / B_parts;
12003 tMax = i / B_parts;
12004 lenMin = t_distMap[i - 1];
12005 lenMax = t_distMap[i];
12006 t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
12007 break;
12008 }
12009 }
12010 return t;
12011}
12012function createTangent(pointA, pointB) {
12013 return maths.normalize(maths.subtract(pointA, pointB));
12014}
12015class maths {
12016 static zeros_Xx2x2(x) {
12017 var zs = [];
12018 while (x--) {
12019 zs.push([0, 0]);
12020 }
12021 return zs;
12022 }
12023 static mulItems(items, multiplier) {
12024 return items.map(x => x * multiplier);
12025 }
12026 static mulMatrix(m1, m2) {
12027 return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
12028 }
12029 static subtract(arr1, arr2) {
12030 return arr1.map((x1, i) => x1 - arr2[i]);
12031 }
12032 static addArrays(arr1, arr2) {
12033 return arr1.map((x1, i) => x1 + arr2[i]);
12034 }
12035 static addItems(items, addition) {
12036 return items.map(x => x + addition);
12037 }
12038 static sum(items) {
12039 return items.reduce((sum, x) => sum + x);
12040 }
12041 static dot(m1, m2) {
12042 return maths.mulMatrix(m1, m2);
12043 }
12044 static vectorLen(v) {
12045 return Math.hypot(...v);
12046 }
12047 static divItems(items, divisor) {
12048 return items.map(x => x / divisor);
12049 }
12050 static squareItems(items) {
12051 return items.map(x => x * x);
12052 }
12053 static normalize(v) {
12054 return this.divItems(v, this.vectorLen(v));
12055 }
12056}
12057class bezier {
12058 static q(ctrlPoly, t) {
12059 var tx = 1.0 - t;
12060 var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
12061 pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
12062 pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
12063 pD = maths.mulItems(ctrlPoly[3], t * t * t);
12064 return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
12065 }
12066 static qprime(ctrlPoly, t) {
12067 var tx = 1.0 - t;
12068 var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
12069 pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
12070 pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
12071 return maths.addArrays(maths.addArrays(pA, pB), pC);
12072 }
12073 static qprimeprime(ctrlPoly, t) {
12074 return maths.addArrays(maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[2], maths.mulItems(ctrlPoly[1], 2)), ctrlPoly[0]), 6 * (1.0 - t)), maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[3], maths.mulItems(ctrlPoly[2], 2)), ctrlPoly[1]), 6 * t));
12075 }
12076}
12077module.exports = fitCurve;
12078module.exports.fitCubic = fitCubic;
12079module.exports.createTangent = createTangent;
12080
12081/***/ }),
12082/* 32 */
12083/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
12084
12085
12086
12087Object.defineProperty(exports, "__esModule", ({
12088 value: true
12089}));
12090exports.AnnotationLayer = void 0;
12091var _util = __w_pdfjs_require__(1);
12092var _display_utils = __w_pdfjs_require__(6);
12093var _annotation_storage = __w_pdfjs_require__(3);
12094var _scripting_utils = __w_pdfjs_require__(33);
12095var _xfa_layer = __w_pdfjs_require__(34);
12096const DEFAULT_TAB_INDEX = 1000;
12097const DEFAULT_FONT_SIZE = 9;
12098const GetElementsByNameSet = new WeakSet();
12099function getRectDims(rect) {
12100 return {
12101 width: rect[2] - rect[0],
12102 height: rect[3] - rect[1]
12103 };
12104}
12105class AnnotationElementFactory {
12106 static create(parameters) {
12107 const subtype = parameters.data.annotationType;
12108 switch (subtype) {
12109 case _util.AnnotationType.LINK:
12110 return new LinkAnnotationElement(parameters);
12111 case _util.AnnotationType.TEXT:
12112 return new TextAnnotationElement(parameters);
12113 case _util.AnnotationType.WIDGET:
12114 const fieldType = parameters.data.fieldType;
12115 switch (fieldType) {
12116 case "Tx":
12117 return new TextWidgetAnnotationElement(parameters);
12118 case "Btn":
12119 if (parameters.data.radioButton) {
12120 return new RadioButtonWidgetAnnotationElement(parameters);
12121 } else if (parameters.data.checkBox) {
12122 return new CheckboxWidgetAnnotationElement(parameters);
12123 }
12124 return new PushButtonWidgetAnnotationElement(parameters);
12125 case "Ch":
12126 return new ChoiceWidgetAnnotationElement(parameters);
12127 }
12128 return new WidgetAnnotationElement(parameters);
12129 case _util.AnnotationType.POPUP:
12130 return new PopupAnnotationElement(parameters);
12131 case _util.AnnotationType.FREETEXT:
12132 return new FreeTextAnnotationElement(parameters);
12133 case _util.AnnotationType.LINE:
12134 return new LineAnnotationElement(parameters);
12135 case _util.AnnotationType.SQUARE:
12136 return new SquareAnnotationElement(parameters);
12137 case _util.AnnotationType.CIRCLE:
12138 return new CircleAnnotationElement(parameters);
12139 case _util.AnnotationType.POLYLINE:
12140 return new PolylineAnnotationElement(parameters);
12141 case _util.AnnotationType.CARET:
12142 return new CaretAnnotationElement(parameters);
12143 case _util.AnnotationType.INK:
12144 return new InkAnnotationElement(parameters);
12145 case _util.AnnotationType.POLYGON:
12146 return new PolygonAnnotationElement(parameters);
12147 case _util.AnnotationType.HIGHLIGHT:
12148 return new HighlightAnnotationElement(parameters);
12149 case _util.AnnotationType.UNDERLINE:
12150 return new UnderlineAnnotationElement(parameters);
12151 case _util.AnnotationType.SQUIGGLY:
12152 return new SquigglyAnnotationElement(parameters);
12153 case _util.AnnotationType.STRIKEOUT:
12154 return new StrikeOutAnnotationElement(parameters);
12155 case _util.AnnotationType.STAMP:
12156 return new StampAnnotationElement(parameters);
12157 case _util.AnnotationType.FILEATTACHMENT:
12158 return new FileAttachmentAnnotationElement(parameters);
12159 default:
12160 return new AnnotationElement(parameters);
12161 }
12162 }
12163}
12164class AnnotationElement {
12165 constructor(parameters, {
12166 isRenderable = false,
12167 ignoreBorder = false,
12168 createQuadrilaterals = false
12169 } = {}) {
12170 this.isRenderable = isRenderable;
12171 this.data = parameters.data;
12172 this.layer = parameters.layer;
12173 this.page = parameters.page;
12174 this.viewport = parameters.viewport;
12175 this.linkService = parameters.linkService;
12176 this.downloadManager = parameters.downloadManager;
12177 this.imageResourcesPath = parameters.imageResourcesPath;
12178 this.renderForms = parameters.renderForms;
12179 this.svgFactory = parameters.svgFactory;
12180 this.annotationStorage = parameters.annotationStorage;
12181 this.enableScripting = parameters.enableScripting;
12182 this.hasJSActions = parameters.hasJSActions;
12183 this._fieldObjects = parameters.fieldObjects;
12184 if (isRenderable) {
12185 this.container = this._createContainer(ignoreBorder);
12186 }
12187 if (createQuadrilaterals) {
12188 this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
12189 }
12190 }
12191 _createContainer(ignoreBorder = false) {
12192 const {
12193 data,
12194 page,
12195 viewport
12196 } = this;
12197 const container = document.createElement("section");
12198 container.setAttribute("data-annotation-id", data.id);
12199 const {
12200 pageWidth,
12201 pageHeight,
12202 pageX,
12203 pageY
12204 } = viewport.rawDims;
12205 const {
12206 width,
12207 height
12208 } = getRectDims(data.rect);
12209 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]]);
12210 if (!ignoreBorder && data.borderStyle.width > 0) {
12211 container.style.borderWidth = `${data.borderStyle.width}px`;
12212 const horizontalRadius = data.borderStyle.horizontalCornerRadius;
12213 const verticalRadius = data.borderStyle.verticalCornerRadius;
12214 if (horizontalRadius > 0 || verticalRadius > 0) {
12215 const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
12216 container.style.borderRadius = radius;
12217 } else if (this instanceof RadioButtonWidgetAnnotationElement) {
12218 const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
12219 container.style.borderRadius = radius;
12220 }
12221 switch (data.borderStyle.style) {
12222 case _util.AnnotationBorderStyleType.SOLID:
12223 container.style.borderStyle = "solid";
12224 break;
12225 case _util.AnnotationBorderStyleType.DASHED:
12226 container.style.borderStyle = "dashed";
12227 break;
12228 case _util.AnnotationBorderStyleType.BEVELED:
12229 (0, _util.warn)("Unimplemented border style: beveled");
12230 break;
12231 case _util.AnnotationBorderStyleType.INSET:
12232 (0, _util.warn)("Unimplemented border style: inset");
12233 break;
12234 case _util.AnnotationBorderStyleType.UNDERLINE:
12235 container.style.borderBottomStyle = "solid";
12236 break;
12237 default:
12238 break;
12239 }
12240 const borderColor = data.borderColor || null;
12241 if (borderColor) {
12242 container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
12243 } else {
12244 container.style.borderWidth = 0;
12245 }
12246 }
12247 container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
12248 container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
12249 const {
12250 rotation
12251 } = data;
12252 if (data.hasOwnCanvas || rotation === 0) {
12253 container.style.width = `${100 * width / pageWidth}%`;
12254 container.style.height = `${100 * height / pageHeight}%`;
12255 } else {
12256 this.setRotation(rotation, container);
12257 }
12258 return container;
12259 }
12260 setRotation(angle, container = this.container) {
12261 const {
12262 pageWidth,
12263 pageHeight
12264 } = this.viewport.rawDims;
12265 const {
12266 width,
12267 height
12268 } = getRectDims(this.data.rect);
12269 let elementWidth, elementHeight;
12270 if (angle % 180 === 0) {
12271 elementWidth = 100 * width / pageWidth;
12272 elementHeight = 100 * height / pageHeight;
12273 } else {
12274 elementWidth = 100 * height / pageWidth;
12275 elementHeight = 100 * width / pageHeight;
12276 }
12277 container.style.width = `${elementWidth}%`;
12278 container.style.height = `${elementHeight}%`;
12279 container.setAttribute("data-main-rotation", (360 - angle) % 360);
12280 }
12281 get _commonActions() {
12282 const setColor = (jsName, styleName, event) => {
12283 const color = event.detail[jsName];
12284 event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
12285 };
12286 return (0, _util.shadow)(this, "_commonActions", {
12287 display: event => {
12288 const hidden = event.detail.display % 2 === 1;
12289 this.container.style.visibility = hidden ? "hidden" : "visible";
12290 this.annotationStorage.setValue(this.data.id, this.data.fieldName, {
12291 hidden,
12292 print: event.detail.display === 0 || event.detail.display === 3
12293 });
12294 },
12295 print: event => {
12296 this.annotationStorage.setValue(this.data.id, this.data.fieldName, {
12297 print: event.detail.print
12298 });
12299 },
12300 hidden: event => {
12301 this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
12302 this.annotationStorage.setValue(this.data.id, this.data.fieldName, {
12303 hidden: event.detail.hidden
12304 });
12305 },
12306 focus: event => {
12307 setTimeout(() => event.target.focus({
12308 preventScroll: false
12309 }), 0);
12310 },
12311 userName: event => {
12312 event.target.title = event.detail.userName;
12313 },
12314 readonly: event => {
12315 if (event.detail.readonly) {
12316 event.target.setAttribute("readonly", "");
12317 } else {
12318 event.target.removeAttribute("readonly");
12319 }
12320 },
12321 required: event => {
12322 this._setRequired(event.target, event.detail.required);
12323 },
12324 bgColor: event => {
12325 setColor("bgColor", "backgroundColor", event);
12326 },
12327 fillColor: event => {
12328 setColor("fillColor", "backgroundColor", event);
12329 },
12330 fgColor: event => {
12331 setColor("fgColor", "color", event);
12332 },
12333 textColor: event => {
12334 setColor("textColor", "color", event);
12335 },
12336 borderColor: event => {
12337 setColor("borderColor", "borderColor", event);
12338 },
12339 strokeColor: event => {
12340 setColor("strokeColor", "borderColor", event);
12341 },
12342 rotation: event => {
12343 const angle = event.detail.rotation;
12344 this.setRotation(angle);
12345 this.annotationStorage.setValue(this.data.id, this.data.fieldName, {
12346 rotation: angle
12347 });
12348 }
12349 });
12350 }
12351 _dispatchEventFromSandbox(actions, jsEvent) {
12352 const commonActions = this._commonActions;
12353 for (const name of Object.keys(jsEvent.detail)) {
12354 const action = actions[name] || commonActions[name];
12355 action?.(jsEvent);
12356 }
12357 }
12358 _setDefaultPropertiesFromJS(element) {
12359 if (!this.enableScripting) {
12360 return;
12361 }
12362 const storedData = this.annotationStorage.getRawValue(this.data.id);
12363 if (!storedData) {
12364 return;
12365 }
12366 const commonActions = this._commonActions;
12367 for (const [actionName, detail] of Object.entries(storedData)) {
12368 const action = commonActions[actionName];
12369 if (action) {
12370 const eventProxy = {
12371 detail: {
12372 [actionName]: detail
12373 },
12374 target: element
12375 };
12376 action(eventProxy);
12377 delete storedData[actionName];
12378 }
12379 }
12380 }
12381 _createQuadrilaterals(ignoreBorder = false) {
12382 if (!this.data.quadPoints) {
12383 return null;
12384 }
12385 const quadrilaterals = [];
12386 const savedRect = this.data.rect;
12387 for (const quadPoint of this.data.quadPoints) {
12388 this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
12389 quadrilaterals.push(this._createContainer(ignoreBorder));
12390 }
12391 this.data.rect = savedRect;
12392 return quadrilaterals;
12393 }
12394 _createPopup(trigger, data) {
12395 let container = this.container;
12396 if (this.quadrilaterals) {
12397 trigger = trigger || this.quadrilaterals;
12398 container = this.quadrilaterals[0];
12399 }
12400 if (!trigger) {
12401 trigger = document.createElement("div");
12402 trigger.className = "popupTriggerArea";
12403 container.append(trigger);
12404 }
12405 const popupElement = new PopupElement({
12406 container,
12407 trigger,
12408 color: data.color,
12409 titleObj: data.titleObj,
12410 modificationDate: data.modificationDate,
12411 contentsObj: data.contentsObj,
12412 richText: data.richText,
12413 hideWrapper: true
12414 });
12415 const popup = popupElement.render();
12416 popup.style.left = "100%";
12417 container.append(popup);
12418 }
12419 _renderQuadrilaterals(className) {
12420 for (const quadrilateral of this.quadrilaterals) {
12421 quadrilateral.className = className;
12422 }
12423 return this.quadrilaterals;
12424 }
12425 render() {
12426 (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
12427 }
12428 _getElementsByName(name, skipId = null) {
12429 const fields = [];
12430 if (this._fieldObjects) {
12431 const fieldObj = this._fieldObjects[name];
12432 if (fieldObj) {
12433 for (const {
12434 page,
12435 id,
12436 exportValues
12437 } of fieldObj) {
12438 if (page === -1) {
12439 continue;
12440 }
12441 if (id === skipId) {
12442 continue;
12443 }
12444 const exportValue = typeof exportValues === "string" ? exportValues : null;
12445 const domElement = document.querySelector(`[data-element-id="${id}"]`);
12446 if (domElement && !GetElementsByNameSet.has(domElement)) {
12447 (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
12448 continue;
12449 }
12450 fields.push({
12451 id,
12452 exportValue,
12453 domElement
12454 });
12455 }
12456 }
12457 return fields;
12458 }
12459 for (const domElement of document.getElementsByName(name)) {
12460 const {
12461 exportValue
12462 } = domElement;
12463 const id = domElement.getAttribute("data-element-id");
12464 if (id === skipId) {
12465 continue;
12466 }
12467 if (!GetElementsByNameSet.has(domElement)) {
12468 continue;
12469 }
12470 fields.push({
12471 id,
12472 exportValue,
12473 domElement
12474 });
12475 }
12476 return fields;
12477 }
12478}
12479class LinkAnnotationElement extends AnnotationElement {
12480 constructor(parameters, options = null) {
12481 super(parameters, {
12482 isRenderable: true,
12483 ignoreBorder: !!options?.ignoreBorder,
12484 createQuadrilaterals: true
12485 });
12486 this.isTooltipOnly = parameters.data.isTooltipOnly;
12487 }
12488 render() {
12489 const {
12490 data,
12491 linkService
12492 } = this;
12493 const link = document.createElement("a");
12494 link.setAttribute("data-element-id", data.id);
12495 let isBound = false;
12496 if (data.url) {
12497 linkService.addLinkAttributes(link, data.url, data.newWindow);
12498 isBound = true;
12499 } else if (data.action) {
12500 this._bindNamedAction(link, data.action);
12501 isBound = true;
12502 } else if (data.attachment) {
12503 this._bindAttachment(link, data.attachment);
12504 isBound = true;
12505 } else if (data.setOCGState) {
12506 this.#bindSetOCGState(link, data.setOCGState);
12507 isBound = true;
12508 } else if (data.dest) {
12509 this._bindLink(link, data.dest);
12510 isBound = true;
12511 } else {
12512 if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
12513 this._bindJSAction(link, data);
12514 isBound = true;
12515 }
12516 if (data.resetForm) {
12517 this._bindResetFormAction(link, data.resetForm);
12518 isBound = true;
12519 } else if (this.isTooltipOnly && !isBound) {
12520 this._bindLink(link, "");
12521 isBound = true;
12522 }
12523 }
12524 if (this.quadrilaterals) {
12525 return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
12526 const linkElement = index === 0 ? link : link.cloneNode();
12527 quadrilateral.append(linkElement);
12528 return quadrilateral;
12529 });
12530 }
12531 this.container.className = "linkAnnotation";
12532 if (isBound) {
12533 this.container.append(link);
12534 }
12535 return this.container;
12536 }
12537 #setInternalLink() {
12538 this.container.setAttribute("data-internal-link", "");
12539 }
12540 _bindLink(link, destination) {
12541 link.href = this.linkService.getDestinationHash(destination);
12542 link.onclick = () => {
12543 if (destination) {
12544 this.linkService.goToDestination(destination);
12545 }
12546 return false;
12547 };
12548 if (destination || destination === "") {
12549 this.#setInternalLink();
12550 }
12551 }
12552 _bindNamedAction(link, action) {
12553 link.href = this.linkService.getAnchorUrl("");
12554 link.onclick = () => {
12555 this.linkService.executeNamedAction(action);
12556 return false;
12557 };
12558 this.#setInternalLink();
12559 }
12560 _bindAttachment(link, attachment) {
12561 link.href = this.linkService.getAnchorUrl("");
12562 link.onclick = () => {
12563 this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
12564 return false;
12565 };
12566 this.#setInternalLink();
12567 }
12568 #bindSetOCGState(link, action) {
12569 link.href = this.linkService.getAnchorUrl("");
12570 link.onclick = () => {
12571 this.linkService.executeSetOCGState(action);
12572 return false;
12573 };
12574 this.#setInternalLink();
12575 }
12576 _bindJSAction(link, data) {
12577 link.href = this.linkService.getAnchorUrl("");
12578 const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
12579 for (const name of Object.keys(data.actions)) {
12580 const jsName = map.get(name);
12581 if (!jsName) {
12582 continue;
12583 }
12584 link[jsName] = () => {
12585 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12586 source: this,
12587 detail: {
12588 id: data.id,
12589 name
12590 }
12591 });
12592 return false;
12593 };
12594 }
12595 if (!link.onclick) {
12596 link.onclick = () => false;
12597 }
12598 this.#setInternalLink();
12599 }
12600 _bindResetFormAction(link, resetForm) {
12601 const otherClickAction = link.onclick;
12602 if (!otherClickAction) {
12603 link.href = this.linkService.getAnchorUrl("");
12604 }
12605 this.#setInternalLink();
12606 if (!this._fieldObjects) {
12607 (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
12608 if (!otherClickAction) {
12609 link.onclick = () => false;
12610 }
12611 return;
12612 }
12613 link.onclick = () => {
12614 otherClickAction?.();
12615 const {
12616 fields: resetFormFields,
12617 refs: resetFormRefs,
12618 include
12619 } = resetForm;
12620 const allFields = [];
12621 if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
12622 const fieldIds = new Set(resetFormRefs);
12623 for (const fieldName of resetFormFields) {
12624 const fields = this._fieldObjects[fieldName] || [];
12625 for (const {
12626 id
12627 } of fields) {
12628 fieldIds.add(id);
12629 }
12630 }
12631 for (const fields of Object.values(this._fieldObjects)) {
12632 for (const field of fields) {
12633 if (fieldIds.has(field.id) === include) {
12634 allFields.push(field);
12635 }
12636 }
12637 }
12638 } else {
12639 for (const fields of Object.values(this._fieldObjects)) {
12640 allFields.push(...fields);
12641 }
12642 }
12643 const storage = this.annotationStorage;
12644 const allIds = [];
12645 for (const field of allFields) {
12646 const {
12647 id
12648 } = field;
12649 allIds.push(id);
12650 switch (field.type) {
12651 case "text":
12652 {
12653 const value = field.defaultValue || "";
12654 storage.setValue(id, this.data.fieldName, {
12655 value
12656 });
12657 break;
12658 }
12659 case "checkbox":
12660 case "radiobutton":
12661 {
12662 const value = field.defaultValue === field.exportValues;
12663 storage.setValue(id, this.data.fieldName, {
12664 value
12665 });
12666 break;
12667 }
12668 case "combobox":
12669 case "listbox":
12670 {
12671 const value = field.defaultValue || "";
12672 storage.setValue(id, this.data.fieldName, {
12673 value
12674 });
12675 break;
12676 }
12677 default:
12678 continue;
12679 }
12680 const domElement = document.querySelector(`[data-element-id="${id}"]`);
12681 if (!domElement) {
12682 continue;
12683 } else if (!GetElementsByNameSet.has(domElement)) {
12684 (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
12685 continue;
12686 }
12687 domElement.dispatchEvent(new Event("resetform"));
12688 }
12689 if (this.enableScripting) {
12690 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12691 source: this,
12692 detail: {
12693 id: "app",
12694 ids: allIds,
12695 name: "ResetForm"
12696 }
12697 });
12698 }
12699 return false;
12700 };
12701 }
12702}
12703class TextAnnotationElement extends AnnotationElement {
12704 constructor(parameters) {
12705 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
12706 super(parameters, {
12707 isRenderable
12708 });
12709 }
12710 render() {
12711 this.container.className = "textAnnotation";
12712 const image = document.createElement("img");
12713 image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
12714 image.alt = "[{{type}} Annotation]";
12715 image.dataset.l10nId = "text_annotation_type";
12716 image.dataset.l10nArgs = JSON.stringify({
12717 type: this.data.name
12718 });
12719 if (!this.data.hasPopup) {
12720 this._createPopup(image, this.data);
12721 }
12722 this.container.append(image);
12723 return this.container;
12724 }
12725}
12726class WidgetAnnotationElement extends AnnotationElement {
12727 render() {
12728 if (this.data.alternativeText) {
12729 this.container.title = this.data.alternativeText;
12730 }
12731 return this.container;
12732 }
12733 _getKeyModifier(event) {
12734 const {
12735 isWin,
12736 isMac
12737 } = _util.FeatureTest.platform;
12738 return isWin && event.ctrlKey || isMac && event.metaKey;
12739 }
12740 _setEventListener(element, baseName, eventName, valueGetter) {
12741 if (baseName.includes("mouse")) {
12742 element.addEventListener(baseName, event => {
12743 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12744 source: this,
12745 detail: {
12746 id: this.data.id,
12747 name: eventName,
12748 value: valueGetter(event),
12749 shift: event.shiftKey,
12750 modifier: this._getKeyModifier(event)
12751 }
12752 });
12753 });
12754 } else {
12755 element.addEventListener(baseName, event => {
12756 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12757 source: this,
12758 detail: {
12759 id: this.data.id,
12760 name: eventName,
12761 value: valueGetter(event)
12762 }
12763 });
12764 });
12765 }
12766 }
12767 _setEventListeners(element, names, getter) {
12768 for (const [baseName, eventName] of names) {
12769 if (eventName === "Action" || this.data.actions?.[eventName]) {
12770 this._setEventListener(element, baseName, eventName, getter);
12771 }
12772 }
12773 }
12774 _setBackgroundColor(element) {
12775 const color = this.data.backgroundColor || null;
12776 element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
12777 }
12778 _setTextStyle(element) {
12779 const TEXT_ALIGNMENT = ["left", "center", "right"];
12780 const {
12781 fontColor
12782 } = this.data.defaultAppearanceData;
12783 const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
12784 const style = element.style;
12785 let computedFontSize;
12786 const BORDER_SIZE = 2;
12787 const roundToOneDecimal = x => Math.round(10 * x) / 10;
12788 if (this.data.multiLine) {
12789 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
12790 const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
12791 const lineHeight = height / numberOfLines;
12792 computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
12793 } else {
12794 const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
12795 computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
12796 }
12797 style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
12798 style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
12799 if (this.data.textAlignment !== null) {
12800 style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
12801 }
12802 }
12803 _setRequired(element, isRequired) {
12804 if (isRequired) {
12805 element.setAttribute("required", true);
12806 } else {
12807 element.removeAttribute("required");
12808 }
12809 element.setAttribute("aria-required", isRequired);
12810 }
12811}
12812class TextWidgetAnnotationElement extends WidgetAnnotationElement {
12813 constructor(parameters) {
12814 const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
12815 super(parameters, {
12816 isRenderable
12817 });
12818 }
12819 setPropertyOnSiblings(base, key, value, keyInStorage) {
12820 const storage = this.annotationStorage;
12821 for (const element of this._getElementsByName(base.name, base.id)) {
12822 if (element.domElement) {
12823 element.domElement[key] = value;
12824 }
12825 storage.setValue(element.id, this.data.fieldName, {
12826 [keyInStorage]: value
12827 });
12828 }
12829 }
12830 render() {
12831 const storage = this.annotationStorage;
12832 const id = this.data.id;
12833 this.container.className = "textWidgetAnnotation";
12834 let element = null;
12835 if (this.renderForms) {
12836 const storedData = storage.getValue(id, this.data.fieldName, {
12837 value: this.data.fieldValue
12838 });
12839 let textContent = storedData.formattedValue || storedData.value || "";
12840 const maxLen = storage.getValue(id, this.data.fieldName, {
12841 charLimit: this.data.maxLen
12842 }).charLimit;
12843 if (maxLen && textContent.length > maxLen) {
12844 textContent = textContent.slice(0, maxLen);
12845 }
12846 const elementData = {
12847 userValue: textContent,
12848 formattedValue: null,
12849 lastCommittedValue: null,
12850 commitKey: 1
12851 };
12852 if (this.data.multiLine) {
12853 element = document.createElement("textarea");
12854 element.textContent = textContent;
12855 if (this.data.doNotScroll) {
12856 element.style.overflowY = "hidden";
12857 }
12858 } else {
12859 element = document.createElement("input");
12860 element.type = "text";
12861 element.setAttribute("value", textContent);
12862 if (this.data.doNotScroll) {
12863 element.style.overflowX = "hidden";
12864 }
12865 }
12866 GetElementsByNameSet.add(element);
12867 element.setAttribute("data-element-id", id);
12868 element.disabled = this.data.readOnly;
12869 element.name = this.data.fieldName;
12870 element.tabIndex = DEFAULT_TAB_INDEX;
12871 this._setRequired(element, this.data.required);
12872 if (maxLen) {
12873 element.maxLength = maxLen;
12874 }
12875 element.addEventListener("input", event => {
12876 storage.setValue(id, this.data.fieldName, {
12877 value: event.target.value
12878 });
12879 this.setPropertyOnSiblings(element, "value", event.target.value, "value");
12880 });
12881 element.addEventListener("resetform", event => {
12882 const defaultValue = this.data.defaultFieldValue ?? "";
12883 element.value = elementData.userValue = defaultValue;
12884 elementData.formattedValue = null;
12885 });
12886 let blurListener = event => {
12887 const {
12888 formattedValue
12889 } = elementData;
12890 if (formattedValue !== null && formattedValue !== undefined) {
12891 event.target.value = formattedValue;
12892 }
12893 event.target.scrollLeft = 0;
12894 };
12895 if (this.enableScripting && this.hasJSActions) {
12896 element.addEventListener("focus", event => {
12897 const {
12898 target
12899 } = event;
12900 if (elementData.userValue) {
12901 target.value = elementData.userValue;
12902 }
12903 elementData.lastCommittedValue = target.value;
12904 elementData.commitKey = 1;
12905 });
12906 const fieldName = this.data.fieldName;
12907 element.addEventListener("updatefromsandbox", jsEvent => {
12908 const actions = {
12909 value(event) {
12910 elementData.userValue = event.detail.value ?? "";
12911 storage.setValue(id, fieldName, {
12912 value: elementData.userValue.toString()
12913 });
12914 event.target.value = elementData.userValue;
12915 },
12916 formattedValue(event) {
12917 const {
12918 formattedValue
12919 } = event.detail;
12920 elementData.formattedValue = formattedValue;
12921 if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
12922 event.target.value = formattedValue;
12923 }
12924 storage.setValue(id, fieldName, {
12925 formattedValue
12926 });
12927 },
12928 selRange(event) {
12929 event.target.setSelectionRange(...event.detail.selRange);
12930 },
12931 charLimit: event => {
12932 const {
12933 charLimit
12934 } = event.detail;
12935 const {
12936 target
12937 } = event;
12938 if (charLimit === 0) {
12939 target.removeAttribute("maxLength");
12940 return;
12941 }
12942 target.setAttribute("maxLength", charLimit);
12943 let value = elementData.userValue;
12944 if (!value || value.length <= charLimit) {
12945 return;
12946 }
12947 value = value.slice(0, charLimit);
12948 target.value = elementData.userValue = value;
12949 storage.setValue(id, this.data.fieldName, {
12950 value
12951 });
12952 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12953 source: this,
12954 detail: {
12955 id,
12956 name: "Keystroke",
12957 value,
12958 willCommit: true,
12959 commitKey: 1,
12960 selStart: target.selectionStart,
12961 selEnd: target.selectionEnd
12962 }
12963 });
12964 }
12965 };
12966 this._dispatchEventFromSandbox(actions, jsEvent);
12967 });
12968 element.addEventListener("keydown", event => {
12969 elementData.commitKey = 1;
12970 let commitKey = -1;
12971 if (event.key === "Escape") {
12972 commitKey = 0;
12973 } else if (event.key === "Enter" && !this.data.multiLine) {
12974 commitKey = 2;
12975 } else if (event.key === "Tab") {
12976 elementData.commitKey = 3;
12977 }
12978 if (commitKey === -1) {
12979 return;
12980 }
12981 const {
12982 value
12983 } = event.target;
12984 if (elementData.lastCommittedValue === value) {
12985 return;
12986 }
12987 elementData.lastCommittedValue = value;
12988 elementData.userValue = value;
12989 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12990 source: this,
12991 detail: {
12992 id,
12993 name: "Keystroke",
12994 value,
12995 willCommit: true,
12996 commitKey,
12997 selStart: event.target.selectionStart,
12998 selEnd: event.target.selectionEnd
12999 }
13000 });
13001 });
13002 const _blurListener = blurListener;
13003 blurListener = null;
13004 element.addEventListener("blur", event => {
13005 if (!event.relatedTarget) {
13006 return;
13007 }
13008 const {
13009 value
13010 } = event.target;
13011 elementData.userValue = value;
13012 if (elementData.lastCommittedValue !== value) {
13013 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
13014 source: this,
13015 detail: {
13016 id,
13017 name: "Keystroke",
13018 value,
13019 willCommit: true,
13020 commitKey: elementData.commitKey,
13021 selStart: event.target.selectionStart,
13022 selEnd: event.target.selectionEnd
13023 }
13024 });
13025 }
13026 _blurListener(event);
13027 });
13028 if (this.data.actions?.Keystroke) {
13029 element.addEventListener("beforeinput", event => {
13030 elementData.lastCommittedValue = null;
13031 const {
13032 data,
13033 target
13034 } = event;
13035 const {
13036 value,
13037 selectionStart,
13038 selectionEnd
13039 } = target;
13040 let selStart = selectionStart,
13041 selEnd = selectionEnd;
13042 switch (event.inputType) {
13043 case "deleteWordBackward":
13044 {
13045 const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
13046 if (match) {
13047 selStart -= match[0].length;
13048 }
13049 break;
13050 }
13051 case "deleteWordForward":
13052 {
13053 const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
13054 if (match) {
13055 selEnd += match[0].length;
13056 }
13057 break;
13058 }
13059 case "deleteContentBackward":
13060 if (selectionStart === selectionEnd) {
13061 selStart -= 1;
13062 }
13063 break;
13064 case "deleteContentForward":
13065 if (selectionStart === selectionEnd) {
13066 selEnd += 1;
13067 }
13068 break;
13069 }
13070 event.preventDefault();
13071 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
13072 source: this,
13073 detail: {
13074 id,
13075 name: "Keystroke",
13076 value,
13077 change: data || "",
13078 willCommit: false,
13079 selStart,
13080 selEnd
13081 }
13082 });
13083 });
13084 }
13085 this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
13086 }
13087 if (blurListener) {
13088 element.addEventListener("blur", blurListener);
13089 }
13090 if (this.data.comb) {
13091 const fieldWidth = this.data.rect[2] - this.data.rect[0];
13092 const combWidth = fieldWidth / maxLen;
13093 element.classList.add("comb");
13094 element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
13095 }
13096 } else {
13097 element = document.createElement("div");
13098 element.textContent = this.data.fieldValue;
13099 element.style.verticalAlign = "middle";
13100 element.style.display = "table-cell";
13101 }
13102 this._setTextStyle(element);
13103 this._setBackgroundColor(element);
13104 this._setDefaultPropertiesFromJS(element);
13105 this.container.append(element);
13106 return this.container;
13107 }
13108}
13109class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
13110 constructor(parameters) {
13111 super(parameters, {
13112 isRenderable: parameters.renderForms
13113 });
13114 }
13115 render() {
13116 const storage = this.annotationStorage;
13117 const data = this.data;
13118 const id = data.id;
13119 let value = storage.getValue(id, `${this.data.fieldName}/${this.data.exportValue}`, {
13120 value: data.exportValue === data.fieldValue
13121 }).value;
13122 if (typeof value === "string") {
13123 value = value !== "Off";
13124 storage.setValue(id, this.data.fieldName, {
13125 value
13126 });
13127 }
13128 this.container.className = "buttonWidgetAnnotation checkBox";
13129 const element = document.createElement("input");
13130 GetElementsByNameSet.add(element);
13131 element.setAttribute("data-element-id", id);
13132 element.disabled = data.readOnly;
13133 this._setRequired(element, this.data.required);
13134 element.type = "checkbox";
13135 element.name = data.fieldName;
13136 if (value) {
13137 element.setAttribute("checked", true);
13138 }
13139 element.setAttribute("exportValue", data.exportValue);
13140 element.tabIndex = DEFAULT_TAB_INDEX;
13141 element.addEventListener("change", event => {
13142 const {
13143 name,
13144 checked
13145 } = event.target;
13146 for (const checkbox of this._getElementsByName(name, id)) {
13147 const curChecked = checked && checkbox.exportValue === data.exportValue;
13148 if (checkbox.domElement) {
13149 checkbox.domElement.checked = curChecked;
13150 }
13151 storage.setValue(checkbox.id, this.data.fieldName, {
13152 value: curChecked,
13153 emitMessage: false
13154 });
13155 }
13156 storage.setValue(id, this.data.fieldName, {
13157 value: checked,
13158 exportValue: checked ? data.exportValue : null
13159 });
13160 });
13161 element.addEventListener("resetform", event => {
13162 const defaultValue = data.defaultFieldValue || "Off";
13163 event.target.checked = defaultValue === data.exportValue;
13164 });
13165 if (this.enableScripting && this.hasJSActions) {
13166 const fieldName = this.data.fieldName;
13167 element.addEventListener("updatefromsandbox", jsEvent => {
13168 const actions = {
13169 value(event) {
13170 event.target.checked = event.detail.value !== "Off";
13171 storage.setValue(id, fieldName, {
13172 value: event.target.checked
13173 });
13174 }
13175 };
13176 this._dispatchEventFromSandbox(actions, jsEvent);
13177 });
13178 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);
13179 }
13180 this._setBackgroundColor(element);
13181 this._setDefaultPropertiesFromJS(element);
13182 this.container.append(element);
13183 return this.container;
13184 }
13185}
13186class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
13187 constructor(parameters) {
13188 super(parameters, {
13189 isRenderable: parameters.renderForms
13190 });
13191 }
13192 render() {
13193 this.container.className = "buttonWidgetAnnotation radioButton";
13194 const storage = this.annotationStorage;
13195 const data = this.data;
13196 const id = data.id;
13197 let value = storage.getValue(id, this.data.fieldName, {
13198 value: data.fieldValue === data.buttonValue
13199 }, this.data.buttonValue).value;
13200 if (typeof value === "string") {
13201 value = value !== data.buttonValue;
13202 storage.setValue(id, this.data.fieldName, {
13203 value
13204 }, this.data.buttonValue);
13205 }
13206 const element = document.createElement("input");
13207 GetElementsByNameSet.add(element);
13208 element.setAttribute("data-element-id", id);
13209 element.disabled = data.readOnly;
13210 this._setRequired(element, this.data.required);
13211 element.type = "radio";
13212 element.name = data.fieldName;
13213 if (value) {
13214 element.setAttribute("checked", true);
13215 }
13216 element.tabIndex = DEFAULT_TAB_INDEX;
13217 element.addEventListener("change", event => {
13218 const {
13219 name,
13220 checked
13221 } = event.target;
13222 for (const radio of this._getElementsByName(name, id)) {
13223 storage.setValue(radio.id, this.data.fieldName, {
13224 value: false,
13225 emitMessage: false
13226 });
13227 }
13228 storage.setValue(id, this.data.fieldName, {
13229 value: checked,
13230 radioValue: this.data.buttonValue
13231 });
13232 });
13233 element.addEventListener("resetform", event => {
13234 const defaultValue = data.defaultFieldValue;
13235 event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
13236 });
13237 if (this.enableScripting && this.hasJSActions) {
13238 const pdfButtonValue = data.buttonValue;
13239 element.addEventListener("updatefromsandbox", jsEvent => {
13240 const fieldName = this.data.fieldName;
13241 const actions = {
13242 value: event => {
13243 const checked = pdfButtonValue === event.detail.value;
13244 for (const radio of this._getElementsByName(event.target.name)) {
13245 const curChecked = checked && radio.id === id;
13246 if (radio.domElement) {
13247 radio.domElement.checked = curChecked;
13248 }
13249 storage.setValue(radio.id, fieldName, {
13250 value: curChecked
13251 });
13252 }
13253 }
13254 };
13255 this._dispatchEventFromSandbox(actions, jsEvent);
13256 });
13257 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);
13258 }
13259 this._setBackgroundColor(element);
13260 this._setDefaultPropertiesFromJS(element);
13261 this.container.append(element);
13262 return this.container;
13263 }
13264}
13265class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
13266 constructor(parameters) {
13267 super(parameters, {
13268 ignoreBorder: parameters.data.hasAppearance
13269 });
13270 }
13271 render() {
13272 const container = super.render();
13273 container.className = "buttonWidgetAnnotation pushButton";
13274 if (this.data.alternativeText) {
13275 container.title = this.data.alternativeText;
13276 }
13277 const linkElement = container.lastChild;
13278 if (this.enableScripting && this.hasJSActions && linkElement) {
13279 this._setDefaultPropertiesFromJS(linkElement);
13280 linkElement.addEventListener("updatefromsandbox", jsEvent => {
13281 this._dispatchEventFromSandbox({}, jsEvent);
13282 });
13283 }
13284 return container;
13285 }
13286}
13287class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
13288 constructor(parameters) {
13289 super(parameters, {
13290 isRenderable: parameters.renderForms
13291 });
13292 }
13293 render() {
13294 this.container.className = "choiceWidgetAnnotation";
13295 const storage = this.annotationStorage;
13296 const id = this.data.id;
13297 const storedData = storage.getValue(id, this.data.fieldName, {
13298 value: this.data.fieldValue
13299 });
13300 const selectElement = document.createElement("select");
13301 GetElementsByNameSet.add(selectElement);
13302 selectElement.setAttribute("data-element-id", id);
13303 selectElement.disabled = this.data.readOnly;
13304 this._setRequired(selectElement, this.data.required);
13305 selectElement.name = this.data.fieldName;
13306 selectElement.tabIndex = DEFAULT_TAB_INDEX;
13307 let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
13308 if (!this.data.combo) {
13309 selectElement.size = this.data.options.length;
13310 if (this.data.multiSelect) {
13311 selectElement.multiple = true;
13312 }
13313 }
13314 selectElement.addEventListener("resetform", event => {
13315 const defaultValue = this.data.defaultFieldValue;
13316 for (const option of selectElement.options) {
13317 option.selected = option.value === defaultValue;
13318 }
13319 });
13320 for (const option of this.data.options) {
13321 const optionElement = document.createElement("option");
13322 optionElement.textContent = option.displayValue;
13323 optionElement.value = option.exportValue;
13324 if (storedData.value.includes(option.exportValue)) {
13325 optionElement.setAttribute("selected", true);
13326 addAnEmptyEntry = false;
13327 }
13328 selectElement.append(optionElement);
13329 }
13330 let removeEmptyEntry = null;
13331 if (addAnEmptyEntry) {
13332 const noneOptionElement = document.createElement("option");
13333 noneOptionElement.value = " ";
13334 noneOptionElement.setAttribute("hidden", true);
13335 noneOptionElement.setAttribute("selected", true);
13336 selectElement.prepend(noneOptionElement);
13337 removeEmptyEntry = () => {
13338 noneOptionElement.remove();
13339 selectElement.removeEventListener("input", removeEmptyEntry);
13340 removeEmptyEntry = null;
13341 };
13342 selectElement.addEventListener("input", removeEmptyEntry);
13343 }
13344 const getValue = isExport => {
13345 const name = isExport ? "value" : "textContent";
13346 const {
13347 options,
13348 multiple
13349 } = selectElement;
13350 if (!multiple) {
13351 return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
13352 }
13353 return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
13354 };
13355 let selectedValues = getValue(false);
13356 const getItems = event => {
13357 const options = event.target.options;
13358 return Array.prototype.map.call(options, option => {
13359 return {
13360 displayValue: option.textContent,
13361 exportValue: option.value
13362 };
13363 });
13364 };
13365 if (this.enableScripting && this.hasJSActions) {
13366 selectElement.addEventListener("updatefromsandbox", jsEvent => {
13367 const fieldName = this.data.fieldName;
13368 const actions = {
13369 value(event) {
13370 removeEmptyEntry?.();
13371 const value = event.detail.value;
13372 const values = new Set(Array.isArray(value) ? value : [value]);
13373 for (const option of selectElement.options) {
13374 option.selected = values.has(option.value);
13375 }
13376 storage.setValue(id, fieldName, {
13377 value: getValue(true)
13378 });
13379 selectedValues = getValue(false);
13380 },
13381 multipleSelection(event) {
13382 selectElement.multiple = true;
13383 },
13384 remove(event) {
13385 const options = selectElement.options;
13386 const index = event.detail.remove;
13387 options[index].selected = false;
13388 selectElement.remove(index);
13389 if (options.length > 0) {
13390 const i = Array.prototype.findIndex.call(options, option => option.selected);
13391 if (i === -1) {
13392 options[0].selected = true;
13393 }
13394 }
13395 storage.setValue(id, fieldName, {
13396 value: getValue(true),
13397 items: getItems(event)
13398 });
13399 selectedValues = getValue(false);
13400 },
13401 clear(event) {
13402 while (selectElement.length !== 0) {
13403 selectElement.remove(0);
13404 }
13405 storage.setValue(id, fieldName, {
13406 value: null,
13407 items: []
13408 });
13409 selectedValues = getValue(false);
13410 },
13411 insert(event) {
13412 const {
13413 index,
13414 displayValue,
13415 exportValue
13416 } = event.detail.insert;
13417 const selectChild = selectElement.children[index];
13418 const optionElement = document.createElement("option");
13419 optionElement.textContent = displayValue;
13420 optionElement.value = exportValue;
13421 if (selectChild) {
13422 selectChild.before(optionElement);
13423 } else {
13424 selectElement.append(optionElement);
13425 }
13426 storage.setValue(id, fieldName, {
13427 value: getValue(true),
13428 items: getItems(event)
13429 });
13430 selectedValues = getValue(false);
13431 },
13432 items(event) {
13433 const {
13434 items
13435 } = event.detail;
13436 while (selectElement.length !== 0) {
13437 selectElement.remove(0);
13438 }
13439 for (const item of items) {
13440 const {
13441 displayValue,
13442 exportValue
13443 } = item;
13444 const optionElement = document.createElement("option");
13445 optionElement.textContent = displayValue;
13446 optionElement.value = exportValue;
13447 selectElement.append(optionElement);
13448 }
13449 if (selectElement.options.length > 0) {
13450 selectElement.options[0].selected = true;
13451 }
13452 storage.setValue(id, fieldName, {
13453 value: getValue(true),
13454 items: getItems(event)
13455 });
13456 selectedValues = getValue(false);
13457 },
13458 indices(event) {
13459 const indices = new Set(event.detail.indices);
13460 for (const option of event.target.options) {
13461 option.selected = indices.has(option.index);
13462 }
13463 storage.setValue(id, fieldName, {
13464 value: getValue(true)
13465 });
13466 selectedValues = getValue(false);
13467 },
13468 editable(event) {
13469 event.target.disabled = !event.detail.editable;
13470 }
13471 };
13472 this._dispatchEventFromSandbox(actions, jsEvent);
13473 });
13474 selectElement.addEventListener("input", event => {
13475 const exportValue = getValue(true);
13476 storage.setValue(id, {
13477 value: exportValue
13478 });
13479 event.preventDefault();
13480 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
13481 source: this,
13482 detail: {
13483 id,
13484 name: "Keystroke",
13485 value: selectedValues,
13486 changeEx: exportValue,
13487 willCommit: false,
13488 commitKey: 1,
13489 keyDown: false
13490 }
13491 });
13492 });
13493 this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
13494 } else {
13495 const fieldName = this.data.fieldName;
13496 selectElement.addEventListener("input", function (event) {
13497 storage.setValue(id, fieldName, {
13498 value: getValue(true),
13499 radioValue: getValue(true)
13500 });
13501 });
13502 }
13503 if (this.data.combo) {
13504 this._setTextStyle(selectElement);
13505 } else {}
13506 this._setBackgroundColor(selectElement);
13507 this._setDefaultPropertiesFromJS(selectElement);
13508 this.container.append(selectElement);
13509 return this.container;
13510 }
13511}
13512class PopupAnnotationElement extends AnnotationElement {
13513 static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
13514 constructor(parameters) {
13515 const {
13516 data
13517 } = parameters;
13518 const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
13519 super(parameters, {
13520 isRenderable
13521 });
13522 }
13523 render() {
13524 this.container.className = "popupAnnotation";
13525 const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
13526 if (parentElements.length === 0) {
13527 return this.container;
13528 }
13529 const popup = new PopupElement({
13530 container: this.container,
13531 trigger: Array.from(parentElements),
13532 color: this.data.color,
13533 titleObj: this.data.titleObj,
13534 modificationDate: this.data.modificationDate,
13535 contentsObj: this.data.contentsObj,
13536 richText: this.data.richText
13537 });
13538 const page = this.page;
13539 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]]);
13540 const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
13541 const popupTop = rect[1];
13542 const {
13543 pageWidth,
13544 pageHeight,
13545 pageX,
13546 pageY
13547 } = this.viewport.rawDims;
13548 this.container.style.left = `${100 * (popupLeft - pageX) / pageWidth}%`;
13549 this.container.style.top = `${100 * (popupTop - pageY) / pageHeight}%`;
13550 this.container.append(popup.render());
13551 return this.container;
13552 }
13553}
13554class PopupElement {
13555 constructor(parameters) {
13556 this.container = parameters.container;
13557 this.trigger = parameters.trigger;
13558 this.color = parameters.color;
13559 this.titleObj = parameters.titleObj;
13560 this.modificationDate = parameters.modificationDate;
13561 this.contentsObj = parameters.contentsObj;
13562 this.richText = parameters.richText;
13563 this.hideWrapper = parameters.hideWrapper || false;
13564 this.pinned = false;
13565 }
13566 render() {
13567 const BACKGROUND_ENLIGHT = 0.7;
13568 const wrapper = document.createElement("div");
13569 wrapper.className = "popupWrapper";
13570 this.hideElement = this.hideWrapper ? wrapper : this.container;
13571 this.hideElement.hidden = true;
13572 const popup = document.createElement("div");
13573 popup.className = "popup";
13574 const color = this.color;
13575 if (color) {
13576 const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
13577 const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
13578 const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
13579 popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
13580 }
13581 const title = document.createElement("h1");
13582 title.dir = this.titleObj.dir;
13583 title.textContent = this.titleObj.str;
13584 popup.append(title);
13585 const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
13586 if (dateObject) {
13587 const modificationDate = document.createElement("span");
13588 modificationDate.className = "popupDate";
13589 modificationDate.textContent = "{{date}}, {{time}}";
13590 modificationDate.dataset.l10nId = "annotation_date_string";
13591 modificationDate.dataset.l10nArgs = JSON.stringify({
13592 date: dateObject.toLocaleDateString(),
13593 time: dateObject.toLocaleTimeString()
13594 });
13595 popup.append(modificationDate);
13596 }
13597 if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
13598 _xfa_layer.XfaLayer.render({
13599 xfaHtml: this.richText.html,
13600 intent: "richText",
13601 div: popup
13602 });
13603 popup.lastChild.className = "richText popupContent";
13604 } else {
13605 const contents = this._formatContents(this.contentsObj);
13606 popup.append(contents);
13607 }
13608 if (!Array.isArray(this.trigger)) {
13609 this.trigger = [this.trigger];
13610 }
13611 for (const element of this.trigger) {
13612 element?.addEventListener("click", this._toggle.bind(this));
13613 element?.addEventListener("mouseover", this._show.bind(this, false));
13614 element?.addEventListener("mouseout", this._hide.bind(this, false));
13615 }
13616 popup.addEventListener("click", this._hide.bind(this, true));
13617 wrapper.append(popup);
13618 return wrapper;
13619 }
13620 _formatContents({
13621 str,
13622 dir
13623 }) {
13624 const p = document.createElement("p");
13625 p.className = "popupContent";
13626 p.dir = dir;
13627 const lines = str.split(/(?:\r\n?|\n)/);
13628 for (let i = 0, ii = lines.length; i < ii; ++i) {
13629 const line = lines[i];
13630 p.append(document.createTextNode(line));
13631 if (i < ii - 1) {
13632 p.append(document.createElement("br"));
13633 }
13634 }
13635 return p;
13636 }
13637 _toggle() {
13638 if (this.pinned) {
13639 this._hide(true);
13640 } else {
13641 this._show(true);
13642 }
13643 }
13644 _show(pin = false) {
13645 if (pin) {
13646 this.pinned = true;
13647 }
13648 if (this.hideElement.hidden) {
13649 this.hideElement.hidden = false;
13650 this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
13651 }
13652 }
13653 _hide(unpin = true) {
13654 if (unpin) {
13655 this.pinned = false;
13656 }
13657 if (!this.hideElement.hidden && !this.pinned) {
13658 this.hideElement.hidden = true;
13659 this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
13660 }
13661 }
13662}
13663class FreeTextAnnotationElement extends AnnotationElement {
13664 constructor(parameters) {
13665 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13666 super(parameters, {
13667 isRenderable,
13668 ignoreBorder: true
13669 });
13670 this.textContent = parameters.data.textContent;
13671 }
13672 render() {
13673 this.container.className = "freeTextAnnotation";
13674 if (this.textContent) {
13675 const content = document.createElement("div");
13676 content.className = "annotationTextContent";
13677 content.setAttribute("role", "comment");
13678 for (const line of this.textContent) {
13679 const lineSpan = document.createElement("span");
13680 lineSpan.textContent = line;
13681 content.append(lineSpan);
13682 }
13683 this.container.append(content);
13684 }
13685 if (!this.data.hasPopup) {
13686 this._createPopup(null, this.data);
13687 }
13688 return this.container;
13689 }
13690}
13691class LineAnnotationElement extends AnnotationElement {
13692 constructor(parameters) {
13693 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13694 super(parameters, {
13695 isRenderable,
13696 ignoreBorder: true
13697 });
13698 }
13699 render() {
13700 this.container.className = "lineAnnotation";
13701 const data = this.data;
13702 const {
13703 width,
13704 height
13705 } = getRectDims(data.rect);
13706 const svg = this.svgFactory.create(width, height, true);
13707 const line = this.svgFactory.createElement("svg:line");
13708 line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
13709 line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
13710 line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
13711 line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
13712 line.setAttribute("stroke-width", data.borderStyle.width || 1);
13713 line.setAttribute("stroke", "transparent");
13714 line.setAttribute("fill", "transparent");
13715 svg.append(line);
13716 this.container.append(svg);
13717 this._createPopup(line, data);
13718 return this.container;
13719 }
13720}
13721class SquareAnnotationElement extends AnnotationElement {
13722 constructor(parameters) {
13723 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13724 super(parameters, {
13725 isRenderable,
13726 ignoreBorder: true
13727 });
13728 }
13729 render() {
13730 this.container.className = "squareAnnotation";
13731 const data = this.data;
13732 const {
13733 width,
13734 height
13735 } = getRectDims(data.rect);
13736 const svg = this.svgFactory.create(width, height, true);
13737 const borderWidth = data.borderStyle.width;
13738 const square = this.svgFactory.createElement("svg:rect");
13739 square.setAttribute("x", borderWidth / 2);
13740 square.setAttribute("y", borderWidth / 2);
13741 square.setAttribute("width", width - borderWidth);
13742 square.setAttribute("height", height - borderWidth);
13743 square.setAttribute("stroke-width", borderWidth || 1);
13744 square.setAttribute("stroke", "transparent");
13745 square.setAttribute("fill", "transparent");
13746 svg.append(square);
13747 this.container.append(svg);
13748 this._createPopup(square, data);
13749 return this.container;
13750 }
13751}
13752class CircleAnnotationElement extends AnnotationElement {
13753 constructor(parameters) {
13754 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13755 super(parameters, {
13756 isRenderable,
13757 ignoreBorder: true
13758 });
13759 }
13760 render() {
13761 this.container.className = "circleAnnotation";
13762 const data = this.data;
13763 const {
13764 width,
13765 height
13766 } = getRectDims(data.rect);
13767 const svg = this.svgFactory.create(width, height, true);
13768 const borderWidth = data.borderStyle.width;
13769 const circle = this.svgFactory.createElement("svg:ellipse");
13770 circle.setAttribute("cx", width / 2);
13771 circle.setAttribute("cy", height / 2);
13772 circle.setAttribute("rx", width / 2 - borderWidth / 2);
13773 circle.setAttribute("ry", height / 2 - borderWidth / 2);
13774 circle.setAttribute("stroke-width", borderWidth || 1);
13775 circle.setAttribute("stroke", "transparent");
13776 circle.setAttribute("fill", "transparent");
13777 svg.append(circle);
13778 this.container.append(svg);
13779 this._createPopup(circle, data);
13780 return this.container;
13781 }
13782}
13783class PolylineAnnotationElement extends AnnotationElement {
13784 constructor(parameters) {
13785 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13786 super(parameters, {
13787 isRenderable,
13788 ignoreBorder: true
13789 });
13790 this.containerClassName = "polylineAnnotation";
13791 this.svgElementName = "svg:polyline";
13792 }
13793 render() {
13794 this.container.className = this.containerClassName;
13795 const data = this.data;
13796 const {
13797 width,
13798 height
13799 } = getRectDims(data.rect);
13800 const svg = this.svgFactory.create(width, height, true);
13801 let points = [];
13802 for (const coordinate of data.vertices) {
13803 const x = coordinate.x - data.rect[0];
13804 const y = data.rect[3] - coordinate.y;
13805 points.push(x + "," + y);
13806 }
13807 points = points.join(" ");
13808 const polyline = this.svgFactory.createElement(this.svgElementName);
13809 polyline.setAttribute("points", points);
13810 polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
13811 polyline.setAttribute("stroke", "transparent");
13812 polyline.setAttribute("fill", "transparent");
13813 svg.append(polyline);
13814 this.container.append(svg);
13815 this._createPopup(polyline, data);
13816 return this.container;
13817 }
13818}
13819class PolygonAnnotationElement extends PolylineAnnotationElement {
13820 constructor(parameters) {
13821 super(parameters);
13822 this.containerClassName = "polygonAnnotation";
13823 this.svgElementName = "svg:polygon";
13824 }
13825}
13826class CaretAnnotationElement extends AnnotationElement {
13827 constructor(parameters) {
13828 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13829 super(parameters, {
13830 isRenderable,
13831 ignoreBorder: true
13832 });
13833 }
13834 render() {
13835 this.container.className = "caretAnnotation";
13836 if (!this.data.hasPopup) {
13837 this._createPopup(null, this.data);
13838 }
13839 return this.container;
13840 }
13841}
13842class InkAnnotationElement extends AnnotationElement {
13843 constructor(parameters) {
13844 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13845 super(parameters, {
13846 isRenderable,
13847 ignoreBorder: true
13848 });
13849 this.containerClassName = "inkAnnotation";
13850 this.svgElementName = "svg:polyline";
13851 }
13852 render() {
13853 this.container.className = this.containerClassName;
13854 const data = this.data;
13855 const {
13856 width,
13857 height
13858 } = getRectDims(data.rect);
13859 const svg = this.svgFactory.create(width, height, true);
13860 for (const inkList of data.inkLists) {
13861 let points = [];
13862 for (const coordinate of inkList) {
13863 const x = coordinate.x - data.rect[0];
13864 const y = data.rect[3] - coordinate.y;
13865 points.push(`${x},${y}`);
13866 }
13867 points = points.join(" ");
13868 const polyline = this.svgFactory.createElement(this.svgElementName);
13869 polyline.setAttribute("points", points);
13870 polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
13871 polyline.setAttribute("stroke", "transparent");
13872 polyline.setAttribute("fill", "transparent");
13873 this._createPopup(polyline, data);
13874 svg.append(polyline);
13875 }
13876 this.container.append(svg);
13877 return this.container;
13878 }
13879}
13880class HighlightAnnotationElement extends AnnotationElement {
13881 constructor(parameters) {
13882 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13883 super(parameters, {
13884 isRenderable,
13885 ignoreBorder: true,
13886 createQuadrilaterals: true
13887 });
13888 }
13889 render() {
13890 if (!this.data.hasPopup) {
13891 this._createPopup(null, this.data);
13892 }
13893 if (this.quadrilaterals) {
13894 return this._renderQuadrilaterals("highlightAnnotation");
13895 }
13896 this.container.className = "highlightAnnotation";
13897 return this.container;
13898 }
13899}
13900class UnderlineAnnotationElement extends AnnotationElement {
13901 constructor(parameters) {
13902 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13903 super(parameters, {
13904 isRenderable,
13905 ignoreBorder: true,
13906 createQuadrilaterals: true
13907 });
13908 }
13909 render() {
13910 if (!this.data.hasPopup) {
13911 this._createPopup(null, this.data);
13912 }
13913 if (this.quadrilaterals) {
13914 return this._renderQuadrilaterals("underlineAnnotation");
13915 }
13916 this.container.className = "underlineAnnotation";
13917 return this.container;
13918 }
13919}
13920class SquigglyAnnotationElement extends AnnotationElement {
13921 constructor(parameters) {
13922 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13923 super(parameters, {
13924 isRenderable,
13925 ignoreBorder: true,
13926 createQuadrilaterals: true
13927 });
13928 }
13929 render() {
13930 if (!this.data.hasPopup) {
13931 this._createPopup(null, this.data);
13932 }
13933 if (this.quadrilaterals) {
13934 return this._renderQuadrilaterals("squigglyAnnotation");
13935 }
13936 this.container.className = "squigglyAnnotation";
13937 return this.container;
13938 }
13939}
13940class StrikeOutAnnotationElement extends AnnotationElement {
13941 constructor(parameters) {
13942 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13943 super(parameters, {
13944 isRenderable,
13945 ignoreBorder: true,
13946 createQuadrilaterals: true
13947 });
13948 }
13949 render() {
13950 if (!this.data.hasPopup) {
13951 this._createPopup(null, this.data);
13952 }
13953 if (this.quadrilaterals) {
13954 return this._renderQuadrilaterals("strikeoutAnnotation");
13955 }
13956 this.container.className = "strikeoutAnnotation";
13957 return this.container;
13958 }
13959}
13960class StampAnnotationElement extends AnnotationElement {
13961 constructor(parameters) {
13962 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13963 super(parameters, {
13964 isRenderable,
13965 ignoreBorder: true
13966 });
13967 }
13968 render() {
13969 this.container.className = "stampAnnotation";
13970 if (!this.data.hasPopup) {
13971 this._createPopup(null, this.data);
13972 }
13973 return this.container;
13974 }
13975}
13976class FileAttachmentAnnotationElement extends AnnotationElement {
13977 constructor(parameters) {
13978 super(parameters, {
13979 isRenderable: true
13980 });
13981 const {
13982 filename,
13983 content
13984 } = this.data.file;
13985 this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
13986 this.content = content;
13987 this.linkService.eventBus?.dispatch("fileattachmentannotation", {
13988 source: this,
13989 filename,
13990 content
13991 });
13992 }
13993 render() {
13994 this.container.className = "fileAttachmentAnnotation";
13995 let trigger;
13996 if (this.data.hasAppearance) {
13997 trigger = document.createElement("div");
13998 } else {
13999 trigger = document.createElement("img");
14000 trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(this.data.name) ? "paperclip" : "pushpin"}.svg`;
14001 }
14002 trigger.className = "popupTriggerArea";
14003 trigger.addEventListener("dblclick", this._download.bind(this));
14004 if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
14005 this._createPopup(trigger, this.data);
14006 }
14007 this.container.append(trigger);
14008 return this.container;
14009 }
14010 _download() {
14011 this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
14012 }
14013}
14014class AnnotationLayer {
14015 static #appendElement(element, id, div, accessibilityManager) {
14016 const contentElement = element.firstChild || element;
14017 contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
14018 div.append(element);
14019 accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
14020 }
14021 static render(params) {
14022 const {
14023 annotations,
14024 div,
14025 viewport,
14026 accessibilityManager
14027 } = params;
14028 (0, _display_utils.setLayerDimensions)(div, viewport);
14029 const elementParams = {
14030 data: null,
14031 layer: div,
14032 page: params.page,
14033 viewport,
14034 linkService: params.linkService,
14035 downloadManager: params.downloadManager,
14036 imageResourcesPath: params.imageResourcesPath || "",
14037 renderForms: params.renderForms !== false,
14038 svgFactory: new _display_utils.DOMSVGFactory(),
14039 annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(),
14040 enableScripting: params.enableScripting === true,
14041 hasJSActions: params.hasJSActions,
14042 fieldObjects: params.fieldObjects
14043 };
14044 let zIndex = 0;
14045 if (window.registerAcroformAnnotations) {
14046 window.registerAcroformAnnotations(annotations);
14047 }
14048 for (const data of annotations) {
14049 if (data.annotationType !== _util.AnnotationType.POPUP) {
14050 const {
14051 width,
14052 height
14053 } = getRectDims(data.rect);
14054 if (width <= 0 || height <= 0) {
14055 continue;
14056 }
14057 }
14058 elementParams.data = data;
14059 const element = AnnotationElementFactory.create(elementParams);
14060 if (!element.isRenderable) {
14061 continue;
14062 }
14063 const rendered = element.render();
14064 if (data.hidden) {
14065 rendered.style.visibility = "hidden";
14066 }
14067 if (Array.isArray(rendered)) {
14068 for (const renderedElement of rendered) {
14069 renderedElement.style.zIndex = zIndex++;
14070 AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
14071 }
14072 } else {
14073 rendered.style.zIndex = zIndex++;
14074 if (element instanceof PopupAnnotationElement) {
14075 div.prepend(rendered);
14076 } else {
14077 AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
14078 }
14079 }
14080 }
14081 this.#setAnnotationCanvasMap(div, params.annotationCanvasMap);
14082 }
14083 static update(params) {
14084 const {
14085 annotationCanvasMap,
14086 div,
14087 viewport
14088 } = params;
14089 (0, _display_utils.setLayerDimensions)(div, {
14090 rotation: viewport.rotation
14091 });
14092 this.#setAnnotationCanvasMap(div, annotationCanvasMap);
14093 div.hidden = false;
14094 }
14095 static #setAnnotationCanvasMap(div, annotationCanvasMap) {
14096 if (!annotationCanvasMap) {
14097 return;
14098 }
14099 for (const [id, canvas] of annotationCanvasMap) {
14100 const element = div.querySelector(`[data-annotation-id="${id}"]`);
14101 if (!element) {
14102 continue;
14103 }
14104 const {
14105 firstChild
14106 } = element;
14107 if (!firstChild) {
14108 element.append(canvas);
14109 } else if (firstChild.nodeName === "CANVAS") {
14110 firstChild.replaceWith(canvas);
14111 } else {
14112 firstChild.before(canvas);
14113 }
14114 }
14115 annotationCanvasMap.clear();
14116 }
14117}
14118exports.AnnotationLayer = AnnotationLayer;
14119
14120/***/ }),
14121/* 33 */
14122/***/ ((__unused_webpack_module, exports) => {
14123
14124
14125
14126Object.defineProperty(exports, "__esModule", ({
14127 value: true
14128}));
14129exports.ColorConverters = void 0;
14130function makeColorComp(n) {
14131 return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
14132}
14133class ColorConverters {
14134 static CMYK_G([c, y, m, k]) {
14135 return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
14136 }
14137 static G_CMYK([g]) {
14138 return ["CMYK", 0, 0, 0, 1 - g];
14139 }
14140 static G_RGB([g]) {
14141 return ["RGB", g, g, g];
14142 }
14143 static G_HTML([g]) {
14144 const G = makeColorComp(g);
14145 return `#${G}${G}${G}`;
14146 }
14147 static RGB_G([r, g, b]) {
14148 return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
14149 }
14150 static RGB_HTML([r, g, b]) {
14151 const R = makeColorComp(r);
14152 const G = makeColorComp(g);
14153 const B = makeColorComp(b);
14154 return `#${R}${G}${B}`;
14155 }
14156 static T_HTML() {
14157 return "#00000000";
14158 }
14159 static CMYK_RGB([c, y, m, k]) {
14160 return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
14161 }
14162 static CMYK_HTML(components) {
14163 const rgb = this.CMYK_RGB(components).slice(1);
14164 return this.RGB_HTML(rgb);
14165 }
14166 static RGB_CMYK([r, g, b]) {
14167 const c = 1 - r;
14168 const m = 1 - g;
14169 const y = 1 - b;
14170 const k = Math.min(c, m, y);
14171 return ["CMYK", c, m, y, k];
14172 }
14173}
14174exports.ColorConverters = ColorConverters;
14175
14176/***/ }),
14177/* 34 */
14178/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14179
14180
14181
14182Object.defineProperty(exports, "__esModule", ({
14183 value: true
14184}));
14185exports.XfaLayer = void 0;
14186var _xfa_text = __w_pdfjs_require__(19);
14187class XfaLayer {
14188 static setupStorage(html, id, element, storage, intent) {
14189 let fieldname = id;
14190 let ancestor = html;
14191 while (ancestor) {
14192 if (ancestor.getAttribute("xfaname")) {
14193 fieldname = ancestor.getAttribute("xfaname");
14194 break;
14195 }
14196 ancestor = ancestor.parentElement;
14197 }
14198 const storedData = storage.getValue(id, fieldname, {
14199 value: null
14200 });
14201 switch (element.name) {
14202 case "textarea":
14203 if (storedData.value !== null) {
14204 html.textContent = storedData.value;
14205 }
14206 if (intent === "print") {
14207 break;
14208 }
14209 html.addEventListener("input", event => {
14210 storage.setValue(id, fieldname, {
14211 value: event.target.value
14212 });
14213 });
14214 break;
14215 case "input":
14216 if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
14217 if (storedData.value === element.attributes.xfaOn) {
14218 html.setAttribute("checked", true);
14219 } else if (storedData.value === element.attributes.xfaOff) {
14220 html.removeAttribute("checked");
14221 }
14222 if (intent === "print") {
14223 break;
14224 }
14225 html.addEventListener("change", event => {
14226 storage.setValue(id, fieldname, {
14227 value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
14228 });
14229 });
14230 } else {
14231 if (storedData.value !== null) {
14232 html.setAttribute("value", storedData.value);
14233 }
14234 if (intent === "print") {
14235 break;
14236 }
14237 html.addEventListener("input", event => {
14238 storage.setValue(id, fieldname, {
14239 value: event.target.value
14240 });
14241 });
14242 }
14243 break;
14244 case "select":
14245 if (storedData.value !== null) {
14246 for (const option of element.children) {
14247 if (option.attributes.value === storedData.value) {
14248 option.attributes.selected = true;
14249 }
14250 }
14251 }
14252 html.addEventListener("input", event => {
14253 const options = event.target.options;
14254 const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
14255 storage.setValue(id, fieldname, {
14256 value
14257 });
14258 });
14259 break;
14260 }
14261 }
14262 static setAttributes({
14263 html,
14264 element,
14265 storage = null,
14266 intent,
14267 linkService
14268 }) {
14269 const {
14270 attributes
14271 } = element;
14272 const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
14273 if (attributes.type === "radio") {
14274 attributes.name = `${attributes.name}-${intent}`;
14275 }
14276 for (const [key, value] of Object.entries(attributes)) {
14277 if (value === null || value === undefined) {
14278 continue;
14279 }
14280 switch (key) {
14281 case "class":
14282 if (value.length) {
14283 html.setAttribute(key, value.join(" "));
14284 }
14285 break;
14286 case "dataId":
14287 break;
14288 case "id":
14289 html.setAttribute("data-element-id", value);
14290 break;
14291 case "style":
14292 Object.assign(html.style, value);
14293 break;
14294 case "textContent":
14295 html.textContent = value;
14296 break;
14297 default:
14298 if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
14299 html.setAttribute(key, value);
14300 }
14301 }
14302 }
14303 if (isHTMLAnchorElement) {
14304 linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
14305 }
14306 if (storage && attributes.dataId) {
14307 this.setupStorage(html, attributes.dataId, element, storage);
14308 }
14309 }
14310 static render(parameters) {
14311 const storage = parameters.annotationStorage;
14312 const linkService = parameters.linkService;
14313 const root = parameters.xfaHtml;
14314 const intent = parameters.intent || "display";
14315 const rootHtml = document.createElement(root.name);
14316 if (root.attributes) {
14317 this.setAttributes({
14318 html: rootHtml,
14319 element: root,
14320 intent,
14321 linkService
14322 });
14323 }
14324 const stack = [[root, -1, rootHtml]];
14325 const rootDiv = parameters.div;
14326 rootDiv.append(rootHtml);
14327 if (parameters.viewport) {
14328 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
14329 rootDiv.style.transform = transform;
14330 }
14331 if (intent !== "richText") {
14332 rootDiv.setAttribute("class", "xfaLayer xfaFont");
14333 }
14334 const textDivs = [];
14335 while (stack.length > 0) {
14336 const [parent, i, html] = stack.at(-1);
14337 if (i + 1 === parent.children.length) {
14338 stack.pop();
14339 continue;
14340 }
14341 const child = parent.children[++stack.at(-1)[1]];
14342 if (child === null) {
14343 continue;
14344 }
14345 const {
14346 name
14347 } = child;
14348 if (name === "#text") {
14349 const node = document.createTextNode(child.value);
14350 textDivs.push(node);
14351 html.append(node);
14352 continue;
14353 }
14354 let childHtml;
14355 if (child?.attributes?.xmlns) {
14356 childHtml = document.createElementNS(child.attributes.xmlns, name);
14357 } else {
14358 childHtml = document.createElement(name);
14359 }
14360 html.append(childHtml);
14361 if (child.attributes) {
14362 this.setAttributes({
14363 html: childHtml,
14364 element: child,
14365 storage,
14366 intent,
14367 linkService
14368 });
14369 }
14370 if (child.children && child.children.length > 0) {
14371 stack.push([child, -1, childHtml]);
14372 } else if (child.value) {
14373 const node = document.createTextNode(child.value);
14374 if (_xfa_text.XfaText.shouldBuildText(name)) {
14375 textDivs.push(node);
14376 }
14377 childHtml.append(node);
14378 }
14379 }
14380 for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
14381 el.setAttribute("readOnly", true);
14382 }
14383 return {
14384 textDivs
14385 };
14386 }
14387 static update(parameters) {
14388 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
14389 parameters.div.style.transform = transform;
14390 parameters.div.hidden = false;
14391 }
14392}
14393exports.XfaLayer = XfaLayer;
14394
14395/***/ }),
14396/* 35 */
14397/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14398
14399
14400
14401Object.defineProperty(exports, "__esModule", ({
14402 value: true
14403}));
14404exports.SVGGraphics = void 0;
14405var _display_utils = __w_pdfjs_require__(6);
14406var _util = __w_pdfjs_require__(1);
14407var _is_node = __w_pdfjs_require__(10);
14408let SVGGraphics = class {
14409 constructor() {
14410 (0, _util.unreachable)("Not implemented: SVGGraphics");
14411 }
14412};
14413exports.SVGGraphics = SVGGraphics;
14414{
14415 const SVG_DEFAULTS = {
14416 fontStyle: "normal",
14417 fontWeight: "normal",
14418 fillColor: "#000000"
14419 };
14420 const XML_NS = "http://www.w3.org/XML/1998/namespace";
14421 const XLINK_NS = "http://www.w3.org/1999/xlink";
14422 const LINE_CAP_STYLES = ["butt", "round", "square"];
14423 const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
14424 const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
14425 if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
14426 return URL.createObjectURL(new Blob([data], {
14427 type: contentType
14428 }));
14429 }
14430 const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
14431 let buffer = `data:${contentType};base64,`;
14432 for (let i = 0, ii = data.length; i < ii; i += 3) {
14433 const b1 = data[i] & 0xff;
14434 const b2 = data[i + 1] & 0xff;
14435 const b3 = data[i + 2] & 0xff;
14436 const d1 = b1 >> 2,
14437 d2 = (b1 & 3) << 4 | b2 >> 4;
14438 const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
14439 const d4 = i + 2 < ii ? b3 & 0x3f : 64;
14440 buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
14441 }
14442 return buffer;
14443 };
14444 const convertImgDataToPng = function () {
14445 const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
14446 const CHUNK_WRAPPER_SIZE = 12;
14447 const crcTable = new Int32Array(256);
14448 for (let i = 0; i < 256; i++) {
14449 let c = i;
14450 for (let h = 0; h < 8; h++) {
14451 if (c & 1) {
14452 c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
14453 } else {
14454 c = c >> 1 & 0x7fffffff;
14455 }
14456 }
14457 crcTable[i] = c;
14458 }
14459 function crc32(data, start, end) {
14460 let crc = -1;
14461 for (let i = start; i < end; i++) {
14462 const a = (crc ^ data[i]) & 0xff;
14463 const b = crcTable[a];
14464 crc = crc >>> 8 ^ b;
14465 }
14466 return crc ^ -1;
14467 }
14468 function writePngChunk(type, body, data, offset) {
14469 let p = offset;
14470 const len = body.length;
14471 data[p] = len >> 24 & 0xff;
14472 data[p + 1] = len >> 16 & 0xff;
14473 data[p + 2] = len >> 8 & 0xff;
14474 data[p + 3] = len & 0xff;
14475 p += 4;
14476 data[p] = type.charCodeAt(0) & 0xff;
14477 data[p + 1] = type.charCodeAt(1) & 0xff;
14478 data[p + 2] = type.charCodeAt(2) & 0xff;
14479 data[p + 3] = type.charCodeAt(3) & 0xff;
14480 p += 4;
14481 data.set(body, p);
14482 p += body.length;
14483 const crc = crc32(data, offset + 4, p);
14484 data[p] = crc >> 24 & 0xff;
14485 data[p + 1] = crc >> 16 & 0xff;
14486 data[p + 2] = crc >> 8 & 0xff;
14487 data[p + 3] = crc & 0xff;
14488 }
14489 function adler32(data, start, end) {
14490 let a = 1;
14491 let b = 0;
14492 for (let i = start; i < end; ++i) {
14493 a = (a + (data[i] & 0xff)) % 65521;
14494 b = (b + a) % 65521;
14495 }
14496 return b << 16 | a;
14497 }
14498 function deflateSync(literals) {
14499 return deflateSyncUncompressed(literals);
14500 }
14501 function deflateSyncUncompressed(literals) {
14502 let len = literals.length;
14503 const maxBlockLength = 0xffff;
14504 const deflateBlocks = Math.ceil(len / maxBlockLength);
14505 const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
14506 let pi = 0;
14507 idat[pi++] = 0x78;
14508 idat[pi++] = 0x9c;
14509 let pos = 0;
14510 while (len > maxBlockLength) {
14511 idat[pi++] = 0x00;
14512 idat[pi++] = 0xff;
14513 idat[pi++] = 0xff;
14514 idat[pi++] = 0x00;
14515 idat[pi++] = 0x00;
14516 idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
14517 pi += maxBlockLength;
14518 pos += maxBlockLength;
14519 len -= maxBlockLength;
14520 }
14521 idat[pi++] = 0x01;
14522 idat[pi++] = len & 0xff;
14523 idat[pi++] = len >> 8 & 0xff;
14524 idat[pi++] = ~len & 0xffff & 0xff;
14525 idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
14526 idat.set(literals.subarray(pos), pi);
14527 pi += literals.length - pos;
14528 const adler = adler32(literals, 0, literals.length);
14529 idat[pi++] = adler >> 24 & 0xff;
14530 idat[pi++] = adler >> 16 & 0xff;
14531 idat[pi++] = adler >> 8 & 0xff;
14532 idat[pi++] = adler & 0xff;
14533 return idat;
14534 }
14535 function encode(imgData, kind, forceDataSchema, isMask) {
14536 const width = imgData.width;
14537 const height = imgData.height;
14538 let bitDepth, colorType, lineSize;
14539 const bytes = imgData.data;
14540 switch (kind) {
14541 case _util.ImageKind.GRAYSCALE_1BPP:
14542 colorType = 0;
14543 bitDepth = 1;
14544 lineSize = width + 7 >> 3;
14545 break;
14546 case _util.ImageKind.RGB_24BPP:
14547 colorType = 2;
14548 bitDepth = 8;
14549 lineSize = width * 3;
14550 break;
14551 case _util.ImageKind.RGBA_32BPP:
14552 colorType = 6;
14553 bitDepth = 8;
14554 lineSize = width * 4;
14555 break;
14556 default:
14557 throw new Error("invalid format");
14558 }
14559 const literals = new Uint8Array((1 + lineSize) * height);
14560 let offsetLiterals = 0,
14561 offsetBytes = 0;
14562 for (let y = 0; y < height; ++y) {
14563 literals[offsetLiterals++] = 0;
14564 literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
14565 offsetBytes += lineSize;
14566 offsetLiterals += lineSize;
14567 }
14568 if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
14569 offsetLiterals = 0;
14570 for (let y = 0; y < height; y++) {
14571 offsetLiterals++;
14572 for (let i = 0; i < lineSize; i++) {
14573 literals[offsetLiterals++] ^= 0xff;
14574 }
14575 }
14576 }
14577 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]);
14578 const idat = deflateSync(literals);
14579 const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
14580 const data = new Uint8Array(pngLength);
14581 let offset = 0;
14582 data.set(PNG_HEADER, offset);
14583 offset += PNG_HEADER.length;
14584 writePngChunk("IHDR", ihdr, data, offset);
14585 offset += CHUNK_WRAPPER_SIZE + ihdr.length;
14586 writePngChunk("IDATA", idat, data, offset);
14587 offset += CHUNK_WRAPPER_SIZE + idat.length;
14588 writePngChunk("IEND", new Uint8Array(0), data, offset);
14589 return createObjectURL(data, "image/png", forceDataSchema);
14590 }
14591 return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
14592 const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
14593 return encode(imgData, kind, forceDataSchema, isMask);
14594 };
14595 }();
14596 class SVGExtraState {
14597 constructor() {
14598 this.fontSizeScale = 1;
14599 this.fontWeight = SVG_DEFAULTS.fontWeight;
14600 this.fontSize = 0;
14601 this.textMatrix = _util.IDENTITY_MATRIX;
14602 this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
14603 this.leading = 0;
14604 this.textRenderingMode = _util.TextRenderingMode.FILL;
14605 this.textMatrixScale = 1;
14606 this.x = 0;
14607 this.y = 0;
14608 this.lineX = 0;
14609 this.lineY = 0;
14610 this.charSpacing = 0;
14611 this.wordSpacing = 0;
14612 this.textHScale = 1;
14613 this.textRise = 0;
14614 this.fillColor = SVG_DEFAULTS.fillColor;
14615 this.strokeColor = "#000000";
14616 this.fillAlpha = 1;
14617 this.strokeAlpha = 1;
14618 this.lineWidth = 1;
14619 this.lineJoin = "";
14620 this.lineCap = "";
14621 this.miterLimit = 0;
14622 this.dashArray = [];
14623 this.dashPhase = 0;
14624 this.dependencies = [];
14625 this.activeClipUrl = null;
14626 this.clipGroup = null;
14627 this.maskId = "";
14628 }
14629 clone() {
14630 return Object.create(this);
14631 }
14632 setCurrentPoint(x, y) {
14633 this.x = x;
14634 this.y = y;
14635 }
14636 }
14637 function opListToTree(opList) {
14638 let opTree = [];
14639 const tmp = [];
14640 for (const opListElement of opList) {
14641 if (opListElement.fn === "save") {
14642 opTree.push({
14643 fnId: 92,
14644 fn: "group",
14645 items: []
14646 });
14647 tmp.push(opTree);
14648 opTree = opTree.at(-1).items;
14649 continue;
14650 }
14651 if (opListElement.fn === "restore") {
14652 opTree = tmp.pop();
14653 } else {
14654 opTree.push(opListElement);
14655 }
14656 }
14657 return opTree;
14658 }
14659 function pf(value) {
14660 if (Number.isInteger(value)) {
14661 return value.toString();
14662 }
14663 const s = value.toFixed(10);
14664 let i = s.length - 1;
14665 if (s[i] !== "0") {
14666 return s;
14667 }
14668 do {
14669 i--;
14670 } while (s[i] === "0");
14671 return s.substring(0, s[i] === "." ? i : i + 1);
14672 }
14673 function pm(m) {
14674 if (m[4] === 0 && m[5] === 0) {
14675 if (m[1] === 0 && m[2] === 0) {
14676 if (m[0] === 1 && m[3] === 1) {
14677 return "";
14678 }
14679 return `scale(${pf(m[0])} ${pf(m[3])})`;
14680 }
14681 if (m[0] === m[3] && m[1] === -m[2]) {
14682 const a = Math.acos(m[0]) * 180 / Math.PI;
14683 return `rotate(${pf(a)})`;
14684 }
14685 } else {
14686 if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
14687 return `translate(${pf(m[4])} ${pf(m[5])})`;
14688 }
14689 }
14690 return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
14691 }
14692 let clipCount = 0;
14693 let maskCount = 0;
14694 let shadingCount = 0;
14695 exports.SVGGraphics = SVGGraphics = class {
14696 constructor(commonObjs, objs, forceDataSchema = false) {
14697 (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
14698 this.svgFactory = new _display_utils.DOMSVGFactory();
14699 this.current = new SVGExtraState();
14700 this.transformMatrix = _util.IDENTITY_MATRIX;
14701 this.transformStack = [];
14702 this.extraStack = [];
14703 this.commonObjs = commonObjs;
14704 this.objs = objs;
14705 this.pendingClip = null;
14706 this.pendingEOFill = false;
14707 this.embedFonts = false;
14708 this.embeddedFonts = Object.create(null);
14709 this.cssStyle = null;
14710 this.forceDataSchema = !!forceDataSchema;
14711 this._operatorIdMapping = [];
14712 for (const op in _util.OPS) {
14713 this._operatorIdMapping[_util.OPS[op]] = op;
14714 }
14715 }
14716 getObject(data, fallback = null) {
14717 if (typeof data === "string") {
14718 return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
14719 }
14720 return fallback;
14721 }
14722 save() {
14723 this.transformStack.push(this.transformMatrix);
14724 const old = this.current;
14725 this.extraStack.push(old);
14726 this.current = old.clone();
14727 }
14728 restore() {
14729 this.transformMatrix = this.transformStack.pop();
14730 this.current = this.extraStack.pop();
14731 this.pendingClip = null;
14732 this.tgrp = null;
14733 }
14734 group(items) {
14735 this.save();
14736 this.executeOpTree(items);
14737 this.restore();
14738 }
14739 loadDependencies(operatorList) {
14740 const fnArray = operatorList.fnArray;
14741 const argsArray = operatorList.argsArray;
14742 for (let i = 0, ii = fnArray.length; i < ii; i++) {
14743 if (fnArray[i] !== _util.OPS.dependency) {
14744 continue;
14745 }
14746 for (const obj of argsArray[i]) {
14747 const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
14748 const promise = new Promise(resolve => {
14749 objsPool.get(obj, resolve);
14750 });
14751 this.current.dependencies.push(promise);
14752 }
14753 }
14754 return Promise.all(this.current.dependencies);
14755 }
14756 transform(a, b, c, d, e, f) {
14757 const transformMatrix = [a, b, c, d, e, f];
14758 this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
14759 this.tgrp = null;
14760 }
14761 getSVG(operatorList, viewport) {
14762 this.viewport = viewport;
14763 const svgElement = this._initialize(viewport);
14764 return this.loadDependencies(operatorList).then(() => {
14765 this.transformMatrix = _util.IDENTITY_MATRIX;
14766 this.executeOpTree(this.convertOpList(operatorList));
14767 return svgElement;
14768 });
14769 }
14770 convertOpList(operatorList) {
14771 const operatorIdMapping = this._operatorIdMapping;
14772 const argsArray = operatorList.argsArray;
14773 const fnArray = operatorList.fnArray;
14774 const opList = [];
14775 for (let i = 0, ii = fnArray.length; i < ii; i++) {
14776 const fnId = fnArray[i];
14777 opList.push({
14778 fnId,
14779 fn: operatorIdMapping[fnId],
14780 args: argsArray[i]
14781 });
14782 }
14783 return opListToTree(opList);
14784 }
14785 executeOpTree(opTree) {
14786 for (const opTreeElement of opTree) {
14787 const fn = opTreeElement.fn;
14788 const fnId = opTreeElement.fnId;
14789 const args = opTreeElement.args;
14790 switch (fnId | 0) {
14791 case _util.OPS.beginText:
14792 this.beginText();
14793 break;
14794 case _util.OPS.dependency:
14795 break;
14796 case _util.OPS.setLeading:
14797 this.setLeading(args);
14798 break;
14799 case _util.OPS.setLeadingMoveText:
14800 this.setLeadingMoveText(args[0], args[1]);
14801 break;
14802 case _util.OPS.setFont:
14803 this.setFont(args);
14804 break;
14805 case _util.OPS.showText:
14806 this.showText(args[0]);
14807 break;
14808 case _util.OPS.showSpacedText:
14809 this.showText(args[0]);
14810 break;
14811 case _util.OPS.endText:
14812 this.endText();
14813 break;
14814 case _util.OPS.moveText:
14815 this.moveText(args[0], args[1]);
14816 break;
14817 case _util.OPS.setCharSpacing:
14818 this.setCharSpacing(args[0]);
14819 break;
14820 case _util.OPS.setWordSpacing:
14821 this.setWordSpacing(args[0]);
14822 break;
14823 case _util.OPS.setHScale:
14824 this.setHScale(args[0]);
14825 break;
14826 case _util.OPS.setTextMatrix:
14827 this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
14828 break;
14829 case _util.OPS.setTextRise:
14830 this.setTextRise(args[0]);
14831 break;
14832 case _util.OPS.setTextRenderingMode:
14833 this.setTextRenderingMode(args[0]);
14834 break;
14835 case _util.OPS.setLineWidth:
14836 this.setLineWidth(args[0]);
14837 break;
14838 case _util.OPS.setLineJoin:
14839 this.setLineJoin(args[0]);
14840 break;
14841 case _util.OPS.setLineCap:
14842 this.setLineCap(args[0]);
14843 break;
14844 case _util.OPS.setMiterLimit:
14845 this.setMiterLimit(args[0]);
14846 break;
14847 case _util.OPS.setFillRGBColor:
14848 this.setFillRGBColor(args[0], args[1], args[2]);
14849 break;
14850 case _util.OPS.setStrokeRGBColor:
14851 this.setStrokeRGBColor(args[0], args[1], args[2]);
14852 break;
14853 case _util.OPS.setStrokeColorN:
14854 this.setStrokeColorN(args);
14855 break;
14856 case _util.OPS.setFillColorN:
14857 this.setFillColorN(args);
14858 break;
14859 case _util.OPS.shadingFill:
14860 this.shadingFill(args[0]);
14861 break;
14862 case _util.OPS.setDash:
14863 this.setDash(args[0], args[1]);
14864 break;
14865 case _util.OPS.setRenderingIntent:
14866 this.setRenderingIntent(args[0]);
14867 break;
14868 case _util.OPS.setFlatness:
14869 this.setFlatness(args[0]);
14870 break;
14871 case _util.OPS.setGState:
14872 this.setGState(args[0]);
14873 break;
14874 case _util.OPS.fill:
14875 this.fill();
14876 break;
14877 case _util.OPS.eoFill:
14878 this.eoFill();
14879 break;
14880 case _util.OPS.stroke:
14881 this.stroke();
14882 break;
14883 case _util.OPS.fillStroke:
14884 this.fillStroke();
14885 break;
14886 case _util.OPS.eoFillStroke:
14887 this.eoFillStroke();
14888 break;
14889 case _util.OPS.clip:
14890 this.clip("nonzero");
14891 break;
14892 case _util.OPS.eoClip:
14893 this.clip("evenodd");
14894 break;
14895 case _util.OPS.paintSolidColorImageMask:
14896 this.paintSolidColorImageMask();
14897 break;
14898 case _util.OPS.paintImageXObject:
14899 this.paintImageXObject(args[0]);
14900 break;
14901 case _util.OPS.paintInlineImageXObject:
14902 this.paintInlineImageXObject(args[0]);
14903 break;
14904 case _util.OPS.paintImageMaskXObject:
14905 this.paintImageMaskXObject(args[0]);
14906 break;
14907 case _util.OPS.paintFormXObjectBegin:
14908 this.paintFormXObjectBegin(args[0], args[1]);
14909 break;
14910 case _util.OPS.paintFormXObjectEnd:
14911 this.paintFormXObjectEnd();
14912 break;
14913 case _util.OPS.closePath:
14914 this.closePath();
14915 break;
14916 case _util.OPS.closeStroke:
14917 this.closeStroke();
14918 break;
14919 case _util.OPS.closeFillStroke:
14920 this.closeFillStroke();
14921 break;
14922 case _util.OPS.closeEOFillStroke:
14923 this.closeEOFillStroke();
14924 break;
14925 case _util.OPS.nextLine:
14926 this.nextLine();
14927 break;
14928 case _util.OPS.transform:
14929 this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
14930 break;
14931 case _util.OPS.constructPath:
14932 this.constructPath(args[0], args[1]);
14933 break;
14934 case _util.OPS.endPath:
14935 this.endPath();
14936 break;
14937 case 92:
14938 this.group(opTreeElement.items);
14939 break;
14940 default:
14941 (0, _util.warn)(`Unimplemented operator ${fn}`);
14942 break;
14943 }
14944 }
14945 }
14946 setWordSpacing(wordSpacing) {
14947 this.current.wordSpacing = wordSpacing;
14948 }
14949 setCharSpacing(charSpacing) {
14950 this.current.charSpacing = charSpacing;
14951 }
14952 nextLine() {
14953 this.moveText(0, this.current.leading);
14954 }
14955 setTextMatrix(a, b, c, d, e, f) {
14956 const current = this.current;
14957 current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
14958 current.textMatrixScale = Math.hypot(a, b);
14959 current.x = current.lineX = 0;
14960 current.y = current.lineY = 0;
14961 current.xcoords = [];
14962 current.ycoords = [];
14963 current.tspan = this.svgFactory.createElement("svg:tspan");
14964 current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
14965 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
14966 current.tspan.setAttributeNS(null, "y", pf(-current.y));
14967 current.txtElement = this.svgFactory.createElement("svg:text");
14968 current.txtElement.append(current.tspan);
14969 }
14970 beginText() {
14971 const current = this.current;
14972 current.x = current.lineX = 0;
14973 current.y = current.lineY = 0;
14974 current.textMatrix = _util.IDENTITY_MATRIX;
14975 current.lineMatrix = _util.IDENTITY_MATRIX;
14976 current.textMatrixScale = 1;
14977 current.tspan = this.svgFactory.createElement("svg:tspan");
14978 current.txtElement = this.svgFactory.createElement("svg:text");
14979 current.txtgrp = this.svgFactory.createElement("svg:g");
14980 current.xcoords = [];
14981 current.ycoords = [];
14982 }
14983 moveText(x, y) {
14984 const current = this.current;
14985 current.x = current.lineX += x;
14986 current.y = current.lineY += y;
14987 current.xcoords = [];
14988 current.ycoords = [];
14989 current.tspan = this.svgFactory.createElement("svg:tspan");
14990 current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
14991 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
14992 current.tspan.setAttributeNS(null, "y", pf(-current.y));
14993 }
14994 showText(glyphs) {
14995 const current = this.current;
14996 const font = current.font;
14997 const fontSize = current.fontSize;
14998 if (fontSize === 0) {
14999 return;
15000 }
15001 const fontSizeScale = current.fontSizeScale;
15002 const charSpacing = current.charSpacing;
15003 const wordSpacing = current.wordSpacing;
15004 const fontDirection = current.fontDirection;
15005 const textHScale = current.textHScale * fontDirection;
15006 const vertical = font.vertical;
15007 const spacingDir = vertical ? 1 : -1;
15008 const defaultVMetrics = font.defaultVMetrics;
15009 const widthAdvanceScale = fontSize * current.fontMatrix[0];
15010 let x = 0;
15011 for (const glyph of glyphs) {
15012 if (glyph === null) {
15013 x += fontDirection * wordSpacing;
15014 continue;
15015 } else if (typeof glyph === "number") {
15016 x += spacingDir * glyph * fontSize / 1000;
15017 continue;
15018 }
15019 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
15020 const character = glyph.fontChar;
15021 let scaledX, scaledY;
15022 let width = glyph.width;
15023 if (vertical) {
15024 let vx;
15025 const vmetric = glyph.vmetric || defaultVMetrics;
15026 vx = glyph.vmetric ? vmetric[1] : width * 0.5;
15027 vx = -vx * widthAdvanceScale;
15028 const vy = vmetric[2] * widthAdvanceScale;
15029 width = vmetric ? -vmetric[0] : width;
15030 scaledX = vx / fontSizeScale;
15031 scaledY = (x + vy) / fontSizeScale;
15032 } else {
15033 scaledX = x / fontSizeScale;
15034 scaledY = 0;
15035 }
15036 if (glyph.isInFont || font.missingFile) {
15037 current.xcoords.push(current.x + scaledX);
15038 if (vertical) {
15039 current.ycoords.push(-current.y + scaledY);
15040 }
15041 current.tspan.textContent += character;
15042 } else {}
15043 let charWidth;
15044 if (vertical) {
15045 charWidth = width * widthAdvanceScale - spacing * fontDirection;
15046 } else {
15047 charWidth = width * widthAdvanceScale + spacing * fontDirection;
15048 }
15049 x += charWidth;
15050 }
15051 current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
15052 if (vertical) {
15053 current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
15054 } else {
15055 current.tspan.setAttributeNS(null, "y", pf(-current.y));
15056 }
15057 if (vertical) {
15058 current.y -= x;
15059 } else {
15060 current.x += x * textHScale;
15061 }
15062 current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
15063 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
15064 if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
15065 current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
15066 }
15067 if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
15068 current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
15069 }
15070 const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
15071 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
15072 if (current.fillColor !== SVG_DEFAULTS.fillColor) {
15073 current.tspan.setAttributeNS(null, "fill", current.fillColor);
15074 }
15075 if (current.fillAlpha < 1) {
15076 current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
15077 }
15078 } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
15079 current.tspan.setAttributeNS(null, "fill", "transparent");
15080 } else {
15081 current.tspan.setAttributeNS(null, "fill", "none");
15082 }
15083 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
15084 const lineWidthScale = 1 / (current.textMatrixScale || 1);
15085 this._setStrokeAttributes(current.tspan, lineWidthScale);
15086 }
15087 let textMatrix = current.textMatrix;
15088 if (current.textRise !== 0) {
15089 textMatrix = textMatrix.slice();
15090 textMatrix[5] += current.textRise;
15091 }
15092 current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
15093 current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
15094 current.txtElement.append(current.tspan);
15095 current.txtgrp.append(current.txtElement);
15096 this._ensureTransformGroup().append(current.txtElement);
15097 }
15098 setLeadingMoveText(x, y) {
15099 this.setLeading(-y);
15100 this.moveText(x, y);
15101 }
15102 addFontStyle(fontObj) {
15103 if (!fontObj.data) {
15104 throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
15105 }
15106 if (!this.cssStyle) {
15107 this.cssStyle = this.svgFactory.createElement("svg:style");
15108 this.cssStyle.setAttributeNS(null, "type", "text/css");
15109 this.defs.append(this.cssStyle);
15110 }
15111 const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
15112 this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
15113 }
15114 setFont(details) {
15115 const current = this.current;
15116 const fontObj = this.commonObjs.get(details[0]);
15117 let size = details[1];
15118 current.font = fontObj;
15119 if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
15120 this.addFontStyle(fontObj);
15121 this.embeddedFonts[fontObj.loadedName] = fontObj;
15122 }
15123 current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
15124 let bold = "normal";
15125 if (fontObj.black) {
15126 bold = "900";
15127 } else if (fontObj.bold) {
15128 bold = "bold";
15129 }
15130 const italic = fontObj.italic ? "italic" : "normal";
15131 if (size < 0) {
15132 size = -size;
15133 current.fontDirection = -1;
15134 } else {
15135 current.fontDirection = 1;
15136 }
15137 current.fontSize = size;
15138 current.fontFamily = fontObj.loadedName;
15139 current.fontWeight = bold;
15140 current.fontStyle = italic;
15141 current.tspan = this.svgFactory.createElement("svg:tspan");
15142 current.tspan.setAttributeNS(null, "y", pf(-current.y));
15143 current.xcoords = [];
15144 current.ycoords = [];
15145 }
15146 endText() {
15147 const current = this.current;
15148 if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
15149 current.element = current.txtElement;
15150 this.clip("nonzero");
15151 this.endPath();
15152 }
15153 }
15154 setLineWidth(width) {
15155 if (width > 0) {
15156 this.current.lineWidth = width;
15157 }
15158 }
15159 setLineCap(style) {
15160 this.current.lineCap = LINE_CAP_STYLES[style];
15161 }
15162 setLineJoin(style) {
15163 this.current.lineJoin = LINE_JOIN_STYLES[style];
15164 }
15165 setMiterLimit(limit) {
15166 this.current.miterLimit = limit;
15167 }
15168 setStrokeAlpha(strokeAlpha) {
15169 this.current.strokeAlpha = strokeAlpha;
15170 }
15171 setStrokeRGBColor(r, g, b) {
15172 this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
15173 }
15174 setFillAlpha(fillAlpha) {
15175 this.current.fillAlpha = fillAlpha;
15176 }
15177 setFillRGBColor(r, g, b) {
15178 this.current.fillColor = _util.Util.makeHexColor(r, g, b);
15179 this.current.tspan = this.svgFactory.createElement("svg:tspan");
15180 this.current.xcoords = [];
15181 this.current.ycoords = [];
15182 }
15183 setStrokeColorN(args) {
15184 this.current.strokeColor = this._makeColorN_Pattern(args);
15185 }
15186 setFillColorN(args) {
15187 this.current.fillColor = this._makeColorN_Pattern(args);
15188 }
15189 shadingFill(args) {
15190 const width = this.viewport.width;
15191 const height = this.viewport.height;
15192 const inv = _util.Util.inverseTransform(this.transformMatrix);
15193 const bl = _util.Util.applyTransform([0, 0], inv);
15194 const br = _util.Util.applyTransform([0, height], inv);
15195 const ul = _util.Util.applyTransform([width, 0], inv);
15196 const ur = _util.Util.applyTransform([width, height], inv);
15197 const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
15198 const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
15199 const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
15200 const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
15201 const rect = this.svgFactory.createElement("svg:rect");
15202 rect.setAttributeNS(null, "x", x0);
15203 rect.setAttributeNS(null, "y", y0);
15204 rect.setAttributeNS(null, "width", x1 - x0);
15205 rect.setAttributeNS(null, "height", y1 - y0);
15206 rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
15207 if (this.current.fillAlpha < 1) {
15208 rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
15209 }
15210 this._ensureTransformGroup().append(rect);
15211 }
15212 _makeColorN_Pattern(args) {
15213 if (args[0] === "TilingPattern") {
15214 return this._makeTilingPattern(args);
15215 }
15216 return this._makeShadingPattern(args);
15217 }
15218 _makeTilingPattern(args) {
15219 const color = args[1];
15220 const operatorList = args[2];
15221 const matrix = args[3] || _util.IDENTITY_MATRIX;
15222 const [x0, y0, x1, y1] = args[4];
15223 const xstep = args[5];
15224 const ystep = args[6];
15225 const paintType = args[7];
15226 const tilingId = `shading${shadingCount++}`;
15227 const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
15228 const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
15229 const txstep = xstep * xscale;
15230 const tystep = ystep * yscale;
15231 const tiling = this.svgFactory.createElement("svg:pattern");
15232 tiling.setAttributeNS(null, "id", tilingId);
15233 tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
15234 tiling.setAttributeNS(null, "width", txstep);
15235 tiling.setAttributeNS(null, "height", tystep);
15236 tiling.setAttributeNS(null, "x", `${tx0}`);
15237 tiling.setAttributeNS(null, "y", `${ty0}`);
15238 const svg = this.svg;
15239 const transformMatrix = this.transformMatrix;
15240 const fillColor = this.current.fillColor;
15241 const strokeColor = this.current.strokeColor;
15242 const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
15243 this.svg = bbox;
15244 this.transformMatrix = matrix;
15245 if (paintType === 2) {
15246 const cssColor = _util.Util.makeHexColor(...color);
15247 this.current.fillColor = cssColor;
15248 this.current.strokeColor = cssColor;
15249 }
15250 this.executeOpTree(this.convertOpList(operatorList));
15251 this.svg = svg;
15252 this.transformMatrix = transformMatrix;
15253 this.current.fillColor = fillColor;
15254 this.current.strokeColor = strokeColor;
15255 tiling.append(bbox.childNodes[0]);
15256 this.defs.append(tiling);
15257 return `url(#${tilingId})`;
15258 }
15259 _makeShadingPattern(args) {
15260 if (typeof args === "string") {
15261 args = this.objs.get(args);
15262 }
15263 switch (args[0]) {
15264 case "RadialAxial":
15265 const shadingId = `shading${shadingCount++}`;
15266 const colorStops = args[3];
15267 let gradient;
15268 switch (args[1]) {
15269 case "axial":
15270 const point0 = args[4];
15271 const point1 = args[5];
15272 gradient = this.svgFactory.createElement("svg:linearGradient");
15273 gradient.setAttributeNS(null, "id", shadingId);
15274 gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
15275 gradient.setAttributeNS(null, "x1", point0[0]);
15276 gradient.setAttributeNS(null, "y1", point0[1]);
15277 gradient.setAttributeNS(null, "x2", point1[0]);
15278 gradient.setAttributeNS(null, "y2", point1[1]);
15279 break;
15280 case "radial":
15281 const focalPoint = args[4];
15282 const circlePoint = args[5];
15283 const focalRadius = args[6];
15284 const circleRadius = args[7];
15285 gradient = this.svgFactory.createElement("svg:radialGradient");
15286 gradient.setAttributeNS(null, "id", shadingId);
15287 gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
15288 gradient.setAttributeNS(null, "cx", circlePoint[0]);
15289 gradient.setAttributeNS(null, "cy", circlePoint[1]);
15290 gradient.setAttributeNS(null, "r", circleRadius);
15291 gradient.setAttributeNS(null, "fx", focalPoint[0]);
15292 gradient.setAttributeNS(null, "fy", focalPoint[1]);
15293 gradient.setAttributeNS(null, "fr", focalRadius);
15294 break;
15295 default:
15296 throw new Error(`Unknown RadialAxial type: ${args[1]}`);
15297 }
15298 for (const colorStop of colorStops) {
15299 const stop = this.svgFactory.createElement("svg:stop");
15300 stop.setAttributeNS(null, "offset", colorStop[0]);
15301 stop.setAttributeNS(null, "stop-color", colorStop[1]);
15302 gradient.append(stop);
15303 }
15304 this.defs.append(gradient);
15305 return `url(#${shadingId})`;
15306 case "Mesh":
15307 (0, _util.warn)("Unimplemented pattern Mesh");
15308 return null;
15309 case "Dummy":
15310 return "hotpink";
15311 default:
15312 throw new Error(`Unknown IR type: ${args[0]}`);
15313 }
15314 }
15315 setDash(dashArray, dashPhase) {
15316 this.current.dashArray = dashArray;
15317 this.current.dashPhase = dashPhase;
15318 }
15319 constructPath(ops, args) {
15320 const current = this.current;
15321 let x = current.x,
15322 y = current.y;
15323 let d = [];
15324 let j = 0;
15325 for (const op of ops) {
15326 switch (op | 0) {
15327 case _util.OPS.rectangle:
15328 x = args[j++];
15329 y = args[j++];
15330 const width = args[j++];
15331 const height = args[j++];
15332 const xw = x + width;
15333 const yh = y + height;
15334 d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
15335 break;
15336 case _util.OPS.moveTo:
15337 x = args[j++];
15338 y = args[j++];
15339 d.push("M", pf(x), pf(y));
15340 break;
15341 case _util.OPS.lineTo:
15342 x = args[j++];
15343 y = args[j++];
15344 d.push("L", pf(x), pf(y));
15345 break;
15346 case _util.OPS.curveTo:
15347 x = args[j + 4];
15348 y = args[j + 5];
15349 d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
15350 j += 6;
15351 break;
15352 case _util.OPS.curveTo2:
15353 d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
15354 x = args[j + 2];
15355 y = args[j + 3];
15356 j += 4;
15357 break;
15358 case _util.OPS.curveTo3:
15359 x = args[j + 2];
15360 y = args[j + 3];
15361 d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
15362 j += 4;
15363 break;
15364 case _util.OPS.closePath:
15365 d.push("Z");
15366 break;
15367 }
15368 }
15369 d = d.join(" ");
15370 if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
15371 d = current.path.getAttributeNS(null, "d") + d;
15372 } else {
15373 current.path = this.svgFactory.createElement("svg:path");
15374 this._ensureTransformGroup().append(current.path);
15375 }
15376 current.path.setAttributeNS(null, "d", d);
15377 current.path.setAttributeNS(null, "fill", "none");
15378 current.element = current.path;
15379 current.setCurrentPoint(x, y);
15380 }
15381 endPath() {
15382 const current = this.current;
15383 current.path = null;
15384 if (!this.pendingClip) {
15385 return;
15386 }
15387 if (!current.element) {
15388 this.pendingClip = null;
15389 return;
15390 }
15391 const clipId = `clippath${clipCount++}`;
15392 const clipPath = this.svgFactory.createElement("svg:clipPath");
15393 clipPath.setAttributeNS(null, "id", clipId);
15394 clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
15395 const clipElement = current.element.cloneNode(true);
15396 if (this.pendingClip === "evenodd") {
15397 clipElement.setAttributeNS(null, "clip-rule", "evenodd");
15398 } else {
15399 clipElement.setAttributeNS(null, "clip-rule", "nonzero");
15400 }
15401 this.pendingClip = null;
15402 clipPath.append(clipElement);
15403 this.defs.append(clipPath);
15404 if (current.activeClipUrl) {
15405 current.clipGroup = null;
15406 for (const prev of this.extraStack) {
15407 prev.clipGroup = null;
15408 }
15409 clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
15410 }
15411 current.activeClipUrl = `url(#${clipId})`;
15412 this.tgrp = null;
15413 }
15414 clip(type) {
15415 this.pendingClip = type;
15416 }
15417 closePath() {
15418 const current = this.current;
15419 if (current.path) {
15420 const d = `${current.path.getAttributeNS(null, "d")}Z`;
15421 current.path.setAttributeNS(null, "d", d);
15422 }
15423 }
15424 setLeading(leading) {
15425 this.current.leading = -leading;
15426 }
15427 setTextRise(textRise) {
15428 this.current.textRise = textRise;
15429 }
15430 setTextRenderingMode(textRenderingMode) {
15431 this.current.textRenderingMode = textRenderingMode;
15432 }
15433 setHScale(scale) {
15434 this.current.textHScale = scale / 100;
15435 }
15436 setRenderingIntent(intent) {}
15437 setFlatness(flatness) {}
15438 setGState(states) {
15439 for (const [key, value] of states) {
15440 switch (key) {
15441 case "LW":
15442 this.setLineWidth(value);
15443 break;
15444 case "LC":
15445 this.setLineCap(value);
15446 break;
15447 case "LJ":
15448 this.setLineJoin(value);
15449 break;
15450 case "ML":
15451 this.setMiterLimit(value);
15452 break;
15453 case "D":
15454 this.setDash(value[0], value[1]);
15455 break;
15456 case "RI":
15457 this.setRenderingIntent(value);
15458 break;
15459 case "FL":
15460 this.setFlatness(value);
15461 break;
15462 case "Font":
15463 this.setFont(value);
15464 break;
15465 case "CA":
15466 this.setStrokeAlpha(value);
15467 break;
15468 case "ca":
15469 this.setFillAlpha(value);
15470 break;
15471 default:
15472 (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
15473 break;
15474 }
15475 }
15476 }
15477 fill() {
15478 const current = this.current;
15479 if (current.element) {
15480 current.element.setAttributeNS(null, "fill", current.fillColor);
15481 current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
15482 this.endPath();
15483 }
15484 }
15485 stroke() {
15486 const current = this.current;
15487 if (current.element) {
15488 this._setStrokeAttributes(current.element);
15489 current.element.setAttributeNS(null, "fill", "none");
15490 this.endPath();
15491 }
15492 }
15493 _setStrokeAttributes(element, lineWidthScale = 1) {
15494 const current = this.current;
15495 let dashArray = current.dashArray;
15496 if (lineWidthScale !== 1 && dashArray.length > 0) {
15497 dashArray = dashArray.map(function (value) {
15498 return lineWidthScale * value;
15499 });
15500 }
15501 element.setAttributeNS(null, "stroke", current.strokeColor);
15502 element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
15503 element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
15504 element.setAttributeNS(null, "stroke-linecap", current.lineCap);
15505 element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
15506 element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
15507 element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
15508 element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
15509 }
15510 eoFill() {
15511 this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
15512 this.fill();
15513 }
15514 fillStroke() {
15515 this.stroke();
15516 this.fill();
15517 }
15518 eoFillStroke() {
15519 this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
15520 this.fillStroke();
15521 }
15522 closeStroke() {
15523 this.closePath();
15524 this.stroke();
15525 }
15526 closeFillStroke() {
15527 this.closePath();
15528 this.fillStroke();
15529 }
15530 closeEOFillStroke() {
15531 this.closePath();
15532 this.eoFillStroke();
15533 }
15534 paintSolidColorImageMask() {
15535 const rect = this.svgFactory.createElement("svg:rect");
15536 rect.setAttributeNS(null, "x", "0");
15537 rect.setAttributeNS(null, "y", "0");
15538 rect.setAttributeNS(null, "width", "1px");
15539 rect.setAttributeNS(null, "height", "1px");
15540 rect.setAttributeNS(null, "fill", this.current.fillColor);
15541 this._ensureTransformGroup().append(rect);
15542 }
15543 paintImageXObject(objId) {
15544 const imgData = this.getObject(objId);
15545 if (!imgData) {
15546 (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
15547 return;
15548 }
15549 this.paintInlineImageXObject(imgData);
15550 }
15551 paintInlineImageXObject(imgData, mask) {
15552 const width = imgData.width;
15553 const height = imgData.height;
15554 const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
15555 const cliprect = this.svgFactory.createElement("svg:rect");
15556 cliprect.setAttributeNS(null, "x", "0");
15557 cliprect.setAttributeNS(null, "y", "0");
15558 cliprect.setAttributeNS(null, "width", pf(width));
15559 cliprect.setAttributeNS(null, "height", pf(height));
15560 this.current.element = cliprect;
15561 this.clip("nonzero");
15562 const imgEl = this.svgFactory.createElement("svg:image");
15563 imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
15564 imgEl.setAttributeNS(null, "x", "0");
15565 imgEl.setAttributeNS(null, "y", pf(-height));
15566 imgEl.setAttributeNS(null, "width", pf(width) + "px");
15567 imgEl.setAttributeNS(null, "height", pf(height) + "px");
15568 imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
15569 if (mask) {
15570 mask.append(imgEl);
15571 } else {
15572 this._ensureTransformGroup().append(imgEl);
15573 }
15574 }
15575 paintImageMaskXObject(img) {
15576 const imgData = this.getObject(img.data, img);
15577 if (imgData.bitmap) {
15578 (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
15579 return;
15580 }
15581 const current = this.current;
15582 const width = imgData.width;
15583 const height = imgData.height;
15584 const fillColor = current.fillColor;
15585 current.maskId = `mask${maskCount++}`;
15586 const mask = this.svgFactory.createElement("svg:mask");
15587 mask.setAttributeNS(null, "id", current.maskId);
15588 const rect = this.svgFactory.createElement("svg:rect");
15589 rect.setAttributeNS(null, "x", "0");
15590 rect.setAttributeNS(null, "y", "0");
15591 rect.setAttributeNS(null, "width", pf(width));
15592 rect.setAttributeNS(null, "height", pf(height));
15593 rect.setAttributeNS(null, "fill", fillColor);
15594 rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
15595 this.defs.append(mask);
15596 this._ensureTransformGroup().append(rect);
15597 this.paintInlineImageXObject(imgData, mask);
15598 }
15599 paintFormXObjectBegin(matrix, bbox) {
15600 if (Array.isArray(matrix) && matrix.length === 6) {
15601 this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
15602 }
15603 if (bbox) {
15604 const width = bbox[2] - bbox[0];
15605 const height = bbox[3] - bbox[1];
15606 const cliprect = this.svgFactory.createElement("svg:rect");
15607 cliprect.setAttributeNS(null, "x", bbox[0]);
15608 cliprect.setAttributeNS(null, "y", bbox[1]);
15609 cliprect.setAttributeNS(null, "width", pf(width));
15610 cliprect.setAttributeNS(null, "height", pf(height));
15611 this.current.element = cliprect;
15612 this.clip("nonzero");
15613 this.endPath();
15614 }
15615 }
15616 paintFormXObjectEnd() {}
15617 _initialize(viewport) {
15618 const svg = this.svgFactory.create(viewport.width, viewport.height);
15619 const definitions = this.svgFactory.createElement("svg:defs");
15620 svg.append(definitions);
15621 this.defs = definitions;
15622 const rootGroup = this.svgFactory.createElement("svg:g");
15623 rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
15624 svg.append(rootGroup);
15625 this.svg = rootGroup;
15626 return svg;
15627 }
15628 _ensureClipGroup() {
15629 if (!this.current.clipGroup) {
15630 const clipGroup = this.svgFactory.createElement("svg:g");
15631 clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
15632 this.svg.append(clipGroup);
15633 this.current.clipGroup = clipGroup;
15634 }
15635 return this.current.clipGroup;
15636 }
15637 _ensureTransformGroup() {
15638 if (!this.tgrp) {
15639 this.tgrp = this.svgFactory.createElement("svg:g");
15640 this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
15641 if (this.current.activeClipUrl) {
15642 this._ensureClipGroup().append(this.tgrp);
15643 } else {
15644 this.svg.append(this.tgrp);
15645 }
15646 }
15647 return this.tgrp;
15648 }
15649 };
15650}
15651
15652/***/ })
15653/******/ ]);
15654/************************************************************************/
15655/******/ // The module cache
15656/******/ var __webpack_module_cache__ = {};
15657/******/
15658/******/ // The require function
15659/******/ function __w_pdfjs_require__(moduleId) {
15660/******/ // Check if module is in cache
15661/******/ var cachedModule = __webpack_module_cache__[moduleId];
15662/******/ if (cachedModule !== undefined) {
15663/******/ return cachedModule.exports;
15664/******/ }
15665/******/ // Create a new module (and put it into the cache)
15666/******/ var module = __webpack_module_cache__[moduleId] = {
15667/******/ // no module.id needed
15668/******/ // no module.loaded needed
15669/******/ exports: {}
15670/******/ };
15671/******/
15672/******/ // Execute the module function
15673/******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
15674/******/
15675/******/ // Return the exports of the module
15676/******/ return module.exports;
15677/******/ }
15678/******/
15679/************************************************************************/
15680var __webpack_exports__ = {};
15681// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
15682(() => {
15683var exports = __webpack_exports__;
15684
15685
15686Object.defineProperty(exports, "__esModule", ({
15687 value: true
15688}));
15689Object.defineProperty(exports, "AbortException", ({
15690 enumerable: true,
15691 get: function () {
15692 return _util.AbortException;
15693 }
15694}));
15695Object.defineProperty(exports, "AnnotationEditorLayer", ({
15696 enumerable: true,
15697 get: function () {
15698 return _annotation_editor_layer.AnnotationEditorLayer;
15699 }
15700}));
15701Object.defineProperty(exports, "AnnotationEditorParamsType", ({
15702 enumerable: true,
15703 get: function () {
15704 return _util.AnnotationEditorParamsType;
15705 }
15706}));
15707Object.defineProperty(exports, "AnnotationEditorType", ({
15708 enumerable: true,
15709 get: function () {
15710 return _util.AnnotationEditorType;
15711 }
15712}));
15713Object.defineProperty(exports, "AnnotationEditorUIManager", ({
15714 enumerable: true,
15715 get: function () {
15716 return _tools.AnnotationEditorUIManager;
15717 }
15718}));
15719Object.defineProperty(exports, "AnnotationLayer", ({
15720 enumerable: true,
15721 get: function () {
15722 return _annotation_layer.AnnotationLayer;
15723 }
15724}));
15725Object.defineProperty(exports, "AnnotationMode", ({
15726 enumerable: true,
15727 get: function () {
15728 return _util.AnnotationMode;
15729 }
15730}));
15731Object.defineProperty(exports, "CMapCompressionType", ({
15732 enumerable: true,
15733 get: function () {
15734 return _util.CMapCompressionType;
15735 }
15736}));
15737Object.defineProperty(exports, "FeatureTest", ({
15738 enumerable: true,
15739 get: function () {
15740 return _util.FeatureTest;
15741 }
15742}));
15743Object.defineProperty(exports, "GlobalWorkerOptions", ({
15744 enumerable: true,
15745 get: function () {
15746 return _worker_options.GlobalWorkerOptions;
15747 }
15748}));
15749Object.defineProperty(exports, "InvalidPDFException", ({
15750 enumerable: true,
15751 get: function () {
15752 return _util.InvalidPDFException;
15753 }
15754}));
15755Object.defineProperty(exports, "MissingPDFException", ({
15756 enumerable: true,
15757 get: function () {
15758 return _util.MissingPDFException;
15759 }
15760}));
15761Object.defineProperty(exports, "OPS", ({
15762 enumerable: true,
15763 get: function () {
15764 return _util.OPS;
15765 }
15766}));
15767Object.defineProperty(exports, "PDFDataRangeTransport", ({
15768 enumerable: true,
15769 get: function () {
15770 return _api.PDFDataRangeTransport;
15771 }
15772}));
15773Object.defineProperty(exports, "PDFDateString", ({
15774 enumerable: true,
15775 get: function () {
15776 return _display_utils.PDFDateString;
15777 }
15778}));
15779Object.defineProperty(exports, "PDFWorker", ({
15780 enumerable: true,
15781 get: function () {
15782 return _api.PDFWorker;
15783 }
15784}));
15785Object.defineProperty(exports, "PasswordResponses", ({
15786 enumerable: true,
15787 get: function () {
15788 return _util.PasswordResponses;
15789 }
15790}));
15791Object.defineProperty(exports, "PermissionFlag", ({
15792 enumerable: true,
15793 get: function () {
15794 return _util.PermissionFlag;
15795 }
15796}));
15797Object.defineProperty(exports, "PixelsPerInch", ({
15798 enumerable: true,
15799 get: function () {
15800 return _display_utils.PixelsPerInch;
15801 }
15802}));
15803Object.defineProperty(exports, "RenderingCancelledException", ({
15804 enumerable: true,
15805 get: function () {
15806 return _display_utils.RenderingCancelledException;
15807 }
15808}));
15809Object.defineProperty(exports, "SVGGraphics", ({
15810 enumerable: true,
15811 get: function () {
15812 return _svg.SVGGraphics;
15813 }
15814}));
15815Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
15816 enumerable: true,
15817 get: function () {
15818 return _util.UNSUPPORTED_FEATURES;
15819 }
15820}));
15821Object.defineProperty(exports, "UnexpectedResponseException", ({
15822 enumerable: true,
15823 get: function () {
15824 return _util.UnexpectedResponseException;
15825 }
15826}));
15827Object.defineProperty(exports, "Util", ({
15828 enumerable: true,
15829 get: function () {
15830 return _util.Util;
15831 }
15832}));
15833Object.defineProperty(exports, "VerbosityLevel", ({
15834 enumerable: true,
15835 get: function () {
15836 return _util.VerbosityLevel;
15837 }
15838}));
15839Object.defineProperty(exports, "XfaLayer", ({
15840 enumerable: true,
15841 get: function () {
15842 return _xfa_layer.XfaLayer;
15843 }
15844}));
15845Object.defineProperty(exports, "build", ({
15846 enumerable: true,
15847 get: function () {
15848 return _api.build;
15849 }
15850}));
15851Object.defineProperty(exports, "createPromiseCapability", ({
15852 enumerable: true,
15853 get: function () {
15854 return _util.createPromiseCapability;
15855 }
15856}));
15857Object.defineProperty(exports, "createValidAbsoluteUrl", ({
15858 enumerable: true,
15859 get: function () {
15860 return _util.createValidAbsoluteUrl;
15861 }
15862}));
15863Object.defineProperty(exports, "getDocument", ({
15864 enumerable: true,
15865 get: function () {
15866 return _api.getDocument;
15867 }
15868}));
15869Object.defineProperty(exports, "getFilenameFromUrl", ({
15870 enumerable: true,
15871 get: function () {
15872 return _display_utils.getFilenameFromUrl;
15873 }
15874}));
15875Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
15876 enumerable: true,
15877 get: function () {
15878 return _display_utils.getPdfFilenameFromUrl;
15879 }
15880}));
15881Object.defineProperty(exports, "getXfaPageViewport", ({
15882 enumerable: true,
15883 get: function () {
15884 return _display_utils.getXfaPageViewport;
15885 }
15886}));
15887Object.defineProperty(exports, "isDataScheme", ({
15888 enumerable: true,
15889 get: function () {
15890 return _display_utils.isDataScheme;
15891 }
15892}));
15893Object.defineProperty(exports, "isPdfFile", ({
15894 enumerable: true,
15895 get: function () {
15896 return _display_utils.isPdfFile;
15897 }
15898}));
15899Object.defineProperty(exports, "loadScript", ({
15900 enumerable: true,
15901 get: function () {
15902 return _display_utils.loadScript;
15903 }
15904}));
15905Object.defineProperty(exports, "renderTextLayer", ({
15906 enumerable: true,
15907 get: function () {
15908 return _text_layer.renderTextLayer;
15909 }
15910}));
15911Object.defineProperty(exports, "setLayerDimensions", ({
15912 enumerable: true,
15913 get: function () {
15914 return _display_utils.setLayerDimensions;
15915 }
15916}));
15917Object.defineProperty(exports, "shadow", ({
15918 enumerable: true,
15919 get: function () {
15920 return _util.shadow;
15921 }
15922}));
15923Object.defineProperty(exports, "updateTextLayer", ({
15924 enumerable: true,
15925 get: function () {
15926 return _text_layer.updateTextLayer;
15927 }
15928}));
15929Object.defineProperty(exports, "version", ({
15930 enumerable: true,
15931 get: function () {
15932 return _api.version;
15933 }
15934}));
15935var _util = __w_pdfjs_require__(1);
15936var _api = __w_pdfjs_require__(2);
15937var _display_utils = __w_pdfjs_require__(6);
15938var _text_layer = __w_pdfjs_require__(26);
15939var _annotation_editor_layer = __w_pdfjs_require__(27);
15940var _tools = __w_pdfjs_require__(5);
15941var _annotation_layer = __w_pdfjs_require__(32);
15942var _worker_options = __w_pdfjs_require__(14);
15943var _svg = __w_pdfjs_require__(35);
15944var _xfa_layer = __w_pdfjs_require__(34);
15945const pdfjsVersion = '3.4.493';
15946const pdfjsBuild = '7b85cf0e7';
15947})();
15948
15949/******/ return __webpack_exports__;
15950/******/ })()
15951;
15952});
15953});