UNPKG

422 kBJavaScriptView Raw
1/**
2 * @licstart The following is the entire license notice for the
3 * Javascript code in this page
4 *
5 * Copyright 2021 Mozilla Foundation
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * @licend The above is the entire license notice for the
20 * Javascript code in this page
21 */
22
23(function webpackUniversalModuleDefinition(root, factory) {
24 if(typeof exports === 'object' && typeof module === 'object')
25 module.exports = factory();
26 else if(typeof define === 'function' && define.amd)
27 define("pdfjs-dist/build/pdf", [], factory);
28 else if(typeof exports === 'object')
29 exports["pdfjs-dist/build/pdf"] = factory();
30 else
31 root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
32})(this, function() {
33return /******/ (() => { // webpackBootstrap
34/******/ "use strict";
35/******/ var __webpack_modules__ = ([
36/* 0 */,
37/* 1 */
38/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
39
40
41
42Object.defineProperty(exports, "__esModule", ({
43 value: true
44}));
45exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.LinkTarget = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = void 0;
46exports.addLinkAttributes = addLinkAttributes;
47exports.deprecated = deprecated;
48exports.getFilenameFromUrl = getFilenameFromUrl;
49exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
50exports.getXfaPageViewport = getXfaPageViewport;
51exports.isDataScheme = isDataScheme;
52exports.isPdfFile = isPdfFile;
53exports.isValidFetchUrl = isValidFetchUrl;
54exports.loadScript = loadScript;
55
56var _util = __w_pdfjs_require__(2);
57
58var _base_factory = __w_pdfjs_require__(5);
59
60const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
61const SVG_NS = "http://www.w3.org/2000/svg";
62const PixelsPerInch = {
63 CSS: 96.0,
64 PDF: 72.0,
65
66 get PDF_TO_CSS_UNITS() {
67 return (0, _util.shadow)(this, "PDF_TO_CSS_UNITS", this.CSS / this.PDF);
68 }
69
70};
71exports.PixelsPerInch = PixelsPerInch;
72
73class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
74 constructor({
75 ownerDocument = globalThis.document
76 } = {}) {
77 super();
78 this._document = ownerDocument;
79 }
80
81 _createCanvas(width, height) {
82 const canvas = this._document.createElement("canvas");
83
84 canvas.width = width;
85 canvas.height = height;
86 return canvas;
87 }
88
89}
90
91exports.DOMCanvasFactory = DOMCanvasFactory;
92
93async function fetchData(url, asTypedArray = false) {
94 if (isValidFetchUrl(url, document.baseURI)) {
95 const response = await fetch(url);
96
97 if (!response.ok) {
98 throw new Error(response.statusText);
99 }
100
101 return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
102 }
103
104 return new Promise((resolve, reject) => {
105 const request = new XMLHttpRequest();
106 request.open("GET", url, true);
107
108 if (asTypedArray) {
109 request.responseType = "arraybuffer";
110 }
111
112 request.onreadystatechange = () => {
113 if (request.readyState !== XMLHttpRequest.DONE) {
114 return;
115 }
116
117 if (request.status === 200 || request.status === 0) {
118 let data;
119
120 if (asTypedArray && request.response) {
121 data = new Uint8Array(request.response);
122 } else if (!asTypedArray && request.responseText) {
123 data = (0, _util.stringToBytes)(request.responseText);
124 }
125
126 if (data) {
127 resolve(data);
128 return;
129 }
130 }
131
132 reject(new Error(request.statusText));
133 };
134
135 request.send(null);
136 });
137}
138
139class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
140 _fetchData(url, compressionType) {
141 return fetchData(url, this.isCompressed).then(data => {
142 return {
143 cMapData: data,
144 compressionType
145 };
146 });
147 }
148
149}
150
151exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
152
153class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
154 _fetchData(url) {
155 return fetchData(url, true);
156 }
157
158}
159
160exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
161
162class DOMSVGFactory extends _base_factory.BaseSVGFactory {
163 _createSVG(type) {
164 return document.createElementNS(SVG_NS, type);
165 }
166
167}
168
169exports.DOMSVGFactory = DOMSVGFactory;
170
171class PageViewport {
172 constructor({
173 viewBox,
174 scale,
175 rotation,
176 offsetX = 0,
177 offsetY = 0,
178 dontFlip = false
179 }) {
180 this.viewBox = viewBox;
181 this.scale = scale;
182 this.rotation = rotation;
183 this.offsetX = offsetX;
184 this.offsetY = offsetY;
185 const centerX = (viewBox[2] + viewBox[0]) / 2;
186 const centerY = (viewBox[3] + viewBox[1]) / 2;
187 let rotateA, rotateB, rotateC, rotateD;
188 rotation %= 360;
189
190 if (rotation < 0) {
191 rotation += 360;
192 }
193
194 switch (rotation) {
195 case 180:
196 rotateA = -1;
197 rotateB = 0;
198 rotateC = 0;
199 rotateD = 1;
200 break;
201
202 case 90:
203 rotateA = 0;
204 rotateB = 1;
205 rotateC = 1;
206 rotateD = 0;
207 break;
208
209 case 270:
210 rotateA = 0;
211 rotateB = -1;
212 rotateC = -1;
213 rotateD = 0;
214 break;
215
216 case 0:
217 rotateA = 1;
218 rotateB = 0;
219 rotateC = 0;
220 rotateD = -1;
221 break;
222
223 default:
224 throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
225 }
226
227 if (dontFlip) {
228 rotateC = -rotateC;
229 rotateD = -rotateD;
230 }
231
232 let offsetCanvasX, offsetCanvasY;
233 let width, height;
234
235 if (rotateA === 0) {
236 offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
237 offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
238 width = Math.abs(viewBox[3] - viewBox[1]) * scale;
239 height = Math.abs(viewBox[2] - viewBox[0]) * scale;
240 } else {
241 offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
242 offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
243 width = Math.abs(viewBox[2] - viewBox[0]) * scale;
244 height = Math.abs(viewBox[3] - viewBox[1]) * scale;
245 }
246
247 this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
248 this.width = width;
249 this.height = height;
250 }
251
252 clone({
253 scale = this.scale,
254 rotation = this.rotation,
255 offsetX = this.offsetX,
256 offsetY = this.offsetY,
257 dontFlip = false
258 } = {}) {
259 return new PageViewport({
260 viewBox: this.viewBox.slice(),
261 scale,
262 rotation,
263 offsetX,
264 offsetY,
265 dontFlip
266 });
267 }
268
269 convertToViewportPoint(x, y) {
270 return _util.Util.applyTransform([x, y], this.transform);
271 }
272
273 convertToViewportRectangle(rect) {
274 const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
275
276 const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
277
278 return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
279 }
280
281 convertToPdfPoint(x, y) {
282 return _util.Util.applyInverseTransform([x, y], this.transform);
283 }
284
285}
286
287exports.PageViewport = PageViewport;
288
289class RenderingCancelledException extends _util.BaseException {
290 constructor(msg, type) {
291 super(msg, "RenderingCancelledException");
292 this.type = type;
293 }
294
295}
296
297exports.RenderingCancelledException = RenderingCancelledException;
298const LinkTarget = {
299 NONE: 0,
300 SELF: 1,
301 BLANK: 2,
302 PARENT: 3,
303 TOP: 4
304};
305exports.LinkTarget = LinkTarget;
306
307function addLinkAttributes(link, {
308 url,
309 target,
310 rel,
311 enabled = true
312} = {}) {
313 (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
314 const urlNullRemoved = (0, _util.removeNullCharacters)(url);
315
316 if (enabled) {
317 link.href = link.title = urlNullRemoved;
318 } else {
319 link.href = "";
320 link.title = `Disabled: ${urlNullRemoved}`;
321
322 link.onclick = () => {
323 return false;
324 };
325 }
326
327 let targetStr = "";
328
329 switch (target) {
330 case LinkTarget.NONE:
331 break;
332
333 case LinkTarget.SELF:
334 targetStr = "_self";
335 break;
336
337 case LinkTarget.BLANK:
338 targetStr = "_blank";
339 break;
340
341 case LinkTarget.PARENT:
342 targetStr = "_parent";
343 break;
344
345 case LinkTarget.TOP:
346 targetStr = "_top";
347 break;
348 }
349
350 link.target = targetStr;
351 link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
352}
353
354function isDataScheme(url) {
355 const ii = url.length;
356 let i = 0;
357
358 while (i < ii && url[i].trim() === "") {
359 i++;
360 }
361
362 return url.substring(i, i + 5).toLowerCase() === "data:";
363}
364
365function isPdfFile(filename) {
366 return typeof filename === "string" && /\.pdf$/i.test(filename);
367}
368
369function getFilenameFromUrl(url) {
370 const anchor = url.indexOf("#");
371 const query = url.indexOf("?");
372 const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
373 return url.substring(url.lastIndexOf("/", end) + 1, end);
374}
375
376function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
377 if (typeof url !== "string") {
378 return defaultFilename;
379 }
380
381 if (isDataScheme(url)) {
382 (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
383 return defaultFilename;
384 }
385
386 const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
387 const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
388 const splitURI = reURI.exec(url);
389 let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
390
391 if (suggestedFilename) {
392 suggestedFilename = suggestedFilename[0];
393
394 if (suggestedFilename.includes("%")) {
395 try {
396 suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
397 } catch (ex) {}
398 }
399 }
400
401 return suggestedFilename || defaultFilename;
402}
403
404class StatTimer {
405 constructor() {
406 this.started = Object.create(null);
407 this.times = [];
408 }
409
410 time(name) {
411 if (name in this.started) {
412 (0, _util.warn)(`Timer is already running for ${name}`);
413 }
414
415 this.started[name] = Date.now();
416 }
417
418 timeEnd(name) {
419 if (!(name in this.started)) {
420 (0, _util.warn)(`Timer has not been started for ${name}`);
421 }
422
423 this.times.push({
424 name,
425 start: this.started[name],
426 end: Date.now()
427 });
428 delete this.started[name];
429 }
430
431 toString() {
432 const outBuf = [];
433 let longest = 0;
434
435 for (const time of this.times) {
436 const name = time.name;
437
438 if (name.length > longest) {
439 longest = name.length;
440 }
441 }
442
443 for (const time of this.times) {
444 const duration = time.end - time.start;
445 outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
446 }
447
448 return outBuf.join("");
449 }
450
451}
452
453exports.StatTimer = StatTimer;
454
455function isValidFetchUrl(url, baseUrl) {
456 try {
457 const {
458 protocol
459 } = baseUrl ? new URL(url, baseUrl) : new URL(url);
460 return protocol === "http:" || protocol === "https:";
461 } catch (ex) {
462 return false;
463 }
464}
465
466function loadScript(src, removeScriptElement = false) {
467 return new Promise((resolve, reject) => {
468 const script = document.createElement("script");
469 script.src = src;
470
471 script.onload = function (evt) {
472 if (removeScriptElement) {
473 script.remove();
474 }
475
476 resolve(evt);
477 };
478
479 script.onerror = function () {
480 reject(new Error(`Cannot load script at: ${script.src}`));
481 };
482
483 (document.head || document.documentElement).appendChild(script);
484 });
485}
486
487function deprecated(details) {
488 console.log("Deprecated API usage: " + details);
489}
490
491let pdfDateStringRegex;
492
493class PDFDateString {
494 static toDateObject(input) {
495 if (!input || !(0, _util.isString)(input)) {
496 return null;
497 }
498
499 if (!pdfDateStringRegex) {
500 pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
501 }
502
503 const matches = pdfDateStringRegex.exec(input);
504
505 if (!matches) {
506 return null;
507 }
508
509 const year = parseInt(matches[1], 10);
510 let month = parseInt(matches[2], 10);
511 month = month >= 1 && month <= 12 ? month - 1 : 0;
512 let day = parseInt(matches[3], 10);
513 day = day >= 1 && day <= 31 ? day : 1;
514 let hour = parseInt(matches[4], 10);
515 hour = hour >= 0 && hour <= 23 ? hour : 0;
516 let minute = parseInt(matches[5], 10);
517 minute = minute >= 0 && minute <= 59 ? minute : 0;
518 let second = parseInt(matches[6], 10);
519 second = second >= 0 && second <= 59 ? second : 0;
520 const universalTimeRelation = matches[7] || "Z";
521 let offsetHour = parseInt(matches[8], 10);
522 offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
523 let offsetMinute = parseInt(matches[9], 10) || 0;
524 offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
525
526 if (universalTimeRelation === "-") {
527 hour += offsetHour;
528 minute += offsetMinute;
529 } else if (universalTimeRelation === "+") {
530 hour -= offsetHour;
531 minute -= offsetMinute;
532 }
533
534 return new Date(Date.UTC(year, month, day, hour, minute, second));
535 }
536
537}
538
539exports.PDFDateString = PDFDateString;
540
541function getXfaPageViewport(xfaPage, {
542 scale = 1,
543 rotation = 0
544}) {
545 const {
546 width,
547 height
548 } = xfaPage.attributes.style;
549 const viewBox = [0, 0, parseInt(width), parseInt(height)];
550 return new PageViewport({
551 viewBox,
552 scale,
553 rotation
554 });
555}
556
557/***/ }),
558/* 2 */
559/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
560
561
562
563Object.defineProperty(exports, "__esModule", ({
564 value: true
565}));
566exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.IsLittleEndianCached = exports.IsEvalSupportedCached = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
567exports.arrayByteLength = arrayByteLength;
568exports.arraysToBytes = arraysToBytes;
569exports.assert = assert;
570exports.bytesToString = bytesToString;
571exports.createObjectURL = createObjectURL;
572exports.createPromiseCapability = createPromiseCapability;
573exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
574exports.escapeString = escapeString;
575exports.getModificationDate = getModificationDate;
576exports.getVerbosityLevel = getVerbosityLevel;
577exports.info = info;
578exports.isArrayBuffer = isArrayBuffer;
579exports.isArrayEqual = isArrayEqual;
580exports.isAscii = isAscii;
581exports.isBool = isBool;
582exports.isNum = isNum;
583exports.isSameOrigin = isSameOrigin;
584exports.isString = isString;
585exports.objectFromMap = objectFromMap;
586exports.objectSize = objectSize;
587exports.removeNullCharacters = removeNullCharacters;
588exports.setVerbosityLevel = setVerbosityLevel;
589exports.shadow = shadow;
590exports.string32 = string32;
591exports.stringToBytes = stringToBytes;
592exports.stringToPDFString = stringToPDFString;
593exports.stringToUTF16BEString = stringToUTF16BEString;
594exports.stringToUTF8String = stringToUTF8String;
595exports.unreachable = unreachable;
596exports.utf8StringToString = utf8StringToString;
597exports.warn = warn;
598
599__w_pdfjs_require__(3);
600
601const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
602exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
603const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
604exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
605const RenderingIntentFlag = {
606 ANY: 0x01,
607 DISPLAY: 0x02,
608 PRINT: 0x04,
609 ANNOTATIONS_FORMS: 0x10,
610 ANNOTATIONS_STORAGE: 0x20,
611 ANNOTATIONS_DISABLE: 0x40,
612 OPLIST: 0x100
613};
614exports.RenderingIntentFlag = RenderingIntentFlag;
615const AnnotationMode = {
616 DISABLE: 0,
617 ENABLE: 1,
618 ENABLE_FORMS: 2,
619 ENABLE_STORAGE: 3
620};
621exports.AnnotationMode = AnnotationMode;
622const PermissionFlag = {
623 PRINT: 0x04,
624 MODIFY_CONTENTS: 0x08,
625 COPY: 0x10,
626 MODIFY_ANNOTATIONS: 0x20,
627 FILL_INTERACTIVE_FORMS: 0x100,
628 COPY_FOR_ACCESSIBILITY: 0x200,
629 ASSEMBLE: 0x400,
630 PRINT_HIGH_QUALITY: 0x800
631};
632exports.PermissionFlag = PermissionFlag;
633const TextRenderingMode = {
634 FILL: 0,
635 STROKE: 1,
636 FILL_STROKE: 2,
637 INVISIBLE: 3,
638 FILL_ADD_TO_PATH: 4,
639 STROKE_ADD_TO_PATH: 5,
640 FILL_STROKE_ADD_TO_PATH: 6,
641 ADD_TO_PATH: 7,
642 FILL_STROKE_MASK: 3,
643 ADD_TO_PATH_FLAG: 4
644};
645exports.TextRenderingMode = TextRenderingMode;
646const ImageKind = {
647 GRAYSCALE_1BPP: 1,
648 RGB_24BPP: 2,
649 RGBA_32BPP: 3
650};
651exports.ImageKind = ImageKind;
652const AnnotationType = {
653 TEXT: 1,
654 LINK: 2,
655 FREETEXT: 3,
656 LINE: 4,
657 SQUARE: 5,
658 CIRCLE: 6,
659 POLYGON: 7,
660 POLYLINE: 8,
661 HIGHLIGHT: 9,
662 UNDERLINE: 10,
663 SQUIGGLY: 11,
664 STRIKEOUT: 12,
665 STAMP: 13,
666 CARET: 14,
667 INK: 15,
668 POPUP: 16,
669 FILEATTACHMENT: 17,
670 SOUND: 18,
671 MOVIE: 19,
672 WIDGET: 20,
673 SCREEN: 21,
674 PRINTERMARK: 22,
675 TRAPNET: 23,
676 WATERMARK: 24,
677 THREED: 25,
678 REDACT: 26
679};
680exports.AnnotationType = AnnotationType;
681const AnnotationStateModelType = {
682 MARKED: "Marked",
683 REVIEW: "Review"
684};
685exports.AnnotationStateModelType = AnnotationStateModelType;
686const AnnotationMarkedState = {
687 MARKED: "Marked",
688 UNMARKED: "Unmarked"
689};
690exports.AnnotationMarkedState = AnnotationMarkedState;
691const AnnotationReviewState = {
692 ACCEPTED: "Accepted",
693 REJECTED: "Rejected",
694 CANCELLED: "Cancelled",
695 COMPLETED: "Completed",
696 NONE: "None"
697};
698exports.AnnotationReviewState = AnnotationReviewState;
699const AnnotationReplyType = {
700 GROUP: "Group",
701 REPLY: "R"
702};
703exports.AnnotationReplyType = AnnotationReplyType;
704const AnnotationFlag = {
705 INVISIBLE: 0x01,
706 HIDDEN: 0x02,
707 PRINT: 0x04,
708 NOZOOM: 0x08,
709 NOROTATE: 0x10,
710 NOVIEW: 0x20,
711 READONLY: 0x40,
712 LOCKED: 0x80,
713 TOGGLENOVIEW: 0x100,
714 LOCKEDCONTENTS: 0x200
715};
716exports.AnnotationFlag = AnnotationFlag;
717const AnnotationFieldFlag = {
718 READONLY: 0x0000001,
719 REQUIRED: 0x0000002,
720 NOEXPORT: 0x0000004,
721 MULTILINE: 0x0001000,
722 PASSWORD: 0x0002000,
723 NOTOGGLETOOFF: 0x0004000,
724 RADIO: 0x0008000,
725 PUSHBUTTON: 0x0010000,
726 COMBO: 0x0020000,
727 EDIT: 0x0040000,
728 SORT: 0x0080000,
729 FILESELECT: 0x0100000,
730 MULTISELECT: 0x0200000,
731 DONOTSPELLCHECK: 0x0400000,
732 DONOTSCROLL: 0x0800000,
733 COMB: 0x1000000,
734 RICHTEXT: 0x2000000,
735 RADIOSINUNISON: 0x2000000,
736 COMMITONSELCHANGE: 0x4000000
737};
738exports.AnnotationFieldFlag = AnnotationFieldFlag;
739const AnnotationBorderStyleType = {
740 SOLID: 1,
741 DASHED: 2,
742 BEVELED: 3,
743 INSET: 4,
744 UNDERLINE: 5
745};
746exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
747const AnnotationActionEventType = {
748 E: "Mouse Enter",
749 X: "Mouse Exit",
750 D: "Mouse Down",
751 U: "Mouse Up",
752 Fo: "Focus",
753 Bl: "Blur",
754 PO: "PageOpen",
755 PC: "PageClose",
756 PV: "PageVisible",
757 PI: "PageInvisible",
758 K: "Keystroke",
759 F: "Format",
760 V: "Validate",
761 C: "Calculate"
762};
763exports.AnnotationActionEventType = AnnotationActionEventType;
764const DocumentActionEventType = {
765 WC: "WillClose",
766 WS: "WillSave",
767 DS: "DidSave",
768 WP: "WillPrint",
769 DP: "DidPrint"
770};
771exports.DocumentActionEventType = DocumentActionEventType;
772const PageActionEventType = {
773 O: "PageOpen",
774 C: "PageClose"
775};
776exports.PageActionEventType = PageActionEventType;
777const StreamType = {
778 UNKNOWN: "UNKNOWN",
779 FLATE: "FLATE",
780 LZW: "LZW",
781 DCT: "DCT",
782 JPX: "JPX",
783 JBIG: "JBIG",
784 A85: "A85",
785 AHX: "AHX",
786 CCF: "CCF",
787 RLX: "RLX"
788};
789exports.StreamType = StreamType;
790const FontType = {
791 UNKNOWN: "UNKNOWN",
792 TYPE1: "TYPE1",
793 TYPE1STANDARD: "TYPE1STANDARD",
794 TYPE1C: "TYPE1C",
795 CIDFONTTYPE0: "CIDFONTTYPE0",
796 CIDFONTTYPE0C: "CIDFONTTYPE0C",
797 TRUETYPE: "TRUETYPE",
798 CIDFONTTYPE2: "CIDFONTTYPE2",
799 TYPE3: "TYPE3",
800 OPENTYPE: "OPENTYPE",
801 TYPE0: "TYPE0",
802 MMTYPE1: "MMTYPE1"
803};
804exports.FontType = FontType;
805const VerbosityLevel = {
806 ERRORS: 0,
807 WARNINGS: 1,
808 INFOS: 5
809};
810exports.VerbosityLevel = VerbosityLevel;
811const CMapCompressionType = {
812 NONE: 0,
813 BINARY: 1,
814 STREAM: 2
815};
816exports.CMapCompressionType = CMapCompressionType;
817const OPS = {
818 dependency: 1,
819 setLineWidth: 2,
820 setLineCap: 3,
821 setLineJoin: 4,
822 setMiterLimit: 5,
823 setDash: 6,
824 setRenderingIntent: 7,
825 setFlatness: 8,
826 setGState: 9,
827 save: 10,
828 restore: 11,
829 transform: 12,
830 moveTo: 13,
831 lineTo: 14,
832 curveTo: 15,
833 curveTo2: 16,
834 curveTo3: 17,
835 closePath: 18,
836 rectangle: 19,
837 stroke: 20,
838 closeStroke: 21,
839 fill: 22,
840 eoFill: 23,
841 fillStroke: 24,
842 eoFillStroke: 25,
843 closeFillStroke: 26,
844 closeEOFillStroke: 27,
845 endPath: 28,
846 clip: 29,
847 eoClip: 30,
848 beginText: 31,
849 endText: 32,
850 setCharSpacing: 33,
851 setWordSpacing: 34,
852 setHScale: 35,
853 setLeading: 36,
854 setFont: 37,
855 setTextRenderingMode: 38,
856 setTextRise: 39,
857 moveText: 40,
858 setLeadingMoveText: 41,
859 setTextMatrix: 42,
860 nextLine: 43,
861 showText: 44,
862 showSpacedText: 45,
863 nextLineShowText: 46,
864 nextLineSetSpacingShowText: 47,
865 setCharWidth: 48,
866 setCharWidthAndBounds: 49,
867 setStrokeColorSpace: 50,
868 setFillColorSpace: 51,
869 setStrokeColor: 52,
870 setStrokeColorN: 53,
871 setFillColor: 54,
872 setFillColorN: 55,
873 setStrokeGray: 56,
874 setFillGray: 57,
875 setStrokeRGBColor: 58,
876 setFillRGBColor: 59,
877 setStrokeCMYKColor: 60,
878 setFillCMYKColor: 61,
879 shadingFill: 62,
880 beginInlineImage: 63,
881 beginImageData: 64,
882 endInlineImage: 65,
883 paintXObject: 66,
884 markPoint: 67,
885 markPointProps: 68,
886 beginMarkedContent: 69,
887 beginMarkedContentProps: 70,
888 endMarkedContent: 71,
889 beginCompat: 72,
890 endCompat: 73,
891 paintFormXObjectBegin: 74,
892 paintFormXObjectEnd: 75,
893 beginGroup: 76,
894 endGroup: 77,
895 beginAnnotations: 78,
896 endAnnotations: 79,
897 beginAnnotation: 80,
898 endAnnotation: 81,
899 paintJpegXObject: 82,
900 paintImageMaskXObject: 83,
901 paintImageMaskXObjectGroup: 84,
902 paintImageXObject: 85,
903 paintInlineImageXObject: 86,
904 paintInlineImageXObjectGroup: 87,
905 paintImageXObjectRepeat: 88,
906 paintImageMaskXObjectRepeat: 89,
907 paintSolidColorImageMask: 90,
908 constructPath: 91
909};
910exports.OPS = OPS;
911const UNSUPPORTED_FEATURES = {
912 unknown: "unknown",
913 forms: "forms",
914 javaScript: "javaScript",
915 signatures: "signatures",
916 smask: "smask",
917 shadingPattern: "shadingPattern",
918 font: "font",
919 errorTilingPattern: "errorTilingPattern",
920 errorExtGState: "errorExtGState",
921 errorXObject: "errorXObject",
922 errorFontLoadType3: "errorFontLoadType3",
923 errorFontState: "errorFontState",
924 errorFontMissing: "errorFontMissing",
925 errorFontTranslate: "errorFontTranslate",
926 errorColorSpace: "errorColorSpace",
927 errorOperatorList: "errorOperatorList",
928 errorFontToUnicode: "errorFontToUnicode",
929 errorFontLoadNative: "errorFontLoadNative",
930 errorFontBuildPath: "errorFontBuildPath",
931 errorFontGetPath: "errorFontGetPath",
932 errorMarkedContent: "errorMarkedContent",
933 errorContentSubStream: "errorContentSubStream"
934};
935exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
936const PasswordResponses = {
937 NEED_PASSWORD: 1,
938 INCORRECT_PASSWORD: 2
939};
940exports.PasswordResponses = PasswordResponses;
941let verbosity = VerbosityLevel.WARNINGS;
942
943function setVerbosityLevel(level) {
944 if (Number.isInteger(level)) {
945 verbosity = level;
946 }
947}
948
949function getVerbosityLevel() {
950 return verbosity;
951}
952
953function info(msg) {
954 if (verbosity >= VerbosityLevel.INFOS) {
955 console.log(`Info: ${msg}`);
956 }
957}
958
959function warn(msg) {
960 if (verbosity >= VerbosityLevel.WARNINGS) {
961 console.log(`Warning: ${msg}`);
962 }
963}
964
965function unreachable(msg) {
966 throw new Error(msg);
967}
968
969function assert(cond, msg) {
970 if (!cond) {
971 unreachable(msg);
972 }
973}
974
975function isSameOrigin(baseUrl, otherUrl) {
976 let base;
977
978 try {
979 base = new URL(baseUrl);
980
981 if (!base.origin || base.origin === "null") {
982 return false;
983 }
984 } catch (e) {
985 return false;
986 }
987
988 const other = new URL(otherUrl, base);
989 return base.origin === other.origin;
990}
991
992function _isValidProtocol(url) {
993 if (!url) {
994 return false;
995 }
996
997 switch (url.protocol) {
998 case "http:":
999 case "https:":
1000 case "ftp:":
1001 case "mailto:":
1002 case "tel:":
1003 return true;
1004
1005 default:
1006 return false;
1007 }
1008}
1009
1010function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
1011 if (!url) {
1012 return null;
1013 }
1014
1015 try {
1016 if (options && typeof url === "string") {
1017 if (options.addDefaultProtocol && url.startsWith("www.")) {
1018 const dots = url.match(/\./g);
1019
1020 if (dots && dots.length >= 2) {
1021 url = `http://${url}`;
1022 }
1023 }
1024
1025 if (options.tryConvertEncoding) {
1026 try {
1027 url = stringToUTF8String(url);
1028 } catch (ex) {}
1029 }
1030 }
1031
1032 const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
1033
1034 if (_isValidProtocol(absoluteUrl)) {
1035 return absoluteUrl;
1036 }
1037 } catch (ex) {}
1038
1039 return null;
1040}
1041
1042function shadow(obj, prop, value) {
1043 Object.defineProperty(obj, prop, {
1044 value,
1045 enumerable: true,
1046 configurable: true,
1047 writable: false
1048 });
1049 return value;
1050}
1051
1052const BaseException = function BaseExceptionClosure() {
1053 function BaseException(message, name) {
1054 if (this.constructor === BaseException) {
1055 unreachable("Cannot initialize BaseException.");
1056 }
1057
1058 this.message = message;
1059 this.name = name;
1060 }
1061
1062 BaseException.prototype = new Error();
1063 BaseException.constructor = BaseException;
1064 return BaseException;
1065}();
1066
1067exports.BaseException = BaseException;
1068
1069class PasswordException extends BaseException {
1070 constructor(msg, code) {
1071 super(msg, "PasswordException");
1072 this.code = code;
1073 }
1074
1075}
1076
1077exports.PasswordException = PasswordException;
1078
1079class UnknownErrorException extends BaseException {
1080 constructor(msg, details) {
1081 super(msg, "UnknownErrorException");
1082 this.details = details;
1083 }
1084
1085}
1086
1087exports.UnknownErrorException = UnknownErrorException;
1088
1089class InvalidPDFException extends BaseException {
1090 constructor(msg) {
1091 super(msg, "InvalidPDFException");
1092 }
1093
1094}
1095
1096exports.InvalidPDFException = InvalidPDFException;
1097
1098class MissingPDFException extends BaseException {
1099 constructor(msg) {
1100 super(msg, "MissingPDFException");
1101 }
1102
1103}
1104
1105exports.MissingPDFException = MissingPDFException;
1106
1107class UnexpectedResponseException extends BaseException {
1108 constructor(msg, status) {
1109 super(msg, "UnexpectedResponseException");
1110 this.status = status;
1111 }
1112
1113}
1114
1115exports.UnexpectedResponseException = UnexpectedResponseException;
1116
1117class FormatError extends BaseException {
1118 constructor(msg) {
1119 super(msg, "FormatError");
1120 }
1121
1122}
1123
1124exports.FormatError = FormatError;
1125
1126class AbortException extends BaseException {
1127 constructor(msg) {
1128 super(msg, "AbortException");
1129 }
1130
1131}
1132
1133exports.AbortException = AbortException;
1134const NullCharactersRegExp = /\x00+/g;
1135const InvisibleCharactersRegExp = /[\x01-\x1F]/g;
1136
1137function removeNullCharacters(str, replaceInvisible = false) {
1138 if (typeof str !== "string") {
1139 warn("The argument for removeNullCharacters must be a string.");
1140 return str;
1141 }
1142
1143 if (replaceInvisible) {
1144 str = str.replace(InvisibleCharactersRegExp, " ");
1145 }
1146
1147 return str.replace(NullCharactersRegExp, "");
1148}
1149
1150function bytesToString(bytes) {
1151 assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString");
1152 const length = bytes.length;
1153 const MAX_ARGUMENT_COUNT = 8192;
1154
1155 if (length < MAX_ARGUMENT_COUNT) {
1156 return String.fromCharCode.apply(null, bytes);
1157 }
1158
1159 const strBuf = [];
1160
1161 for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
1162 const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
1163 const chunk = bytes.subarray(i, chunkEnd);
1164 strBuf.push(String.fromCharCode.apply(null, chunk));
1165 }
1166
1167 return strBuf.join("");
1168}
1169
1170function stringToBytes(str) {
1171 assert(typeof str === "string", "Invalid argument for stringToBytes");
1172 const length = str.length;
1173 const bytes = new Uint8Array(length);
1174
1175 for (let i = 0; i < length; ++i) {
1176 bytes[i] = str.charCodeAt(i) & 0xff;
1177 }
1178
1179 return bytes;
1180}
1181
1182function arrayByteLength(arr) {
1183 if (arr.length !== undefined) {
1184 return arr.length;
1185 }
1186
1187 assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument.");
1188 return arr.byteLength;
1189}
1190
1191function arraysToBytes(arr) {
1192 const length = arr.length;
1193
1194 if (length === 1 && arr[0] instanceof Uint8Array) {
1195 return arr[0];
1196 }
1197
1198 let resultLength = 0;
1199
1200 for (let i = 0; i < length; i++) {
1201 resultLength += arrayByteLength(arr[i]);
1202 }
1203
1204 let pos = 0;
1205 const data = new Uint8Array(resultLength);
1206
1207 for (let i = 0; i < length; i++) {
1208 let item = arr[i];
1209
1210 if (!(item instanceof Uint8Array)) {
1211 if (typeof item === "string") {
1212 item = stringToBytes(item);
1213 } else {
1214 item = new Uint8Array(item);
1215 }
1216 }
1217
1218 const itemLength = item.byteLength;
1219 data.set(item, pos);
1220 pos += itemLength;
1221 }
1222
1223 return data;
1224}
1225
1226function string32(value) {
1227 return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
1228}
1229
1230function objectSize(obj) {
1231 return Object.keys(obj).length;
1232}
1233
1234function objectFromMap(map) {
1235 const obj = Object.create(null);
1236
1237 for (const [key, value] of map) {
1238 obj[key] = value;
1239 }
1240
1241 return obj;
1242}
1243
1244function isLittleEndian() {
1245 const buffer8 = new Uint8Array(4);
1246 buffer8[0] = 1;
1247 const view32 = new Uint32Array(buffer8.buffer, 0, 1);
1248 return view32[0] === 1;
1249}
1250
1251const IsLittleEndianCached = {
1252 get value() {
1253 return shadow(this, "value", isLittleEndian());
1254 }
1255
1256};
1257exports.IsLittleEndianCached = IsLittleEndianCached;
1258
1259function isEvalSupported() {
1260 try {
1261 new Function("");
1262 return true;
1263 } catch (e) {
1264 return false;
1265 }
1266}
1267
1268const IsEvalSupportedCached = {
1269 get value() {
1270 return shadow(this, "value", isEvalSupported());
1271 }
1272
1273};
1274exports.IsEvalSupportedCached = IsEvalSupportedCached;
1275const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
1276
1277class Util {
1278 static makeHexColor(r, g, b) {
1279 return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
1280 }
1281
1282 static transform(m1, m2) {
1283 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]];
1284 }
1285
1286 static applyTransform(p, m) {
1287 const xt = p[0] * m[0] + p[1] * m[2] + m[4];
1288 const yt = p[0] * m[1] + p[1] * m[3] + m[5];
1289 return [xt, yt];
1290 }
1291
1292 static applyInverseTransform(p, m) {
1293 const d = m[0] * m[3] - m[1] * m[2];
1294 const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
1295 const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
1296 return [xt, yt];
1297 }
1298
1299 static getAxialAlignedBoundingBox(r, m) {
1300 const p1 = Util.applyTransform(r, m);
1301 const p2 = Util.applyTransform(r.slice(2, 4), m);
1302 const p3 = Util.applyTransform([r[0], r[3]], m);
1303 const p4 = Util.applyTransform([r[2], r[1]], m);
1304 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])];
1305 }
1306
1307 static inverseTransform(m) {
1308 const d = m[0] * m[3] - m[1] * m[2];
1309 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];
1310 }
1311
1312 static apply3dTransform(m, v) {
1313 return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
1314 }
1315
1316 static singularValueDecompose2dScale(m) {
1317 const transpose = [m[0], m[2], m[1], m[3]];
1318 const a = m[0] * transpose[0] + m[1] * transpose[2];
1319 const b = m[0] * transpose[1] + m[1] * transpose[3];
1320 const c = m[2] * transpose[0] + m[3] * transpose[2];
1321 const d = m[2] * transpose[1] + m[3] * transpose[3];
1322 const first = (a + d) / 2;
1323 const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
1324 const sx = first + second || 1;
1325 const sy = first - second || 1;
1326 return [Math.sqrt(sx), Math.sqrt(sy)];
1327 }
1328
1329 static normalizeRect(rect) {
1330 const r = rect.slice(0);
1331
1332 if (rect[0] > rect[2]) {
1333 r[0] = rect[2];
1334 r[2] = rect[0];
1335 }
1336
1337 if (rect[1] > rect[3]) {
1338 r[1] = rect[3];
1339 r[3] = rect[1];
1340 }
1341
1342 return r;
1343 }
1344
1345 static intersect(rect1, rect2) {
1346 function compare(a, b) {
1347 return a - b;
1348 }
1349
1350 const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
1351 const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
1352 const result = [];
1353 rect1 = Util.normalizeRect(rect1);
1354 rect2 = Util.normalizeRect(rect2);
1355
1356 if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
1357 result[0] = orderedX[1];
1358 result[2] = orderedX[2];
1359 } else {
1360 return null;
1361 }
1362
1363 if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
1364 result[1] = orderedY[1];
1365 result[3] = orderedY[2];
1366 } else {
1367 return null;
1368 }
1369
1370 return result;
1371 }
1372
1373 static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
1374 const tvalues = [],
1375 bounds = [[], []];
1376 let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
1377
1378 for (let i = 0; i < 2; ++i) {
1379 if (i === 0) {
1380 b = 6 * x0 - 12 * x1 + 6 * x2;
1381 a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
1382 c = 3 * x1 - 3 * x0;
1383 } else {
1384 b = 6 * y0 - 12 * y1 + 6 * y2;
1385 a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
1386 c = 3 * y1 - 3 * y0;
1387 }
1388
1389 if (Math.abs(a) < 1e-12) {
1390 if (Math.abs(b) < 1e-12) {
1391 continue;
1392 }
1393
1394 t = -c / b;
1395
1396 if (0 < t && t < 1) {
1397 tvalues.push(t);
1398 }
1399
1400 continue;
1401 }
1402
1403 b2ac = b * b - 4 * c * a;
1404 sqrtb2ac = Math.sqrt(b2ac);
1405
1406 if (b2ac < 0) {
1407 continue;
1408 }
1409
1410 t1 = (-b + sqrtb2ac) / (2 * a);
1411
1412 if (0 < t1 && t1 < 1) {
1413 tvalues.push(t1);
1414 }
1415
1416 t2 = (-b - sqrtb2ac) / (2 * a);
1417
1418 if (0 < t2 && t2 < 1) {
1419 tvalues.push(t2);
1420 }
1421 }
1422
1423 let j = tvalues.length,
1424 mt;
1425 const jlen = j;
1426
1427 while (j--) {
1428 t = tvalues[j];
1429 mt = 1 - t;
1430 bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
1431 bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
1432 }
1433
1434 bounds[0][jlen] = x0;
1435 bounds[1][jlen] = y0;
1436 bounds[0][jlen + 1] = x3;
1437 bounds[1][jlen + 1] = y3;
1438 bounds[0].length = bounds[1].length = jlen + 2;
1439 return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
1440 }
1441
1442}
1443
1444exports.Util = Util;
1445const 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];
1446
1447function stringToPDFString(str) {
1448 const length = str.length,
1449 strBuf = [];
1450
1451 if (str[0] === "\xFE" && str[1] === "\xFF") {
1452 for (let i = 2; i < length; i += 2) {
1453 strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
1454 }
1455 } else if (str[0] === "\xFF" && str[1] === "\xFE") {
1456 for (let i = 2; i < length; i += 2) {
1457 strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i)));
1458 }
1459 } else {
1460 for (let i = 0; i < length; ++i) {
1461 const code = PDFStringTranslateTable[str.charCodeAt(i)];
1462 strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
1463 }
1464 }
1465
1466 return strBuf.join("");
1467}
1468
1469function escapeString(str) {
1470 return str.replace(/([()\\\n\r])/g, match => {
1471 if (match === "\n") {
1472 return "\\n";
1473 } else if (match === "\r") {
1474 return "\\r";
1475 }
1476
1477 return `\\${match}`;
1478 });
1479}
1480
1481function isAscii(str) {
1482 return /^[\x00-\x7F]*$/.test(str);
1483}
1484
1485function stringToUTF16BEString(str) {
1486 const buf = ["\xFE\xFF"];
1487
1488 for (let i = 0, ii = str.length; i < ii; i++) {
1489 const char = str.charCodeAt(i);
1490 buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
1491 }
1492
1493 return buf.join("");
1494}
1495
1496function stringToUTF8String(str) {
1497 return decodeURIComponent(escape(str));
1498}
1499
1500function utf8StringToString(str) {
1501 return unescape(encodeURIComponent(str));
1502}
1503
1504function isBool(v) {
1505 return typeof v === "boolean";
1506}
1507
1508function isNum(v) {
1509 return typeof v === "number";
1510}
1511
1512function isString(v) {
1513 return typeof v === "string";
1514}
1515
1516function isArrayBuffer(v) {
1517 return typeof v === "object" && v !== null && v.byteLength !== undefined;
1518}
1519
1520function isArrayEqual(arr1, arr2) {
1521 if (arr1.length !== arr2.length) {
1522 return false;
1523 }
1524
1525 for (let i = 0, ii = arr1.length; i < ii; i++) {
1526 if (arr1[i] !== arr2[i]) {
1527 return false;
1528 }
1529 }
1530
1531 return true;
1532}
1533
1534function getModificationDate(date = new Date()) {
1535 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")];
1536 return buffer.join("");
1537}
1538
1539function createPromiseCapability() {
1540 const capability = Object.create(null);
1541 let isSettled = false;
1542 Object.defineProperty(capability, "settled", {
1543 get() {
1544 return isSettled;
1545 }
1546
1547 });
1548 capability.promise = new Promise(function (resolve, reject) {
1549 capability.resolve = function (data) {
1550 isSettled = true;
1551 resolve(data);
1552 };
1553
1554 capability.reject = function (reason) {
1555 isSettled = true;
1556 reject(reason);
1557 };
1558 });
1559 return capability;
1560}
1561
1562function createObjectURL(data, contentType = "", forceDataSchema = false) {
1563 if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
1564 return URL.createObjectURL(new Blob([data], {
1565 type: contentType
1566 }));
1567 }
1568
1569 const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
1570 let buffer = `data:${contentType};base64,`;
1571
1572 for (let i = 0, ii = data.length; i < ii; i += 3) {
1573 const b1 = data[i] & 0xff;
1574 const b2 = data[i + 1] & 0xff;
1575 const b3 = data[i + 2] & 0xff;
1576 const d1 = b1 >> 2,
1577 d2 = (b1 & 3) << 4 | b2 >> 4;
1578 const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
1579 const d4 = i + 2 < ii ? b3 & 0x3f : 64;
1580 buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
1581 }
1582
1583 return buffer;
1584}
1585
1586/***/ }),
1587/* 3 */
1588/***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
1589
1590
1591
1592var _is_node = __w_pdfjs_require__(4);
1593
1594;
1595
1596/***/ }),
1597/* 4 */
1598/***/ ((__unused_webpack_module, exports) => {
1599
1600
1601
1602Object.defineProperty(exports, "__esModule", ({
1603 value: true
1604}));
1605exports.isNodeJS = void 0;
1606const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
1607exports.isNodeJS = isNodeJS;
1608
1609/***/ }),
1610/* 5 */
1611/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
1612
1613
1614
1615Object.defineProperty(exports, "__esModule", ({
1616 value: true
1617}));
1618exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
1619
1620var _util = __w_pdfjs_require__(2);
1621
1622class BaseCanvasFactory {
1623 constructor() {
1624 if (this.constructor === BaseCanvasFactory) {
1625 (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
1626 }
1627 }
1628
1629 create(width, height) {
1630 if (width <= 0 || height <= 0) {
1631 throw new Error("Invalid canvas size");
1632 }
1633
1634 const canvas = this._createCanvas(width, height);
1635
1636 return {
1637 canvas,
1638 context: canvas.getContext("2d")
1639 };
1640 }
1641
1642 reset(canvasAndContext, width, height) {
1643 if (!canvasAndContext.canvas) {
1644 throw new Error("Canvas is not specified");
1645 }
1646
1647 if (width <= 0 || height <= 0) {
1648 throw new Error("Invalid canvas size");
1649 }
1650
1651 canvasAndContext.canvas.width = width;
1652 canvasAndContext.canvas.height = height;
1653 }
1654
1655 destroy(canvasAndContext) {
1656 if (!canvasAndContext.canvas) {
1657 throw new Error("Canvas is not specified");
1658 }
1659
1660 canvasAndContext.canvas.width = 0;
1661 canvasAndContext.canvas.height = 0;
1662 canvasAndContext.canvas = null;
1663 canvasAndContext.context = null;
1664 }
1665
1666 _createCanvas(width, height) {
1667 (0, _util.unreachable)("Abstract method `_createCanvas` called.");
1668 }
1669
1670}
1671
1672exports.BaseCanvasFactory = BaseCanvasFactory;
1673
1674class BaseCMapReaderFactory {
1675 constructor({
1676 baseUrl = null,
1677 isCompressed = false
1678 }) {
1679 if (this.constructor === BaseCMapReaderFactory) {
1680 (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
1681 }
1682
1683 this.baseUrl = baseUrl;
1684 this.isCompressed = isCompressed;
1685 }
1686
1687 async fetch({
1688 name
1689 }) {
1690 if (!this.baseUrl) {
1691 throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
1692 }
1693
1694 if (!name) {
1695 throw new Error("CMap name must be specified.");
1696 }
1697
1698 const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
1699 const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
1700 return this._fetchData(url, compressionType).catch(reason => {
1701 throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
1702 });
1703 }
1704
1705 _fetchData(url, compressionType) {
1706 (0, _util.unreachable)("Abstract method `_fetchData` called.");
1707 }
1708
1709}
1710
1711exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
1712
1713class BaseStandardFontDataFactory {
1714 constructor({
1715 baseUrl = null
1716 }) {
1717 if (this.constructor === BaseStandardFontDataFactory) {
1718 (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
1719 }
1720
1721 this.baseUrl = baseUrl;
1722 }
1723
1724 async fetch({
1725 filename
1726 }) {
1727 if (!this.baseUrl) {
1728 throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
1729 }
1730
1731 if (!filename) {
1732 throw new Error("Font filename must be specified.");
1733 }
1734
1735 const url = `${this.baseUrl}${filename}`;
1736 return this._fetchData(url).catch(reason => {
1737 throw new Error(`Unable to load font data at: ${url}`);
1738 });
1739 }
1740
1741 _fetchData(url) {
1742 (0, _util.unreachable)("Abstract method `_fetchData` called.");
1743 }
1744
1745}
1746
1747exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
1748
1749class BaseSVGFactory {
1750 constructor() {
1751 if (this.constructor === BaseSVGFactory) {
1752 (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
1753 }
1754 }
1755
1756 create(width, height) {
1757 if (width <= 0 || height <= 0) {
1758 throw new Error("Invalid SVG dimensions");
1759 }
1760
1761 const svg = this._createSVG("svg:svg");
1762
1763 svg.setAttribute("version", "1.1");
1764 svg.setAttribute("width", `${width}px`);
1765 svg.setAttribute("height", `${height}px`);
1766 svg.setAttribute("preserveAspectRatio", "none");
1767 svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
1768 return svg;
1769 }
1770
1771 createElement(type) {
1772 if (typeof type !== "string") {
1773 throw new Error("Invalid SVG element type");
1774 }
1775
1776 return this._createSVG(type);
1777 }
1778
1779 _createSVG(type) {
1780 (0, _util.unreachable)("Abstract method `_createSVG` called.");
1781 }
1782
1783}
1784
1785exports.BaseSVGFactory = BaseSVGFactory;
1786
1787/***/ }),
1788/* 6 */
1789/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
1790
1791
1792
1793Object.defineProperty(exports, "__esModule", ({
1794 value: true
1795}));
1796exports.build = exports.RenderTask = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
1797exports.getDocument = getDocument;
1798exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
1799exports.version = void 0;
1800
1801var _util = __w_pdfjs_require__(2);
1802
1803var _display_utils = __w_pdfjs_require__(1);
1804
1805var _font_loader = __w_pdfjs_require__(7);
1806
1807var _node_utils = __w_pdfjs_require__(8);
1808
1809var _annotation_storage = __w_pdfjs_require__(9);
1810
1811var _canvas = __w_pdfjs_require__(10);
1812
1813var _worker_options = __w_pdfjs_require__(12);
1814
1815var _is_node = __w_pdfjs_require__(4);
1816
1817var _message_handler = __w_pdfjs_require__(13);
1818
1819var _metadata = __w_pdfjs_require__(14);
1820
1821var _optional_content_config = __w_pdfjs_require__(15);
1822
1823var _transport_stream = __w_pdfjs_require__(16);
1824
1825var _xfa_text = __w_pdfjs_require__(17);
1826
1827const DEFAULT_RANGE_CHUNK_SIZE = 65536;
1828const RENDERING_CANCELLED_TIMEOUT = 100;
1829const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
1830exports.DefaultCanvasFactory = DefaultCanvasFactory;
1831const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
1832exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
1833const DefaultStandardFontDataFactory = _is_node.isNodeJS ? _node_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory;
1834exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
1835let createPDFNetworkStream;
1836
1837function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
1838 createPDFNetworkStream = pdfNetworkStreamFactory;
1839}
1840
1841function getDocument(src) {
1842 const task = new PDFDocumentLoadingTask();
1843 let source;
1844
1845 if (typeof src === "string" || src instanceof URL) {
1846 source = {
1847 url: src
1848 };
1849 } else if ((0, _util.isArrayBuffer)(src)) {
1850 source = {
1851 data: src
1852 };
1853 } else if (src instanceof PDFDataRangeTransport) {
1854 source = {
1855 range: src
1856 };
1857 } else {
1858 if (typeof src !== "object") {
1859 throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
1860 }
1861
1862 if (!src.url && !src.data && !src.range) {
1863 throw new Error("Invalid parameter object: need either .data, .range or .url");
1864 }
1865
1866 source = src;
1867 }
1868
1869 const params = Object.create(null);
1870 let rangeTransport = null,
1871 worker = null;
1872
1873 for (const key in source) {
1874 const value = source[key];
1875
1876 switch (key) {
1877 case "url":
1878 if (typeof window !== "undefined") {
1879 try {
1880 params[key] = new URL(value, window.location).href;
1881 continue;
1882 } catch (ex) {
1883 (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
1884 }
1885 } else if (typeof value === "string" || value instanceof URL) {
1886 params[key] = value.toString();
1887 continue;
1888 }
1889
1890 throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
1891
1892 case "range":
1893 rangeTransport = value;
1894 continue;
1895
1896 case "worker":
1897 worker = value;
1898 continue;
1899
1900 case "data":
1901 if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
1902 params[key] = new Uint8Array(value);
1903 } else if (value instanceof Uint8Array) {
1904 break;
1905 } else if (typeof value === "string") {
1906 params[key] = (0, _util.stringToBytes)(value);
1907 } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
1908 params[key] = new Uint8Array(value);
1909 } else if ((0, _util.isArrayBuffer)(value)) {
1910 params[key] = new Uint8Array(value);
1911 } else {
1912 throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
1913 }
1914
1915 continue;
1916 }
1917
1918 params[key] = value;
1919 }
1920
1921 params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
1922 params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
1923 params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
1924 params.ignoreErrors = params.stopAtErrors !== true;
1925 params.fontExtraProperties = params.fontExtraProperties === true;
1926 params.pdfBug = params.pdfBug === true;
1927 params.enableXfa = params.enableXfa === true;
1928
1929 if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
1930 params.docBaseUrl = null;
1931 }
1932
1933 if (!Number.isInteger(params.maxImageSize)) {
1934 params.maxImageSize = -1;
1935 }
1936
1937 if (typeof params.useWorkerFetch !== "boolean") {
1938 params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
1939 }
1940
1941 if (typeof params.isEvalSupported !== "boolean") {
1942 params.isEvalSupported = true;
1943 }
1944
1945 if (typeof params.disableFontFace !== "boolean") {
1946 params.disableFontFace = _is_node.isNodeJS;
1947 }
1948
1949 if (typeof params.useSystemFonts !== "boolean") {
1950 params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
1951 }
1952
1953 if (typeof params.ownerDocument === "undefined") {
1954 params.ownerDocument = globalThis.document;
1955 }
1956
1957 if (typeof params.disableRange !== "boolean") {
1958 params.disableRange = false;
1959 }
1960
1961 if (typeof params.disableStream !== "boolean") {
1962 params.disableStream = false;
1963 }
1964
1965 if (typeof params.disableAutoFetch !== "boolean") {
1966 params.disableAutoFetch = false;
1967 }
1968
1969 (0, _util.setVerbosityLevel)(params.verbosity);
1970
1971 if (!worker) {
1972 const workerParams = {
1973 verbosity: params.verbosity,
1974 port: _worker_options.GlobalWorkerOptions.workerPort
1975 };
1976 worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
1977 task._worker = worker;
1978 }
1979
1980 const docId = task.docId;
1981 worker.promise.then(function () {
1982 if (task.destroyed) {
1983 throw new Error("Loading aborted");
1984 }
1985
1986 const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
1987
1988 const networkStreamPromise = new Promise(function (resolve) {
1989 let networkStream;
1990
1991 if (rangeTransport) {
1992 networkStream = new _transport_stream.PDFDataTransportStream({
1993 length: params.length,
1994 initialData: params.initialData,
1995 progressiveDone: params.progressiveDone,
1996 contentDispositionFilename: params.contentDispositionFilename,
1997 disableRange: params.disableRange,
1998 disableStream: params.disableStream
1999 }, rangeTransport);
2000 } else if (!params.data) {
2001 networkStream = createPDFNetworkStream({
2002 url: params.url,
2003 length: params.length,
2004 httpHeaders: params.httpHeaders,
2005 withCredentials: params.withCredentials,
2006 rangeChunkSize: params.rangeChunkSize,
2007 disableRange: params.disableRange,
2008 disableStream: params.disableStream
2009 });
2010 }
2011
2012 resolve(networkStream);
2013 });
2014 return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
2015 if (task.destroyed) {
2016 throw new Error("Loading aborted");
2017 }
2018
2019 const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
2020 const transport = new WorkerTransport(messageHandler, task, networkStream, params);
2021 task._transport = transport;
2022 messageHandler.send("Ready", null);
2023 });
2024 }).catch(task._capability.reject);
2025 return task;
2026}
2027
2028async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
2029 if (worker.destroyed) {
2030 throw new Error("Worker was destroyed");
2031 }
2032
2033 if (pdfDataRangeTransport) {
2034 source.length = pdfDataRangeTransport.length;
2035 source.initialData = pdfDataRangeTransport.initialData;
2036 source.progressiveDone = pdfDataRangeTransport.progressiveDone;
2037 source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
2038 }
2039
2040 const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
2041 docId,
2042 apiVersion: '2.12.313',
2043 source: {
2044 data: source.data,
2045 url: source.url,
2046 password: source.password,
2047 disableAutoFetch: source.disableAutoFetch,
2048 rangeChunkSize: source.rangeChunkSize,
2049 length: source.length
2050 },
2051 maxImageSize: source.maxImageSize,
2052 disableFontFace: source.disableFontFace,
2053 docBaseUrl: source.docBaseUrl,
2054 ignoreErrors: source.ignoreErrors,
2055 isEvalSupported: source.isEvalSupported,
2056 fontExtraProperties: source.fontExtraProperties,
2057 enableXfa: source.enableXfa,
2058 useSystemFonts: source.useSystemFonts,
2059 cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
2060 standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
2061 });
2062
2063 if (worker.destroyed) {
2064 throw new Error("Worker was destroyed");
2065 }
2066
2067 return workerId;
2068}
2069
2070class PDFDocumentLoadingTask {
2071 static get idCounters() {
2072 return (0, _util.shadow)(this, "idCounters", {
2073 doc: 0
2074 });
2075 }
2076
2077 constructor() {
2078 this._capability = (0, _util.createPromiseCapability)();
2079 this._transport = null;
2080 this._worker = null;
2081 this.docId = `d${PDFDocumentLoadingTask.idCounters.doc++}`;
2082 this.destroyed = false;
2083 this.onPassword = null;
2084 this.onProgress = null;
2085 this.onUnsupportedFeature = null;
2086 }
2087
2088 get promise() {
2089 return this._capability.promise;
2090 }
2091
2092 async destroy() {
2093 this.destroyed = true;
2094 await this._transport?.destroy();
2095 this._transport = null;
2096
2097 if (this._worker) {
2098 this._worker.destroy();
2099
2100 this._worker = null;
2101 }
2102 }
2103
2104}
2105
2106exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
2107
2108class PDFDataRangeTransport {
2109 constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
2110 this.length = length;
2111 this.initialData = initialData;
2112 this.progressiveDone = progressiveDone;
2113 this.contentDispositionFilename = contentDispositionFilename;
2114 this._rangeListeners = [];
2115 this._progressListeners = [];
2116 this._progressiveReadListeners = [];
2117 this._progressiveDoneListeners = [];
2118 this._readyCapability = (0, _util.createPromiseCapability)();
2119 }
2120
2121 addRangeListener(listener) {
2122 this._rangeListeners.push(listener);
2123 }
2124
2125 addProgressListener(listener) {
2126 this._progressListeners.push(listener);
2127 }
2128
2129 addProgressiveReadListener(listener) {
2130 this._progressiveReadListeners.push(listener);
2131 }
2132
2133 addProgressiveDoneListener(listener) {
2134 this._progressiveDoneListeners.push(listener);
2135 }
2136
2137 onDataRange(begin, chunk) {
2138 for (const listener of this._rangeListeners) {
2139 listener(begin, chunk);
2140 }
2141 }
2142
2143 onDataProgress(loaded, total) {
2144 this._readyCapability.promise.then(() => {
2145 for (const listener of this._progressListeners) {
2146 listener(loaded, total);
2147 }
2148 });
2149 }
2150
2151 onDataProgressiveRead(chunk) {
2152 this._readyCapability.promise.then(() => {
2153 for (const listener of this._progressiveReadListeners) {
2154 listener(chunk);
2155 }
2156 });
2157 }
2158
2159 onDataProgressiveDone() {
2160 this._readyCapability.promise.then(() => {
2161 for (const listener of this._progressiveDoneListeners) {
2162 listener();
2163 }
2164 });
2165 }
2166
2167 transportReady() {
2168 this._readyCapability.resolve();
2169 }
2170
2171 requestDataRange(begin, end) {
2172 (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
2173 }
2174
2175 abort() {}
2176
2177}
2178
2179exports.PDFDataRangeTransport = PDFDataRangeTransport;
2180
2181class PDFDocumentProxy {
2182 constructor(pdfInfo, transport) {
2183 this._pdfInfo = pdfInfo;
2184 this._transport = transport;
2185 Object.defineProperty(this, "fingerprint", {
2186 get() {
2187 (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
2188 return this.fingerprints[0];
2189 }
2190
2191 });
2192 Object.defineProperty(this, "getStats", {
2193 value: async () => {
2194 (0, _display_utils.deprecated)("`PDFDocumentProxy.getStats`, " + "please use the `PDFDocumentProxy.stats`-getter instead.");
2195 return this.stats || {
2196 streamTypes: {},
2197 fontTypes: {}
2198 };
2199 }
2200 });
2201 }
2202
2203 get annotationStorage() {
2204 return this._transport.annotationStorage;
2205 }
2206
2207 get numPages() {
2208 return this._pdfInfo.numPages;
2209 }
2210
2211 get fingerprints() {
2212 return this._pdfInfo.fingerprints;
2213 }
2214
2215 get stats() {
2216 return this._transport.stats;
2217 }
2218
2219 get isPureXfa() {
2220 return !!this._transport._htmlForXfa;
2221 }
2222
2223 get allXfaHtml() {
2224 return this._transport._htmlForXfa;
2225 }
2226
2227 getPage(pageNumber) {
2228 return this._transport.getPage(pageNumber);
2229 }
2230
2231 getPageIndex(ref) {
2232 return this._transport.getPageIndex(ref);
2233 }
2234
2235 getDestinations() {
2236 return this._transport.getDestinations();
2237 }
2238
2239 getDestination(id) {
2240 return this._transport.getDestination(id);
2241 }
2242
2243 getPageLabels() {
2244 return this._transport.getPageLabels();
2245 }
2246
2247 getPageLayout() {
2248 return this._transport.getPageLayout();
2249 }
2250
2251 getPageMode() {
2252 return this._transport.getPageMode();
2253 }
2254
2255 getViewerPreferences() {
2256 return this._transport.getViewerPreferences();
2257 }
2258
2259 getOpenAction() {
2260 return this._transport.getOpenAction();
2261 }
2262
2263 getAttachments() {
2264 return this._transport.getAttachments();
2265 }
2266
2267 getJavaScript() {
2268 return this._transport.getJavaScript();
2269 }
2270
2271 getJSActions() {
2272 return this._transport.getDocJSActions();
2273 }
2274
2275 getOutline() {
2276 return this._transport.getOutline();
2277 }
2278
2279 getOptionalContentConfig() {
2280 return this._transport.getOptionalContentConfig();
2281 }
2282
2283 getPermissions() {
2284 return this._transport.getPermissions();
2285 }
2286
2287 getMetadata() {
2288 return this._transport.getMetadata();
2289 }
2290
2291 getMarkInfo() {
2292 return this._transport.getMarkInfo();
2293 }
2294
2295 getData() {
2296 return this._transport.getData();
2297 }
2298
2299 getDownloadInfo() {
2300 return this._transport.downloadInfoCapability.promise;
2301 }
2302
2303 cleanup(keepLoadedFonts = false) {
2304 return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
2305 }
2306
2307 destroy() {
2308 return this.loadingTask.destroy();
2309 }
2310
2311 get loadingParams() {
2312 return this._transport.loadingParams;
2313 }
2314
2315 get loadingTask() {
2316 return this._transport.loadingTask;
2317 }
2318
2319 saveDocument() {
2320 if (this._transport.annotationStorage.size <= 0) {
2321 (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
2322 }
2323
2324 return this._transport.saveDocument();
2325 }
2326
2327 getFieldObjects() {
2328 return this._transport.getFieldObjects();
2329 }
2330
2331 hasJSActions() {
2332 return this._transport.hasJSActions();
2333 }
2334
2335 getCalculationOrderIds() {
2336 return this._transport.getCalculationOrderIds();
2337 }
2338
2339}
2340
2341exports.PDFDocumentProxy = PDFDocumentProxy;
2342
2343class PDFPageProxy {
2344 constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
2345 this._pageIndex = pageIndex;
2346 this._pageInfo = pageInfo;
2347 this._ownerDocument = ownerDocument;
2348 this._transport = transport;
2349 this._stats = pdfBug ? new _display_utils.StatTimer() : null;
2350 this._pdfBug = pdfBug;
2351 this.commonObjs = transport.commonObjs;
2352 this.objs = new PDFObjects();
2353 this.cleanupAfterRender = false;
2354 this.pendingCleanup = false;
2355 this._intentStates = new Map();
2356 this._annotationPromises = new Map();
2357 this.destroyed = false;
2358 }
2359
2360 get pageNumber() {
2361 return this._pageIndex + 1;
2362 }
2363
2364 get rotate() {
2365 return this._pageInfo.rotate;
2366 }
2367
2368 get ref() {
2369 return this._pageInfo.ref;
2370 }
2371
2372 get userUnit() {
2373 return this._pageInfo.userUnit;
2374 }
2375
2376 get view() {
2377 return this._pageInfo.view;
2378 }
2379
2380 getViewport({
2381 scale,
2382 rotation = this.rotate,
2383 offsetX = 0,
2384 offsetY = 0,
2385 dontFlip = false
2386 } = {}) {
2387 return new _display_utils.PageViewport({
2388 viewBox: this.view,
2389 scale,
2390 rotation,
2391 offsetX,
2392 offsetY,
2393 dontFlip
2394 });
2395 }
2396
2397 getAnnotations({
2398 intent = "display"
2399 } = {}) {
2400 const intentArgs = this._transport.getRenderingIntent(intent);
2401
2402 let promise = this._annotationPromises.get(intentArgs.cacheKey);
2403
2404 if (!promise) {
2405 promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
2406
2407 this._annotationPromises.set(intentArgs.cacheKey, promise);
2408
2409 promise = promise.then(annotations => {
2410 for (const annotation of annotations) {
2411 if (annotation.titleObj !== undefined) {
2412 Object.defineProperty(annotation, "title", {
2413 get() {
2414 (0, _display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead.");
2415 return annotation.titleObj.str;
2416 }
2417
2418 });
2419 }
2420
2421 if (annotation.contentsObj !== undefined) {
2422 Object.defineProperty(annotation, "contents", {
2423 get() {
2424 (0, _display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead.");
2425 return annotation.contentsObj.str;
2426 }
2427
2428 });
2429 }
2430 }
2431
2432 return annotations;
2433 });
2434 }
2435
2436 return promise;
2437 }
2438
2439 getJSActions() {
2440 return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
2441 }
2442
2443 async getXfa() {
2444 return this._transport._htmlForXfa?.children[this._pageIndex] || null;
2445 }
2446
2447 render({
2448 canvasContext,
2449 viewport,
2450 intent = "display",
2451 annotationMode = _util.AnnotationMode.ENABLE,
2452 transform = null,
2453 imageLayer = null,
2454 canvasFactory = null,
2455 background = null,
2456 optionalContentConfigPromise = null,
2457 annotationCanvasMap = null
2458 }) {
2459 if (arguments[0]?.renderInteractiveForms !== undefined) {
2460 (0, _display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, " + "please use the `annotationMode`-option instead.");
2461
2462 if (arguments[0].renderInteractiveForms === true && annotationMode === _util.AnnotationMode.ENABLE) {
2463 annotationMode = _util.AnnotationMode.ENABLE_FORMS;
2464 }
2465 }
2466
2467 if (arguments[0]?.includeAnnotationStorage !== undefined) {
2468 (0, _display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, " + "please use the `annotationMode`-option instead.");
2469
2470 if (arguments[0].includeAnnotationStorage === true && annotationMode === _util.AnnotationMode.ENABLE) {
2471 annotationMode = _util.AnnotationMode.ENABLE_STORAGE;
2472 }
2473 }
2474
2475 if (this._stats) {
2476 this._stats.time("Overall");
2477 }
2478
2479 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode);
2480
2481 this.pendingCleanup = false;
2482
2483 if (!optionalContentConfigPromise) {
2484 optionalContentConfigPromise = this._transport.getOptionalContentConfig();
2485 }
2486
2487 let intentState = this._intentStates.get(intentArgs.cacheKey);
2488
2489 if (!intentState) {
2490 intentState = Object.create(null);
2491
2492 this._intentStates.set(intentArgs.cacheKey, intentState);
2493 }
2494
2495 if (intentState.streamReaderCancelTimeout) {
2496 clearTimeout(intentState.streamReaderCancelTimeout);
2497 intentState.streamReaderCancelTimeout = null;
2498 }
2499
2500 const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
2501 ownerDocument: this._ownerDocument
2502 });
2503 const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
2504
2505 if (!intentState.displayReadyCapability) {
2506 intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
2507 intentState.operatorList = {
2508 fnArray: [],
2509 argsArray: [],
2510 lastChunk: false
2511 };
2512
2513 if (this._stats) {
2514 this._stats.time("Page Request");
2515 }
2516
2517 this._pumpOperatorList(intentArgs);
2518 }
2519
2520 const complete = error => {
2521 intentState.renderTasks.delete(internalRenderTask);
2522
2523 if (this.cleanupAfterRender || intentPrint) {
2524 this.pendingCleanup = true;
2525 }
2526
2527 this._tryCleanup();
2528
2529 if (error) {
2530 internalRenderTask.capability.reject(error);
2531
2532 this._abortOperatorList({
2533 intentState,
2534 reason: error instanceof Error ? error : new Error(error)
2535 });
2536 } else {
2537 internalRenderTask.capability.resolve();
2538 }
2539
2540 if (this._stats) {
2541 this._stats.timeEnd("Rendering");
2542
2543 this._stats.timeEnd("Overall");
2544 }
2545 };
2546
2547 const internalRenderTask = new InternalRenderTask({
2548 callback: complete,
2549 params: {
2550 canvasContext,
2551 viewport,
2552 transform,
2553 imageLayer,
2554 background
2555 },
2556 objs: this.objs,
2557 commonObjs: this.commonObjs,
2558 annotationCanvasMap,
2559 operatorList: intentState.operatorList,
2560 pageIndex: this._pageIndex,
2561 canvasFactory: canvasFactoryInstance,
2562 useRequestAnimationFrame: !intentPrint,
2563 pdfBug: this._pdfBug
2564 });
2565 (intentState.renderTasks ||= new Set()).add(internalRenderTask);
2566 const renderTask = internalRenderTask.task;
2567 Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
2568 if (this.pendingCleanup) {
2569 complete();
2570 return;
2571 }
2572
2573 if (this._stats) {
2574 this._stats.time("Rendering");
2575 }
2576
2577 internalRenderTask.initializeGraphics({
2578 transparency,
2579 optionalContentConfig
2580 });
2581 internalRenderTask.operatorListChanged();
2582 }).catch(complete);
2583 return renderTask;
2584 }
2585
2586 getOperatorList({
2587 intent = "display",
2588 annotationMode = _util.AnnotationMode.ENABLE
2589 } = {}) {
2590 function operatorListChanged() {
2591 if (intentState.operatorList.lastChunk) {
2592 intentState.opListReadCapability.resolve(intentState.operatorList);
2593 intentState.renderTasks.delete(opListTask);
2594 }
2595 }
2596
2597 const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, true);
2598
2599 let intentState = this._intentStates.get(intentArgs.cacheKey);
2600
2601 if (!intentState) {
2602 intentState = Object.create(null);
2603
2604 this._intentStates.set(intentArgs.cacheKey, intentState);
2605 }
2606
2607 let opListTask;
2608
2609 if (!intentState.opListReadCapability) {
2610 opListTask = Object.create(null);
2611 opListTask.operatorListChanged = operatorListChanged;
2612 intentState.opListReadCapability = (0, _util.createPromiseCapability)();
2613 (intentState.renderTasks ||= new Set()).add(opListTask);
2614 intentState.operatorList = {
2615 fnArray: [],
2616 argsArray: [],
2617 lastChunk: false
2618 };
2619
2620 if (this._stats) {
2621 this._stats.time("Page Request");
2622 }
2623
2624 this._pumpOperatorList(intentArgs);
2625 }
2626
2627 return intentState.opListReadCapability.promise;
2628 }
2629
2630 streamTextContent({
2631 normalizeWhitespace = false,
2632 disableCombineTextItems = false,
2633 includeMarkedContent = false
2634 } = {}) {
2635 const TEXT_CONTENT_CHUNK_SIZE = 100;
2636 return this._transport.messageHandler.sendWithStream("GetTextContent", {
2637 pageIndex: this._pageIndex,
2638 normalizeWhitespace: normalizeWhitespace === true,
2639 combineTextItems: disableCombineTextItems !== true,
2640 includeMarkedContent: includeMarkedContent === true
2641 }, {
2642 highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
2643
2644 size(textContent) {
2645 return textContent.items.length;
2646 }
2647
2648 });
2649 }
2650
2651 getTextContent(params = {}) {
2652 if (this._transport._htmlForXfa) {
2653 return this.getXfa().then(xfa => {
2654 return _xfa_text.XfaText.textContent(xfa);
2655 });
2656 }
2657
2658 const readableStream = this.streamTextContent(params);
2659 return new Promise(function (resolve, reject) {
2660 function pump() {
2661 reader.read().then(function ({
2662 value,
2663 done
2664 }) {
2665 if (done) {
2666 resolve(textContent);
2667 return;
2668 }
2669
2670 Object.assign(textContent.styles, value.styles);
2671 textContent.items.push(...value.items);
2672 pump();
2673 }, reject);
2674 }
2675
2676 const reader = readableStream.getReader();
2677 const textContent = {
2678 items: [],
2679 styles: Object.create(null)
2680 };
2681 pump();
2682 });
2683 }
2684
2685 getStructTree() {
2686 return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
2687 }
2688
2689 _destroy() {
2690 this.destroyed = true;
2691 const waitOn = [];
2692
2693 for (const intentState of this._intentStates.values()) {
2694 this._abortOperatorList({
2695 intentState,
2696 reason: new Error("Page was destroyed."),
2697 force: true
2698 });
2699
2700 if (intentState.opListReadCapability) {
2701 continue;
2702 }
2703
2704 for (const internalRenderTask of intentState.renderTasks) {
2705 waitOn.push(internalRenderTask.completed);
2706 internalRenderTask.cancel();
2707 }
2708 }
2709
2710 this.objs.clear();
2711
2712 this._annotationPromises.clear();
2713
2714 this._jsActionsPromise = null;
2715 this._structTreePromise = null;
2716 this.pendingCleanup = false;
2717 return Promise.all(waitOn);
2718 }
2719
2720 cleanup(resetStats = false) {
2721 this.pendingCleanup = true;
2722 return this._tryCleanup(resetStats);
2723 }
2724
2725 _tryCleanup(resetStats = false) {
2726 if (!this.pendingCleanup) {
2727 return false;
2728 }
2729
2730 for (const {
2731 renderTasks,
2732 operatorList
2733 } of this._intentStates.values()) {
2734 if (renderTasks.size > 0 || !operatorList.lastChunk) {
2735 return false;
2736 }
2737 }
2738
2739 this._intentStates.clear();
2740
2741 this.objs.clear();
2742
2743 this._annotationPromises.clear();
2744
2745 this._jsActionsPromise = null;
2746 this._structTreePromise = null;
2747
2748 if (resetStats && this._stats) {
2749 this._stats = new _display_utils.StatTimer();
2750 }
2751
2752 this.pendingCleanup = false;
2753 return true;
2754 }
2755
2756 _startRenderPage(transparency, cacheKey) {
2757 const intentState = this._intentStates.get(cacheKey);
2758
2759 if (!intentState) {
2760 return;
2761 }
2762
2763 if (this._stats) {
2764 this._stats.timeEnd("Page Request");
2765 }
2766
2767 if (intentState.displayReadyCapability) {
2768 intentState.displayReadyCapability.resolve(transparency);
2769 }
2770 }
2771
2772 _renderPageChunk(operatorListChunk, intentState) {
2773 for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
2774 intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
2775 intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
2776 }
2777
2778 intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
2779
2780 for (const internalRenderTask of intentState.renderTasks) {
2781 internalRenderTask.operatorListChanged();
2782 }
2783
2784 if (operatorListChunk.lastChunk) {
2785 this._tryCleanup();
2786 }
2787 }
2788
2789 _pumpOperatorList({
2790 renderingIntent,
2791 cacheKey
2792 }) {
2793 const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
2794 pageIndex: this._pageIndex,
2795 intent: renderingIntent,
2796 cacheKey,
2797 annotationStorage: renderingIntent & _util.RenderingIntentFlag.ANNOTATIONS_STORAGE ? this._transport.annotationStorage.serializable : null
2798 });
2799
2800 const reader = readableStream.getReader();
2801
2802 const intentState = this._intentStates.get(cacheKey);
2803
2804 intentState.streamReader = reader;
2805
2806 const pump = () => {
2807 reader.read().then(({
2808 value,
2809 done
2810 }) => {
2811 if (done) {
2812 intentState.streamReader = null;
2813 return;
2814 }
2815
2816 if (this._transport.destroyed) {
2817 return;
2818 }
2819
2820 this._renderPageChunk(value, intentState);
2821
2822 pump();
2823 }, reason => {
2824 intentState.streamReader = null;
2825
2826 if (this._transport.destroyed) {
2827 return;
2828 }
2829
2830 if (intentState.operatorList) {
2831 intentState.operatorList.lastChunk = true;
2832
2833 for (const internalRenderTask of intentState.renderTasks) {
2834 internalRenderTask.operatorListChanged();
2835 }
2836
2837 this._tryCleanup();
2838 }
2839
2840 if (intentState.displayReadyCapability) {
2841 intentState.displayReadyCapability.reject(reason);
2842 } else if (intentState.opListReadCapability) {
2843 intentState.opListReadCapability.reject(reason);
2844 } else {
2845 throw reason;
2846 }
2847 });
2848 };
2849
2850 pump();
2851 }
2852
2853 _abortOperatorList({
2854 intentState,
2855 reason,
2856 force = false
2857 }) {
2858 if (!intentState.streamReader) {
2859 return;
2860 }
2861
2862 if (!force) {
2863 if (intentState.renderTasks.size > 0) {
2864 return;
2865 }
2866
2867 if (reason instanceof _display_utils.RenderingCancelledException) {
2868 intentState.streamReaderCancelTimeout = setTimeout(() => {
2869 this._abortOperatorList({
2870 intentState,
2871 reason,
2872 force: true
2873 });
2874
2875 intentState.streamReaderCancelTimeout = null;
2876 }, RENDERING_CANCELLED_TIMEOUT);
2877 return;
2878 }
2879 }
2880
2881 intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
2882 intentState.streamReader = null;
2883
2884 if (this._transport.destroyed) {
2885 return;
2886 }
2887
2888 for (const [curCacheKey, curIntentState] of this._intentStates) {
2889 if (curIntentState === intentState) {
2890 this._intentStates.delete(curCacheKey);
2891
2892 break;
2893 }
2894 }
2895
2896 this.cleanup();
2897 }
2898
2899 get stats() {
2900 return this._stats;
2901 }
2902
2903}
2904
2905exports.PDFPageProxy = PDFPageProxy;
2906
2907class LoopbackPort {
2908 constructor() {
2909 this._listeners = [];
2910 this._deferred = Promise.resolve();
2911 }
2912
2913 postMessage(obj, transfers) {
2914 function cloneValue(object) {
2915 if (globalThis.structuredClone) {
2916 return globalThis.structuredClone(object, transfers);
2917 }
2918
2919 function fallbackCloneValue(value) {
2920 if (typeof value === "function" || typeof value === "symbol" || value instanceof URL) {
2921 throw new Error(`LoopbackPort.postMessage - cannot clone: ${value?.toString()}`);
2922 }
2923
2924 if (typeof value !== "object" || value === null) {
2925 return value;
2926 }
2927
2928 if (cloned.has(value)) {
2929 return cloned.get(value);
2930 }
2931
2932 let buffer, result;
2933
2934 if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
2935 if (transfers?.includes(buffer)) {
2936 result = new value.constructor(buffer, value.byteOffset, value.byteLength);
2937 } else {
2938 result = new value.constructor(value);
2939 }
2940
2941 cloned.set(value, result);
2942 return result;
2943 }
2944
2945 if (value instanceof Map) {
2946 result = new Map();
2947 cloned.set(value, result);
2948
2949 for (const [key, val] of value) {
2950 result.set(key, fallbackCloneValue(val));
2951 }
2952
2953 return result;
2954 }
2955
2956 if (value instanceof Set) {
2957 result = new Set();
2958 cloned.set(value, result);
2959
2960 for (const val of value) {
2961 result.add(fallbackCloneValue(val));
2962 }
2963
2964 return result;
2965 }
2966
2967 result = Array.isArray(value) ? [] : Object.create(null);
2968 cloned.set(value, result);
2969
2970 for (const i in value) {
2971 let desc,
2972 p = value;
2973
2974 while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
2975 p = Object.getPrototypeOf(p);
2976 }
2977
2978 if (typeof desc.value === "undefined") {
2979 continue;
2980 }
2981
2982 if (typeof desc.value === "function" && !value.hasOwnProperty?.(i)) {
2983 continue;
2984 }
2985
2986 result[i] = fallbackCloneValue(desc.value);
2987 }
2988
2989 return result;
2990 }
2991
2992 const cloned = new WeakMap();
2993 return fallbackCloneValue(object);
2994 }
2995
2996 const event = {
2997 data: cloneValue(obj)
2998 };
2999
3000 this._deferred.then(() => {
3001 for (const listener of this._listeners) {
3002 listener.call(this, event);
3003 }
3004 });
3005 }
3006
3007 addEventListener(name, listener) {
3008 this._listeners.push(listener);
3009 }
3010
3011 removeEventListener(name, listener) {
3012 const i = this._listeners.indexOf(listener);
3013
3014 this._listeners.splice(i, 1);
3015 }
3016
3017 terminate() {
3018 this._listeners.length = 0;
3019 }
3020
3021}
3022
3023exports.LoopbackPort = LoopbackPort;
3024const PDFWorkerUtil = {
3025 isWorkerDisabled: false,
3026 fallbackWorkerSrc: null,
3027 fakeWorkerId: 0
3028};
3029{
3030 if (_is_node.isNodeJS && typeof require === "function") {
3031 PDFWorkerUtil.isWorkerDisabled = true;
3032 PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
3033 } else if (typeof document === "object") {
3034 const pdfjsFilePath = document?.currentScript?.src;
3035
3036 if (pdfjsFilePath) {
3037 PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
3038 }
3039 }
3040
3041 PDFWorkerUtil.createCDNWrapper = function (url) {
3042 const wrapper = `importScripts("${url}");`;
3043 return URL.createObjectURL(new Blob([wrapper]));
3044 };
3045}
3046
3047class PDFWorker {
3048 static get _workerPorts() {
3049 return (0, _util.shadow)(this, "_workerPorts", new WeakMap());
3050 }
3051
3052 constructor({
3053 name = null,
3054 port = null,
3055 verbosity = (0, _util.getVerbosityLevel)()
3056 } = {}) {
3057 if (port && PDFWorker._workerPorts.has(port)) {
3058 throw new Error("Cannot use more than one PDFWorker per port.");
3059 }
3060
3061 this.name = name;
3062 this.destroyed = false;
3063 this.verbosity = verbosity;
3064 this._readyCapability = (0, _util.createPromiseCapability)();
3065 this._port = null;
3066 this._webWorker = null;
3067 this._messageHandler = null;
3068
3069 if (port) {
3070 PDFWorker._workerPorts.set(port, this);
3071
3072 this._initializeFromPort(port);
3073
3074 return;
3075 }
3076
3077 this._initialize();
3078 }
3079
3080 get promise() {
3081 return this._readyCapability.promise;
3082 }
3083
3084 get port() {
3085 return this._port;
3086 }
3087
3088 get messageHandler() {
3089 return this._messageHandler;
3090 }
3091
3092 _initializeFromPort(port) {
3093 this._port = port;
3094 this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
3095
3096 this._messageHandler.on("ready", function () {});
3097
3098 this._readyCapability.resolve();
3099 }
3100
3101 _initialize() {
3102 if (typeof Worker !== "undefined" && !PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
3103 let workerSrc = PDFWorker.workerSrc;
3104
3105 try {
3106 if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
3107 workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
3108 }
3109
3110 const worker = new Worker(workerSrc);
3111 const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
3112
3113 const terminateEarly = () => {
3114 worker.removeEventListener("error", onWorkerError);
3115 messageHandler.destroy();
3116 worker.terminate();
3117
3118 if (this.destroyed) {
3119 this._readyCapability.reject(new Error("Worker was destroyed"));
3120 } else {
3121 this._setupFakeWorker();
3122 }
3123 };
3124
3125 const onWorkerError = () => {
3126 if (!this._webWorker) {
3127 terminateEarly();
3128 }
3129 };
3130
3131 worker.addEventListener("error", onWorkerError);
3132 messageHandler.on("test", data => {
3133 worker.removeEventListener("error", onWorkerError);
3134
3135 if (this.destroyed) {
3136 terminateEarly();
3137 return;
3138 }
3139
3140 if (data) {
3141 this._messageHandler = messageHandler;
3142 this._port = worker;
3143 this._webWorker = worker;
3144
3145 this._readyCapability.resolve();
3146
3147 messageHandler.send("configure", {
3148 verbosity: this.verbosity
3149 });
3150 } else {
3151 this._setupFakeWorker();
3152
3153 messageHandler.destroy();
3154 worker.terminate();
3155 }
3156 });
3157 messageHandler.on("ready", data => {
3158 worker.removeEventListener("error", onWorkerError);
3159
3160 if (this.destroyed) {
3161 terminateEarly();
3162 return;
3163 }
3164
3165 try {
3166 sendTest();
3167 } catch (e) {
3168 this._setupFakeWorker();
3169 }
3170 });
3171
3172 const sendTest = () => {
3173 const testObj = new Uint8Array([255]);
3174
3175 try {
3176 messageHandler.send("test", testObj, [testObj.buffer]);
3177 } catch (ex) {
3178 (0, _util.warn)("Cannot use postMessage transfers.");
3179 testObj[0] = 0;
3180 messageHandler.send("test", testObj);
3181 }
3182 };
3183
3184 sendTest();
3185 return;
3186 } catch (e) {
3187 (0, _util.info)("The worker has been disabled.");
3188 }
3189 }
3190
3191 this._setupFakeWorker();
3192 }
3193
3194 _setupFakeWorker() {
3195 if (!PDFWorkerUtil.isWorkerDisabled) {
3196 (0, _util.warn)("Setting up fake worker.");
3197 PDFWorkerUtil.isWorkerDisabled = true;
3198 }
3199
3200 PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
3201 if (this.destroyed) {
3202 this._readyCapability.reject(new Error("Worker was destroyed"));
3203
3204 return;
3205 }
3206
3207 const port = new LoopbackPort();
3208 this._port = port;
3209 const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
3210 const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
3211 WorkerMessageHandler.setup(workerHandler, port);
3212 const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
3213 this._messageHandler = messageHandler;
3214
3215 this._readyCapability.resolve();
3216
3217 messageHandler.send("configure", {
3218 verbosity: this.verbosity
3219 });
3220 }).catch(reason => {
3221 this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
3222 });
3223 }
3224
3225 destroy() {
3226 this.destroyed = true;
3227
3228 if (this._webWorker) {
3229 this._webWorker.terminate();
3230
3231 this._webWorker = null;
3232 }
3233
3234 PDFWorker._workerPorts.delete(this._port);
3235
3236 this._port = null;
3237
3238 if (this._messageHandler) {
3239 this._messageHandler.destroy();
3240
3241 this._messageHandler = null;
3242 }
3243 }
3244
3245 static fromPort(params) {
3246 if (!params?.port) {
3247 throw new Error("PDFWorker.fromPort - invalid method signature.");
3248 }
3249
3250 if (this._workerPorts.has(params.port)) {
3251 return this._workerPorts.get(params.port);
3252 }
3253
3254 return new PDFWorker(params);
3255 }
3256
3257 static get workerSrc() {
3258 if (_worker_options.GlobalWorkerOptions.workerSrc) {
3259 return _worker_options.GlobalWorkerOptions.workerSrc;
3260 }
3261
3262 if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
3263 if (!_is_node.isNodeJS) {
3264 (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
3265 }
3266
3267 return PDFWorkerUtil.fallbackWorkerSrc;
3268 }
3269
3270 throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
3271 }
3272
3273 static get _mainThreadWorkerMessageHandler() {
3274 try {
3275 return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
3276 } catch (ex) {
3277 return null;
3278 }
3279 }
3280
3281 static get _setupFakeWorkerGlobal() {
3282 const loader = async () => {
3283 const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
3284
3285 if (mainWorkerMessageHandler) {
3286 return mainWorkerMessageHandler;
3287 }
3288
3289 if (_is_node.isNodeJS && typeof require === "function") {
3290 const worker = eval("require")(this.workerSrc);
3291 return worker.WorkerMessageHandler;
3292 }
3293
3294 await (0, _display_utils.loadScript)(this.workerSrc);
3295 return window.pdfjsWorker.WorkerMessageHandler;
3296 };
3297
3298 return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
3299 }
3300
3301}
3302
3303exports.PDFWorker = PDFWorker;
3304{
3305 PDFWorker.getWorkerSrc = function () {
3306 (0, _display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead.");
3307 return this.workerSrc;
3308 };
3309}
3310
3311class WorkerTransport {
3312 #docStats = null;
3313 #pageCache = new Map();
3314 #pagePromises = new Map();
3315 #metadataPromise = null;
3316
3317 constructor(messageHandler, loadingTask, networkStream, params) {
3318 this.messageHandler = messageHandler;
3319 this.loadingTask = loadingTask;
3320 this.commonObjs = new PDFObjects();
3321 this.fontLoader = new _font_loader.FontLoader({
3322 docId: loadingTask.docId,
3323 onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
3324 ownerDocument: params.ownerDocument,
3325 styleElement: params.styleElement
3326 });
3327 this._params = params;
3328
3329 if (!params.useWorkerFetch) {
3330 this.CMapReaderFactory = new params.CMapReaderFactory({
3331 baseUrl: params.cMapUrl,
3332 isCompressed: params.cMapPacked
3333 });
3334 this.StandardFontDataFactory = new params.StandardFontDataFactory({
3335 baseUrl: params.standardFontDataUrl
3336 });
3337 }
3338
3339 this.destroyed = false;
3340 this.destroyCapability = null;
3341 this._passwordCapability = null;
3342 this._networkStream = networkStream;
3343 this._fullReader = null;
3344 this._lastProgress = null;
3345 this.downloadInfoCapability = (0, _util.createPromiseCapability)();
3346 this.setupMessageHandler();
3347 }
3348
3349 get annotationStorage() {
3350 return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
3351 }
3352
3353 get stats() {
3354 return this.#docStats;
3355 }
3356
3357 getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, isOpList = false) {
3358 let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
3359 let lastModified = "";
3360
3361 switch (intent) {
3362 case "any":
3363 renderingIntent = _util.RenderingIntentFlag.ANY;
3364 break;
3365
3366 case "display":
3367 break;
3368
3369 case "print":
3370 renderingIntent = _util.RenderingIntentFlag.PRINT;
3371 break;
3372
3373 default:
3374 (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
3375 }
3376
3377 switch (annotationMode) {
3378 case _util.AnnotationMode.DISABLE:
3379 renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
3380 break;
3381
3382 case _util.AnnotationMode.ENABLE:
3383 break;
3384
3385 case _util.AnnotationMode.ENABLE_FORMS:
3386 renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
3387 break;
3388
3389 case _util.AnnotationMode.ENABLE_STORAGE:
3390 renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
3391 lastModified = this.annotationStorage.lastModified;
3392 break;
3393
3394 default:
3395 (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
3396 }
3397
3398 if (isOpList) {
3399 renderingIntent += _util.RenderingIntentFlag.OPLIST;
3400 }
3401
3402 return {
3403 renderingIntent,
3404 cacheKey: `${renderingIntent}_${lastModified}`
3405 };
3406 }
3407
3408 destroy() {
3409 if (this.destroyCapability) {
3410 return this.destroyCapability.promise;
3411 }
3412
3413 this.destroyed = true;
3414 this.destroyCapability = (0, _util.createPromiseCapability)();
3415
3416 if (this._passwordCapability) {
3417 this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
3418 }
3419
3420 const waitOn = [];
3421
3422 for (const page of this.#pageCache.values()) {
3423 waitOn.push(page._destroy());
3424 }
3425
3426 this.#pageCache.clear();
3427 this.#pagePromises.clear();
3428
3429 if (this.hasOwnProperty("annotationStorage")) {
3430 this.annotationStorage.resetModified();
3431 }
3432
3433 const terminated = this.messageHandler.sendWithPromise("Terminate", null);
3434 waitOn.push(terminated);
3435 Promise.all(waitOn).then(() => {
3436 this.commonObjs.clear();
3437 this.fontLoader.clear();
3438 this.#metadataPromise = null;
3439 this._getFieldObjectsPromise = null;
3440 this._hasJSActionsPromise = null;
3441
3442 if (this._networkStream) {
3443 this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
3444 }
3445
3446 if (this.messageHandler) {
3447 this.messageHandler.destroy();
3448 this.messageHandler = null;
3449 }
3450
3451 this.destroyCapability.resolve();
3452 }, this.destroyCapability.reject);
3453 return this.destroyCapability.promise;
3454 }
3455
3456 setupMessageHandler() {
3457 const {
3458 messageHandler,
3459 loadingTask
3460 } = this;
3461 messageHandler.on("GetReader", (data, sink) => {
3462 (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
3463 this._fullReader = this._networkStream.getFullReader();
3464
3465 this._fullReader.onProgress = evt => {
3466 this._lastProgress = {
3467 loaded: evt.loaded,
3468 total: evt.total
3469 };
3470 };
3471
3472 sink.onPull = () => {
3473 this._fullReader.read().then(function ({
3474 value,
3475 done
3476 }) {
3477 if (done) {
3478 sink.close();
3479 return;
3480 }
3481
3482 (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
3483 sink.enqueue(new Uint8Array(value), 1, [value]);
3484 }).catch(reason => {
3485 sink.error(reason);
3486 });
3487 };
3488
3489 sink.onCancel = reason => {
3490 this._fullReader.cancel(reason);
3491
3492 sink.ready.catch(readyReason => {
3493 if (this.destroyed) {
3494 return;
3495 }
3496
3497 throw readyReason;
3498 });
3499 };
3500 });
3501 messageHandler.on("ReaderHeadersReady", data => {
3502 const headersCapability = (0, _util.createPromiseCapability)();
3503 const fullReader = this._fullReader;
3504 fullReader.headersReady.then(() => {
3505 if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
3506 if (this._lastProgress) {
3507 loadingTask.onProgress?.(this._lastProgress);
3508 }
3509
3510 fullReader.onProgress = evt => {
3511 loadingTask.onProgress?.({
3512 loaded: evt.loaded,
3513 total: evt.total
3514 });
3515 };
3516 }
3517
3518 headersCapability.resolve({
3519 isStreamingSupported: fullReader.isStreamingSupported,
3520 isRangeSupported: fullReader.isRangeSupported,
3521 contentLength: fullReader.contentLength
3522 });
3523 }, headersCapability.reject);
3524 return headersCapability.promise;
3525 });
3526 messageHandler.on("GetRangeReader", (data, sink) => {
3527 (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
3528
3529 const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
3530
3531 if (!rangeReader) {
3532 sink.close();
3533 return;
3534 }
3535
3536 sink.onPull = () => {
3537 rangeReader.read().then(function ({
3538 value,
3539 done
3540 }) {
3541 if (done) {
3542 sink.close();
3543 return;
3544 }
3545
3546 (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
3547 sink.enqueue(new Uint8Array(value), 1, [value]);
3548 }).catch(reason => {
3549 sink.error(reason);
3550 });
3551 };
3552
3553 sink.onCancel = reason => {
3554 rangeReader.cancel(reason);
3555 sink.ready.catch(readyReason => {
3556 if (this.destroyed) {
3557 return;
3558 }
3559
3560 throw readyReason;
3561 });
3562 };
3563 });
3564 messageHandler.on("GetDoc", ({
3565 pdfInfo
3566 }) => {
3567 this._numPages = pdfInfo.numPages;
3568 this._htmlForXfa = pdfInfo.htmlForXfa;
3569 delete pdfInfo.htmlForXfa;
3570
3571 loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
3572 });
3573 messageHandler.on("DocException", function (ex) {
3574 let reason;
3575
3576 switch (ex.name) {
3577 case "PasswordException":
3578 reason = new _util.PasswordException(ex.message, ex.code);
3579 break;
3580
3581 case "InvalidPDFException":
3582 reason = new _util.InvalidPDFException(ex.message);
3583 break;
3584
3585 case "MissingPDFException":
3586 reason = new _util.MissingPDFException(ex.message);
3587 break;
3588
3589 case "UnexpectedResponseException":
3590 reason = new _util.UnexpectedResponseException(ex.message, ex.status);
3591 break;
3592
3593 case "UnknownErrorException":
3594 reason = new _util.UnknownErrorException(ex.message, ex.details);
3595 break;
3596
3597 default:
3598 (0, _util.unreachable)("DocException - expected a valid Error.");
3599 }
3600
3601 loadingTask._capability.reject(reason);
3602 });
3603 messageHandler.on("PasswordRequest", exception => {
3604 this._passwordCapability = (0, _util.createPromiseCapability)();
3605
3606 if (loadingTask.onPassword) {
3607 const updatePassword = password => {
3608 this._passwordCapability.resolve({
3609 password
3610 });
3611 };
3612
3613 try {
3614 loadingTask.onPassword(updatePassword, exception.code);
3615 } catch (ex) {
3616 this._passwordCapability.reject(ex);
3617 }
3618 } else {
3619 this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
3620 }
3621
3622 return this._passwordCapability.promise;
3623 });
3624 messageHandler.on("DataLoaded", data => {
3625 loadingTask.onProgress?.({
3626 loaded: data.length,
3627 total: data.length
3628 });
3629 this.downloadInfoCapability.resolve(data);
3630 });
3631 messageHandler.on("StartRenderPage", data => {
3632 if (this.destroyed) {
3633 return;
3634 }
3635
3636 const page = this.#pageCache.get(data.pageIndex);
3637
3638 page._startRenderPage(data.transparency, data.cacheKey);
3639 });
3640 messageHandler.on("commonobj", ([id, type, exportedData]) => {
3641 if (this.destroyed) {
3642 return;
3643 }
3644
3645 if (this.commonObjs.has(id)) {
3646 return;
3647 }
3648
3649 switch (type) {
3650 case "Font":
3651 const params = this._params;
3652
3653 if ("error" in exportedData) {
3654 const exportedError = exportedData.error;
3655 (0, _util.warn)(`Error during font loading: ${exportedError}`);
3656 this.commonObjs.resolve(id, exportedError);
3657 break;
3658 }
3659
3660 let fontRegistry = null;
3661
3662 if (params.pdfBug && globalThis.FontInspector?.enabled) {
3663 fontRegistry = {
3664 registerFont(font, url) {
3665 globalThis.FontInspector.fontAdded(font, url);
3666 }
3667
3668 };
3669 }
3670
3671 const font = new _font_loader.FontFaceObject(exportedData, {
3672 isEvalSupported: params.isEvalSupported,
3673 disableFontFace: params.disableFontFace,
3674 ignoreErrors: params.ignoreErrors,
3675 onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
3676 fontRegistry
3677 });
3678 this.fontLoader.bind(font).catch(reason => {
3679 return messageHandler.sendWithPromise("FontFallback", {
3680 id
3681 });
3682 }).finally(() => {
3683 if (!params.fontExtraProperties && font.data) {
3684 font.data = null;
3685 }
3686
3687 this.commonObjs.resolve(id, font);
3688 });
3689 break;
3690
3691 case "FontPath":
3692 case "Image":
3693 this.commonObjs.resolve(id, exportedData);
3694 break;
3695
3696 default:
3697 throw new Error(`Got unknown common object type ${type}`);
3698 }
3699 });
3700 messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
3701 if (this.destroyed) {
3702 return;
3703 }
3704
3705 const pageProxy = this.#pageCache.get(pageIndex);
3706
3707 if (pageProxy.objs.has(id)) {
3708 return;
3709 }
3710
3711 switch (type) {
3712 case "Image":
3713 pageProxy.objs.resolve(id, imageData);
3714 const MAX_IMAGE_SIZE_TO_STORE = 8000000;
3715
3716 if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) {
3717 pageProxy.cleanupAfterRender = true;
3718 }
3719
3720 break;
3721
3722 case "Pattern":
3723 pageProxy.objs.resolve(id, imageData);
3724 break;
3725
3726 default:
3727 throw new Error(`Got unknown object type ${type}`);
3728 }
3729 });
3730 messageHandler.on("DocProgress", data => {
3731 if (this.destroyed) {
3732 return;
3733 }
3734
3735 loadingTask.onProgress?.({
3736 loaded: data.loaded,
3737 total: data.total
3738 });
3739 });
3740 messageHandler.on("DocStats", data => {
3741 if (this.destroyed) {
3742 return;
3743 }
3744
3745 this.#docStats = Object.freeze({
3746 streamTypes: Object.freeze(data.streamTypes),
3747 fontTypes: Object.freeze(data.fontTypes)
3748 });
3749 });
3750 messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
3751 messageHandler.on("FetchBuiltInCMap", data => {
3752 if (this.destroyed) {
3753 return Promise.reject(new Error("Worker was destroyed."));
3754 }
3755
3756 if (!this.CMapReaderFactory) {
3757 return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
3758 }
3759
3760 return this.CMapReaderFactory.fetch(data);
3761 });
3762 messageHandler.on("FetchStandardFontData", data => {
3763 if (this.destroyed) {
3764 return Promise.reject(new Error("Worker was destroyed."));
3765 }
3766
3767 if (!this.StandardFontDataFactory) {
3768 return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
3769 }
3770
3771 return this.StandardFontDataFactory.fetch(data);
3772 });
3773 }
3774
3775 _onUnsupportedFeature({
3776 featureId
3777 }) {
3778 if (this.destroyed) {
3779 return;
3780 }
3781
3782 this.loadingTask.onUnsupportedFeature?.(featureId);
3783 }
3784
3785 getData() {
3786 return this.messageHandler.sendWithPromise("GetData", null);
3787 }
3788
3789 getPage(pageNumber) {
3790 if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
3791 return Promise.reject(new Error("Invalid page request"));
3792 }
3793
3794 const pageIndex = pageNumber - 1,
3795 cachedPromise = this.#pagePromises.get(pageIndex);
3796
3797 if (cachedPromise) {
3798 return cachedPromise;
3799 }
3800
3801 const promise = this.messageHandler.sendWithPromise("GetPage", {
3802 pageIndex
3803 }).then(pageInfo => {
3804 if (this.destroyed) {
3805 throw new Error("Transport destroyed");
3806 }
3807
3808 const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
3809 this.#pageCache.set(pageIndex, page);
3810 return page;
3811 });
3812 this.#pagePromises.set(pageIndex, promise);
3813 return promise;
3814 }
3815
3816 getPageIndex(ref) {
3817 return this.messageHandler.sendWithPromise("GetPageIndex", {
3818 ref
3819 });
3820 }
3821
3822 getAnnotations(pageIndex, intent) {
3823 return this.messageHandler.sendWithPromise("GetAnnotations", {
3824 pageIndex,
3825 intent
3826 });
3827 }
3828
3829 saveDocument() {
3830 return this.messageHandler.sendWithPromise("SaveDocument", {
3831 isPureXfa: !!this._htmlForXfa,
3832 numPages: this._numPages,
3833 annotationStorage: this.annotationStorage.serializable,
3834 filename: this._fullReader?.filename ?? null
3835 }).finally(() => {
3836 this.annotationStorage.resetModified();
3837 });
3838 }
3839
3840 getFieldObjects() {
3841 return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
3842 }
3843
3844 hasJSActions() {
3845 return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
3846 }
3847
3848 getCalculationOrderIds() {
3849 return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
3850 }
3851
3852 getDestinations() {
3853 return this.messageHandler.sendWithPromise("GetDestinations", null);
3854 }
3855
3856 getDestination(id) {
3857 if (typeof id !== "string") {
3858 return Promise.reject(new Error("Invalid destination request."));
3859 }
3860
3861 return this.messageHandler.sendWithPromise("GetDestination", {
3862 id
3863 });
3864 }
3865
3866 getPageLabels() {
3867 return this.messageHandler.sendWithPromise("GetPageLabels", null);
3868 }
3869
3870 getPageLayout() {
3871 return this.messageHandler.sendWithPromise("GetPageLayout", null);
3872 }
3873
3874 getPageMode() {
3875 return this.messageHandler.sendWithPromise("GetPageMode", null);
3876 }
3877
3878 getViewerPreferences() {
3879 return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
3880 }
3881
3882 getOpenAction() {
3883 return this.messageHandler.sendWithPromise("GetOpenAction", null);
3884 }
3885
3886 getAttachments() {
3887 return this.messageHandler.sendWithPromise("GetAttachments", null);
3888 }
3889
3890 getJavaScript() {
3891 return this.messageHandler.sendWithPromise("GetJavaScript", null);
3892 }
3893
3894 getDocJSActions() {
3895 return this.messageHandler.sendWithPromise("GetDocJSActions", null);
3896 }
3897
3898 getPageJSActions(pageIndex) {
3899 return this.messageHandler.sendWithPromise("GetPageJSActions", {
3900 pageIndex
3901 });
3902 }
3903
3904 getStructTree(pageIndex) {
3905 return this.messageHandler.sendWithPromise("GetStructTree", {
3906 pageIndex
3907 });
3908 }
3909
3910 getOutline() {
3911 return this.messageHandler.sendWithPromise("GetOutline", null);
3912 }
3913
3914 getOptionalContentConfig() {
3915 return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
3916 return new _optional_content_config.OptionalContentConfig(results);
3917 });
3918 }
3919
3920 getPermissions() {
3921 return this.messageHandler.sendWithPromise("GetPermissions", null);
3922 }
3923
3924 getMetadata() {
3925 return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
3926 return {
3927 info: results[0],
3928 metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
3929 contentDispositionFilename: this._fullReader?.filename ?? null,
3930 contentLength: this._fullReader?.contentLength ?? null
3931 };
3932 });
3933 }
3934
3935 getMarkInfo() {
3936 return this.messageHandler.sendWithPromise("GetMarkInfo", null);
3937 }
3938
3939 async startCleanup(keepLoadedFonts = false) {
3940 await this.messageHandler.sendWithPromise("Cleanup", null);
3941
3942 if (this.destroyed) {
3943 return;
3944 }
3945
3946 for (const page of this.#pageCache.values()) {
3947 const cleanupSuccessful = page.cleanup();
3948
3949 if (!cleanupSuccessful) {
3950 throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
3951 }
3952 }
3953
3954 this.commonObjs.clear();
3955
3956 if (!keepLoadedFonts) {
3957 this.fontLoader.clear();
3958 }
3959
3960 this.#metadataPromise = null;
3961 this._getFieldObjectsPromise = null;
3962 this._hasJSActionsPromise = null;
3963 }
3964
3965 get loadingParams() {
3966 const params = this._params;
3967 return (0, _util.shadow)(this, "loadingParams", {
3968 disableAutoFetch: params.disableAutoFetch,
3969 enableXfa: params.enableXfa
3970 });
3971 }
3972
3973}
3974
3975class PDFObjects {
3976 constructor() {
3977 this._objs = Object.create(null);
3978 }
3979
3980 _ensureObj(objId) {
3981 if (this._objs[objId]) {
3982 return this._objs[objId];
3983 }
3984
3985 return this._objs[objId] = {
3986 capability: (0, _util.createPromiseCapability)(),
3987 data: null,
3988 resolved: false
3989 };
3990 }
3991
3992 get(objId, callback = null) {
3993 if (callback) {
3994 this._ensureObj(objId).capability.promise.then(callback);
3995
3996 return null;
3997 }
3998
3999 const obj = this._objs[objId];
4000
4001 if (!obj || !obj.resolved) {
4002 throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
4003 }
4004
4005 return obj.data;
4006 }
4007
4008 has(objId) {
4009 const obj = this._objs[objId];
4010 return obj?.resolved || false;
4011 }
4012
4013 resolve(objId, data) {
4014 const obj = this._ensureObj(objId);
4015
4016 obj.resolved = true;
4017 obj.data = data;
4018 obj.capability.resolve(data);
4019 }
4020
4021 clear() {
4022 this._objs = Object.create(null);
4023 }
4024
4025}
4026
4027class RenderTask {
4028 constructor(internalRenderTask) {
4029 this._internalRenderTask = internalRenderTask;
4030 this.onContinue = null;
4031 }
4032
4033 get promise() {
4034 return this._internalRenderTask.capability.promise;
4035 }
4036
4037 cancel() {
4038 this._internalRenderTask.cancel();
4039 }
4040
4041}
4042
4043exports.RenderTask = RenderTask;
4044
4045class InternalRenderTask {
4046 static get canvasInUse() {
4047 return (0, _util.shadow)(this, "canvasInUse", new WeakSet());
4048 }
4049
4050 constructor({
4051 callback,
4052 params,
4053 objs,
4054 commonObjs,
4055 annotationCanvasMap,
4056 operatorList,
4057 pageIndex,
4058 canvasFactory,
4059 useRequestAnimationFrame = false,
4060 pdfBug = false
4061 }) {
4062 this.callback = callback;
4063 this.params = params;
4064 this.objs = objs;
4065 this.commonObjs = commonObjs;
4066 this.annotationCanvasMap = annotationCanvasMap;
4067 this.operatorListIdx = null;
4068 this.operatorList = operatorList;
4069 this._pageIndex = pageIndex;
4070 this.canvasFactory = canvasFactory;
4071 this._pdfBug = pdfBug;
4072 this.running = false;
4073 this.graphicsReadyCallback = null;
4074 this.graphicsReady = false;
4075 this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
4076 this.cancelled = false;
4077 this.capability = (0, _util.createPromiseCapability)();
4078 this.task = new RenderTask(this);
4079 this._cancelBound = this.cancel.bind(this);
4080 this._continueBound = this._continue.bind(this);
4081 this._scheduleNextBound = this._scheduleNext.bind(this);
4082 this._nextBound = this._next.bind(this);
4083 this._canvas = params.canvasContext.canvas;
4084 }
4085
4086 get completed() {
4087 return this.capability.promise.catch(function () {});
4088 }
4089
4090 initializeGraphics({
4091 transparency = false,
4092 optionalContentConfig
4093 }) {
4094 if (this.cancelled) {
4095 return;
4096 }
4097
4098 if (this._canvas) {
4099 if (InternalRenderTask.canvasInUse.has(this._canvas)) {
4100 throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
4101 }
4102
4103 InternalRenderTask.canvasInUse.add(this._canvas);
4104 }
4105
4106 if (this._pdfBug && globalThis.StepperManager?.enabled) {
4107 this.stepper = globalThis.StepperManager.create(this._pageIndex);
4108 this.stepper.init(this.operatorList);
4109 this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
4110 }
4111
4112 const {
4113 canvasContext,
4114 viewport,
4115 transform,
4116 imageLayer,
4117 background
4118 } = this.params;
4119 this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig, this.annotationCanvasMap);
4120 this.gfx.beginDrawing({
4121 transform,
4122 viewport,
4123 transparency,
4124 background
4125 });
4126 this.operatorListIdx = 0;
4127 this.graphicsReady = true;
4128
4129 if (this.graphicsReadyCallback) {
4130 this.graphicsReadyCallback();
4131 }
4132 }
4133
4134 cancel(error = null) {
4135 this.running = false;
4136 this.cancelled = true;
4137
4138 if (this.gfx) {
4139 this.gfx.endDrawing();
4140 }
4141
4142 if (this._canvas) {
4143 InternalRenderTask.canvasInUse.delete(this._canvas);
4144 }
4145
4146 this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
4147 }
4148
4149 operatorListChanged() {
4150 if (!this.graphicsReady) {
4151 if (!this.graphicsReadyCallback) {
4152 this.graphicsReadyCallback = this._continueBound;
4153 }
4154
4155 return;
4156 }
4157
4158 if (this.stepper) {
4159 this.stepper.updateOperatorList(this.operatorList);
4160 }
4161
4162 if (this.running) {
4163 return;
4164 }
4165
4166 this._continue();
4167 }
4168
4169 _continue() {
4170 this.running = true;
4171
4172 if (this.cancelled) {
4173 return;
4174 }
4175
4176 if (this.task.onContinue) {
4177 this.task.onContinue(this._scheduleNextBound);
4178 } else {
4179 this._scheduleNext();
4180 }
4181 }
4182
4183 _scheduleNext() {
4184 if (this._useRequestAnimationFrame) {
4185 window.requestAnimationFrame(() => {
4186 this._nextBound().catch(this._cancelBound);
4187 });
4188 } else {
4189 Promise.resolve().then(this._nextBound).catch(this._cancelBound);
4190 }
4191 }
4192
4193 async _next() {
4194 if (this.cancelled) {
4195 return;
4196 }
4197
4198 this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
4199
4200 if (this.operatorListIdx === this.operatorList.argsArray.length) {
4201 this.running = false;
4202
4203 if (this.operatorList.lastChunk) {
4204 this.gfx.endDrawing();
4205
4206 if (this._canvas) {
4207 InternalRenderTask.canvasInUse.delete(this._canvas);
4208 }
4209
4210 this.callback();
4211 }
4212 }
4213 }
4214
4215}
4216
4217const version = '2.12.313';
4218exports.version = version;
4219const build = 'a2ae56f39';
4220exports.build = build;
4221
4222/***/ }),
4223/* 7 */
4224/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4225
4226
4227
4228Object.defineProperty(exports, "__esModule", ({
4229 value: true
4230}));
4231exports.FontLoader = exports.FontFaceObject = void 0;
4232
4233var _util = __w_pdfjs_require__(2);
4234
4235class BaseFontLoader {
4236 constructor({
4237 docId,
4238 onUnsupportedFeature,
4239 ownerDocument = globalThis.document,
4240 styleElement = null
4241 }) {
4242 if (this.constructor === BaseFontLoader) {
4243 (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
4244 }
4245
4246 this.docId = docId;
4247 this._onUnsupportedFeature = onUnsupportedFeature;
4248 this._document = ownerDocument;
4249 this.nativeFontFaces = [];
4250 this.styleElement = null;
4251 }
4252
4253 addNativeFontFace(nativeFontFace) {
4254 this.nativeFontFaces.push(nativeFontFace);
4255
4256 this._document.fonts.add(nativeFontFace);
4257 }
4258
4259 insertRule(rule) {
4260 let styleElement = this.styleElement;
4261
4262 if (!styleElement) {
4263 styleElement = this.styleElement = this._document.createElement("style");
4264 styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
4265
4266 this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
4267 }
4268
4269 const styleSheet = styleElement.sheet;
4270 styleSheet.insertRule(rule, styleSheet.cssRules.length);
4271 }
4272
4273 clear() {
4274 for (const nativeFontFace of this.nativeFontFaces) {
4275 this._document.fonts.delete(nativeFontFace);
4276 }
4277
4278 this.nativeFontFaces.length = 0;
4279
4280 if (this.styleElement) {
4281 this.styleElement.remove();
4282 this.styleElement = null;
4283 }
4284 }
4285
4286 async bind(font) {
4287 if (font.attached || font.missingFile) {
4288 return;
4289 }
4290
4291 font.attached = true;
4292
4293 if (this.isFontLoadingAPISupported) {
4294 const nativeFontFace = font.createNativeFontFace();
4295
4296 if (nativeFontFace) {
4297 this.addNativeFontFace(nativeFontFace);
4298
4299 try {
4300 await nativeFontFace.loaded;
4301 } catch (ex) {
4302 this._onUnsupportedFeature({
4303 featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
4304 });
4305
4306 (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
4307 font.disableFontFace = true;
4308 throw ex;
4309 }
4310 }
4311
4312 return;
4313 }
4314
4315 const rule = font.createFontFaceRule();
4316
4317 if (rule) {
4318 this.insertRule(rule);
4319
4320 if (this.isSyncFontLoadingSupported) {
4321 return;
4322 }
4323
4324 await new Promise(resolve => {
4325 const request = this._queueLoadingCallback(resolve);
4326
4327 this._prepareFontLoadEvent([rule], [font], request);
4328 });
4329 }
4330 }
4331
4332 _queueLoadingCallback(callback) {
4333 (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
4334 }
4335
4336 get isFontLoadingAPISupported() {
4337 const hasFonts = !!this._document?.fonts;
4338 return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
4339 }
4340
4341 get isSyncFontLoadingSupported() {
4342 (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
4343 }
4344
4345 get _loadTestFont() {
4346 (0, _util.unreachable)("Abstract method `_loadTestFont`.");
4347 }
4348
4349 _prepareFontLoadEvent(rules, fontsToLoad, request) {
4350 (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
4351 }
4352
4353}
4354
4355let FontLoader;
4356exports.FontLoader = FontLoader;
4357{
4358 exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
4359 constructor(params) {
4360 super(params);
4361 this.loadingContext = {
4362 requests: [],
4363 nextRequestId: 0
4364 };
4365 this.loadTestFontId = 0;
4366 }
4367
4368 get isSyncFontLoadingSupported() {
4369 let supported = false;
4370
4371 if (typeof navigator === "undefined") {
4372 supported = true;
4373 } else {
4374 const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
4375
4376 if (m?.[1] >= 14) {
4377 supported = true;
4378 }
4379 }
4380
4381 return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
4382 }
4383
4384 _queueLoadingCallback(callback) {
4385 function completeRequest() {
4386 (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
4387 request.done = true;
4388
4389 while (context.requests.length > 0 && context.requests[0].done) {
4390 const otherRequest = context.requests.shift();
4391 setTimeout(otherRequest.callback, 0);
4392 }
4393 }
4394
4395 const context = this.loadingContext;
4396 const request = {
4397 id: `pdfjs-font-loading-${context.nextRequestId++}`,
4398 done: false,
4399 complete: completeRequest,
4400 callback
4401 };
4402 context.requests.push(request);
4403 return request;
4404 }
4405
4406 get _loadTestFont() {
4407 const getLoadTestFont = function () {
4408 return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
4409 };
4410
4411 return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
4412 }
4413
4414 _prepareFontLoadEvent(rules, fonts, request) {
4415 function int32(data, offset) {
4416 return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
4417 }
4418
4419 function spliceString(s, offset, remove, insert) {
4420 const chunk1 = s.substring(0, offset);
4421 const chunk2 = s.substring(offset + remove);
4422 return chunk1 + insert + chunk2;
4423 }
4424
4425 let i, ii;
4426
4427 const canvas = this._document.createElement("canvas");
4428
4429 canvas.width = 1;
4430 canvas.height = 1;
4431 const ctx = canvas.getContext("2d");
4432 let called = 0;
4433
4434 function isFontReady(name, callback) {
4435 called++;
4436
4437 if (called > 30) {
4438 (0, _util.warn)("Load test font never loaded.");
4439 callback();
4440 return;
4441 }
4442
4443 ctx.font = "30px " + name;
4444 ctx.fillText(".", 0, 20);
4445 const imageData = ctx.getImageData(0, 0, 1, 1);
4446
4447 if (imageData.data[3] > 0) {
4448 callback();
4449 return;
4450 }
4451
4452 setTimeout(isFontReady.bind(null, name, callback));
4453 }
4454
4455 const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
4456 let data = this._loadTestFont;
4457 const COMMENT_OFFSET = 976;
4458 data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
4459 const CFF_CHECKSUM_OFFSET = 16;
4460 const XXXX_VALUE = 0x58585858;
4461 let checksum = int32(data, CFF_CHECKSUM_OFFSET);
4462
4463 for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
4464 checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
4465 }
4466
4467 if (i < loadTestFontId.length) {
4468 checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
4469 }
4470
4471 data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
4472 const url = `url(data:font/opentype;base64,${btoa(data)});`;
4473 const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
4474 this.insertRule(rule);
4475 const names = [];
4476
4477 for (const font of fonts) {
4478 names.push(font.loadedName);
4479 }
4480
4481 names.push(loadTestFontId);
4482
4483 const div = this._document.createElement("div");
4484
4485 div.style.visibility = "hidden";
4486 div.style.width = div.style.height = "10px";
4487 div.style.position = "absolute";
4488 div.style.top = div.style.left = "0px";
4489
4490 for (const name of names) {
4491 const span = this._document.createElement("span");
4492
4493 span.textContent = "Hi";
4494 span.style.fontFamily = name;
4495 div.appendChild(span);
4496 }
4497
4498 this._document.body.appendChild(div);
4499
4500 isFontReady(loadTestFontId, () => {
4501 div.remove();
4502 request.complete();
4503 });
4504 }
4505
4506 };
4507}
4508
4509class FontFaceObject {
4510 constructor(translatedData, {
4511 isEvalSupported = true,
4512 disableFontFace = false,
4513 ignoreErrors = false,
4514 onUnsupportedFeature,
4515 fontRegistry = null
4516 }) {
4517 this.compiledGlyphs = Object.create(null);
4518
4519 for (const i in translatedData) {
4520 this[i] = translatedData[i];
4521 }
4522
4523 this.isEvalSupported = isEvalSupported !== false;
4524 this.disableFontFace = disableFontFace === true;
4525 this.ignoreErrors = ignoreErrors === true;
4526 this._onUnsupportedFeature = onUnsupportedFeature;
4527 this.fontRegistry = fontRegistry;
4528 }
4529
4530 createNativeFontFace() {
4531 if (!this.data || this.disableFontFace) {
4532 return null;
4533 }
4534
4535 let nativeFontFace;
4536
4537 if (!this.cssFontInfo) {
4538 nativeFontFace = new FontFace(this.loadedName, this.data, {});
4539 } else {
4540 const css = {
4541 weight: this.cssFontInfo.fontWeight
4542 };
4543
4544 if (this.cssFontInfo.italicAngle) {
4545 css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
4546 }
4547
4548 nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
4549 }
4550
4551 if (this.fontRegistry) {
4552 this.fontRegistry.registerFont(this);
4553 }
4554
4555 return nativeFontFace;
4556 }
4557
4558 createFontFaceRule() {
4559 if (!this.data || this.disableFontFace) {
4560 return null;
4561 }
4562
4563 const data = (0, _util.bytesToString)(this.data);
4564 const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
4565 let rule;
4566
4567 if (!this.cssFontInfo) {
4568 rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
4569 } else {
4570 let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
4571
4572 if (this.cssFontInfo.italicAngle) {
4573 css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
4574 }
4575
4576 rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
4577 }
4578
4579 if (this.fontRegistry) {
4580 this.fontRegistry.registerFont(this, url);
4581 }
4582
4583 return rule;
4584 }
4585
4586 getPathGenerator(objs, character) {
4587 if (this.compiledGlyphs[character] !== undefined) {
4588 return this.compiledGlyphs[character];
4589 }
4590
4591 let cmds;
4592
4593 try {
4594 cmds = objs.get(this.loadedName + "_path_" + character);
4595 } catch (ex) {
4596 if (!this.ignoreErrors) {
4597 throw ex;
4598 }
4599
4600 this._onUnsupportedFeature({
4601 featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
4602 });
4603
4604 (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
4605 return this.compiledGlyphs[character] = function (c, size) {};
4606 }
4607
4608 if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
4609 const jsBuf = [];
4610
4611 for (const current of cmds) {
4612 const args = current.args !== undefined ? current.args.join(",") : "";
4613 jsBuf.push("c.", current.cmd, "(", args, ");\n");
4614 }
4615
4616 return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
4617 }
4618
4619 return this.compiledGlyphs[character] = function (c, size) {
4620 for (const current of cmds) {
4621 if (current.cmd === "scale") {
4622 current.args = [size, -size];
4623 }
4624
4625 c[current.cmd].apply(c, current.args);
4626 }
4627 };
4628 }
4629
4630}
4631
4632exports.FontFaceObject = FontFaceObject;
4633
4634/***/ }),
4635/* 8 */
4636/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4637
4638
4639
4640Object.defineProperty(exports, "__esModule", ({
4641 value: true
4642}));
4643exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
4644
4645var _base_factory = __w_pdfjs_require__(5);
4646
4647var _is_node = __w_pdfjs_require__(4);
4648
4649var _util = __w_pdfjs_require__(2);
4650
4651let NodeCanvasFactory = class {
4652 constructor() {
4653 (0, _util.unreachable)("Not implemented: NodeCanvasFactory");
4654 }
4655
4656};
4657exports.NodeCanvasFactory = NodeCanvasFactory;
4658let NodeCMapReaderFactory = class {
4659 constructor() {
4660 (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory");
4661 }
4662
4663};
4664exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
4665let NodeStandardFontDataFactory = class {
4666 constructor() {
4667 (0, _util.unreachable)("Not implemented: NodeStandardFontDataFactory");
4668 }
4669
4670};
4671exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
4672
4673if (_is_node.isNodeJS) {
4674 const fetchData = function (url) {
4675 return new Promise((resolve, reject) => {
4676 const fs = require("fs");
4677
4678 fs.readFile(url, (error, data) => {
4679 if (error || !data) {
4680 reject(new Error(error));
4681 return;
4682 }
4683
4684 resolve(new Uint8Array(data));
4685 });
4686 });
4687 };
4688
4689 exports.NodeCanvasFactory = NodeCanvasFactory = class extends _base_factory.BaseCanvasFactory {
4690 _createCanvas(width, height) {
4691 const Canvas = require("canvas");
4692
4693 return Canvas.createCanvas(width, height);
4694 }
4695
4696 };
4697 exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _base_factory.BaseCMapReaderFactory {
4698 _fetchData(url, compressionType) {
4699 return fetchData(url).then(data => {
4700 return {
4701 cMapData: data,
4702 compressionType
4703 };
4704 });
4705 }
4706
4707 };
4708 exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory = class extends _base_factory.BaseStandardFontDataFactory {
4709 _fetchData(url) {
4710 return fetchData(url);
4711 }
4712
4713 };
4714}
4715
4716/***/ }),
4717/* 9 */
4718/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4719
4720
4721
4722Object.defineProperty(exports, "__esModule", ({
4723 value: true
4724}));
4725exports.AnnotationStorage = void 0;
4726
4727var _util = __w_pdfjs_require__(2);
4728
4729class AnnotationStorage {
4730 constructor() {
4731 this._storage = new Map();
4732 this._timeStamp = Date.now();
4733 this._modified = false;
4734 this.onSetModified = null;
4735 this.onResetModified = null;
4736 }
4737
4738 getValue(key, defaultValue) {
4739 const value = this._storage.get(key);
4740
4741 if (value === undefined) {
4742 return defaultValue;
4743 }
4744
4745 return Object.assign(defaultValue, value);
4746 }
4747
4748 setValue(key, value) {
4749 const obj = this._storage.get(key);
4750
4751 let modified = false;
4752
4753 if (obj !== undefined) {
4754 for (const [entry, val] of Object.entries(value)) {
4755 if (obj[entry] !== val) {
4756 modified = true;
4757 obj[entry] = val;
4758 }
4759 }
4760 } else {
4761 modified = true;
4762
4763 this._storage.set(key, value);
4764 }
4765
4766 if (modified) {
4767 this._timeStamp = Date.now();
4768
4769 this._setModified();
4770 }
4771 }
4772
4773 getAll() {
4774 return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
4775 }
4776
4777 get size() {
4778 return this._storage.size;
4779 }
4780
4781 _setModified() {
4782 if (!this._modified) {
4783 this._modified = true;
4784
4785 if (typeof this.onSetModified === "function") {
4786 this.onSetModified();
4787 }
4788 }
4789 }
4790
4791 resetModified() {
4792 if (this._modified) {
4793 this._modified = false;
4794
4795 if (typeof this.onResetModified === "function") {
4796 this.onResetModified();
4797 }
4798 }
4799 }
4800
4801 get serializable() {
4802 return this._storage.size > 0 ? this._storage : null;
4803 }
4804
4805 get lastModified() {
4806 return this._timeStamp.toString();
4807 }
4808
4809}
4810
4811exports.AnnotationStorage = AnnotationStorage;
4812
4813/***/ }),
4814/* 10 */
4815/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4816
4817
4818
4819Object.defineProperty(exports, "__esModule", ({
4820 value: true
4821}));
4822exports.CanvasGraphics = void 0;
4823
4824var _util = __w_pdfjs_require__(2);
4825
4826var _pattern_helper = __w_pdfjs_require__(11);
4827
4828var _display_utils = __w_pdfjs_require__(1);
4829
4830const MIN_FONT_SIZE = 16;
4831const MAX_FONT_SIZE = 100;
4832const MAX_GROUP_SIZE = 4096;
4833const EXECUTION_TIME = 15;
4834const EXECUTION_STEPS = 10;
4835const COMPILE_TYPE3_GLYPHS = true;
4836const MAX_SIZE_TO_COMPILE = 1000;
4837const FULL_CHUNK_HEIGHT = 16;
4838const LINEWIDTH_SCALE_FACTOR = 1.000001;
4839
4840function mirrorContextOperations(ctx, destCtx) {
4841 if (ctx._removeMirroring) {
4842 throw new Error("Context is already forwarding operations.");
4843 }
4844
4845 ctx.__originalSave = ctx.save;
4846 ctx.__originalRestore = ctx.restore;
4847 ctx.__originalRotate = ctx.rotate;
4848 ctx.__originalScale = ctx.scale;
4849 ctx.__originalTranslate = ctx.translate;
4850 ctx.__originalTransform = ctx.transform;
4851 ctx.__originalSetTransform = ctx.setTransform;
4852 ctx.__originalResetTransform = ctx.resetTransform;
4853 ctx.__originalClip = ctx.clip;
4854 ctx.__originalMoveTo = ctx.moveTo;
4855 ctx.__originalLineTo = ctx.lineTo;
4856 ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
4857 ctx.__originalRect = ctx.rect;
4858 ctx.__originalClosePath = ctx.closePath;
4859 ctx.__originalBeginPath = ctx.beginPath;
4860
4861 ctx._removeMirroring = () => {
4862 ctx.save = ctx.__originalSave;
4863 ctx.restore = ctx.__originalRestore;
4864 ctx.rotate = ctx.__originalRotate;
4865 ctx.scale = ctx.__originalScale;
4866 ctx.translate = ctx.__originalTranslate;
4867 ctx.transform = ctx.__originalTransform;
4868 ctx.setTransform = ctx.__originalSetTransform;
4869 ctx.resetTransform = ctx.__originalResetTransform;
4870 ctx.clip = ctx.__originalClip;
4871 ctx.moveTo = ctx.__originalMoveTo;
4872 ctx.lineTo = ctx.__originalLineTo;
4873 ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
4874 ctx.rect = ctx.__originalRect;
4875 ctx.closePath = ctx.__originalClosePath;
4876 ctx.beginPath = ctx.__originalBeginPath;
4877 delete ctx._removeMirroring;
4878 };
4879
4880 ctx.save = function ctxSave() {
4881 destCtx.save();
4882
4883 this.__originalSave();
4884 };
4885
4886 ctx.restore = function ctxRestore() {
4887 destCtx.restore();
4888
4889 this.__originalRestore();
4890 };
4891
4892 ctx.translate = function ctxTranslate(x, y) {
4893 destCtx.translate(x, y);
4894
4895 this.__originalTranslate(x, y);
4896 };
4897
4898 ctx.scale = function ctxScale(x, y) {
4899 destCtx.scale(x, y);
4900
4901 this.__originalScale(x, y);
4902 };
4903
4904 ctx.transform = function ctxTransform(a, b, c, d, e, f) {
4905 destCtx.transform(a, b, c, d, e, f);
4906
4907 this.__originalTransform(a, b, c, d, e, f);
4908 };
4909
4910 ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
4911 destCtx.setTransform(a, b, c, d, e, f);
4912
4913 this.__originalSetTransform(a, b, c, d, e, f);
4914 };
4915
4916 ctx.resetTransform = function ctxResetTransform() {
4917 destCtx.resetTransform();
4918
4919 this.__originalResetTransform();
4920 };
4921
4922 ctx.rotate = function ctxRotate(angle) {
4923 destCtx.rotate(angle);
4924
4925 this.__originalRotate(angle);
4926 };
4927
4928 ctx.clip = function ctxRotate(rule) {
4929 destCtx.clip(rule);
4930
4931 this.__originalClip(rule);
4932 };
4933
4934 ctx.moveTo = function (x, y) {
4935 destCtx.moveTo(x, y);
4936
4937 this.__originalMoveTo(x, y);
4938 };
4939
4940 ctx.lineTo = function (x, y) {
4941 destCtx.lineTo(x, y);
4942
4943 this.__originalLineTo(x, y);
4944 };
4945
4946 ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
4947 destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
4948
4949 this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
4950 };
4951
4952 ctx.rect = function (x, y, width, height) {
4953 destCtx.rect(x, y, width, height);
4954
4955 this.__originalRect(x, y, width, height);
4956 };
4957
4958 ctx.closePath = function () {
4959 destCtx.closePath();
4960
4961 this.__originalClosePath();
4962 };
4963
4964 ctx.beginPath = function () {
4965 destCtx.beginPath();
4966
4967 this.__originalBeginPath();
4968 };
4969}
4970
4971function addContextCurrentTransform(ctx) {
4972 if (ctx.mozCurrentTransform) {
4973 return;
4974 }
4975
4976 ctx._originalSave = ctx.save;
4977 ctx._originalRestore = ctx.restore;
4978 ctx._originalRotate = ctx.rotate;
4979 ctx._originalScale = ctx.scale;
4980 ctx._originalTranslate = ctx.translate;
4981 ctx._originalTransform = ctx.transform;
4982 ctx._originalSetTransform = ctx.setTransform;
4983 ctx._originalResetTransform = ctx.resetTransform;
4984 ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
4985 ctx._transformStack = [];
4986
4987 try {
4988 const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
4989 ctx._setLineWidth = desc.set;
4990 ctx._getLineWidth = desc.get;
4991 Object.defineProperty(ctx, "lineWidth", {
4992 set: function setLineWidth(width) {
4993 this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
4994 },
4995 get: function getLineWidth() {
4996 return this._getLineWidth();
4997 }
4998 });
4999 } catch (_) {}
5000
5001 Object.defineProperty(ctx, "mozCurrentTransform", {
5002 get: function getCurrentTransform() {
5003 return this._transformMatrix;
5004 }
5005 });
5006 Object.defineProperty(ctx, "mozCurrentTransformInverse", {
5007 get: function getCurrentTransformInverse() {
5008 const [a, b, c, d, e, f] = this._transformMatrix;
5009 const ad_bc = a * d - b * c;
5010 const bc_ad = b * c - a * d;
5011 return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc];
5012 }
5013 });
5014
5015 ctx.save = function ctxSave() {
5016 const old = this._transformMatrix;
5017
5018 this._transformStack.push(old);
5019
5020 this._transformMatrix = old.slice(0, 6);
5021
5022 this._originalSave();
5023 };
5024
5025 ctx.restore = function ctxRestore() {
5026 const prev = this._transformStack.pop();
5027
5028 if (prev) {
5029 this._transformMatrix = prev;
5030
5031 this._originalRestore();
5032 }
5033 };
5034
5035 ctx.translate = function ctxTranslate(x, y) {
5036 const m = this._transformMatrix;
5037 m[4] = m[0] * x + m[2] * y + m[4];
5038 m[5] = m[1] * x + m[3] * y + m[5];
5039
5040 this._originalTranslate(x, y);
5041 };
5042
5043 ctx.scale = function ctxScale(x, y) {
5044 const m = this._transformMatrix;
5045 m[0] *= x;
5046 m[1] *= x;
5047 m[2] *= y;
5048 m[3] *= y;
5049
5050 this._originalScale(x, y);
5051 };
5052
5053 ctx.transform = function ctxTransform(a, b, c, d, e, f) {
5054 const m = this._transformMatrix;
5055 this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]];
5056
5057 ctx._originalTransform(a, b, c, d, e, f);
5058 };
5059
5060 ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
5061 this._transformMatrix = [a, b, c, d, e, f];
5062
5063 ctx._originalSetTransform(a, b, c, d, e, f);
5064 };
5065
5066 ctx.resetTransform = function ctxResetTransform() {
5067 this._transformMatrix = [1, 0, 0, 1, 0, 0];
5068
5069 ctx._originalResetTransform();
5070 };
5071
5072 ctx.rotate = function ctxRotate(angle) {
5073 const cosValue = Math.cos(angle);
5074 const sinValue = Math.sin(angle);
5075 const m = this._transformMatrix;
5076 this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]];
5077
5078 this._originalRotate(angle);
5079 };
5080}
5081
5082class CachedCanvases {
5083 constructor(canvasFactory) {
5084 this.canvasFactory = canvasFactory;
5085 this.cache = Object.create(null);
5086 }
5087
5088 getCanvas(id, width, height, trackTransform) {
5089 let canvasEntry;
5090
5091 if (this.cache[id] !== undefined) {
5092 canvasEntry = this.cache[id];
5093 this.canvasFactory.reset(canvasEntry, width, height);
5094 canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
5095 } else {
5096 canvasEntry = this.canvasFactory.create(width, height);
5097 this.cache[id] = canvasEntry;
5098 }
5099
5100 if (trackTransform) {
5101 addContextCurrentTransform(canvasEntry.context);
5102 }
5103
5104 return canvasEntry;
5105 }
5106
5107 clear() {
5108 for (const id in this.cache) {
5109 const canvasEntry = this.cache[id];
5110 this.canvasFactory.destroy(canvasEntry);
5111 delete this.cache[id];
5112 }
5113 }
5114
5115}
5116
5117function compileType3Glyph(imgData) {
5118 const POINT_TO_PROCESS_LIMIT = 1000;
5119 const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
5120 const width = imgData.width,
5121 height = imgData.height,
5122 width1 = width + 1;
5123 let i, ii, j, j0;
5124 const points = new Uint8Array(width1 * (height + 1));
5125 const lineSize = width + 7 & ~7,
5126 data0 = imgData.data;
5127 const data = new Uint8Array(lineSize * height);
5128 let pos = 0;
5129
5130 for (i = 0, ii = data0.length; i < ii; i++) {
5131 const elem = data0[i];
5132 let mask = 128;
5133
5134 while (mask > 0) {
5135 data[pos++] = elem & mask ? 0 : 255;
5136 mask >>= 1;
5137 }
5138 }
5139
5140 let count = 0;
5141 pos = 0;
5142
5143 if (data[pos] !== 0) {
5144 points[0] = 1;
5145 ++count;
5146 }
5147
5148 for (j = 1; j < width; j++) {
5149 if (data[pos] !== data[pos + 1]) {
5150 points[j] = data[pos] ? 2 : 1;
5151 ++count;
5152 }
5153
5154 pos++;
5155 }
5156
5157 if (data[pos] !== 0) {
5158 points[j] = 2;
5159 ++count;
5160 }
5161
5162 for (i = 1; i < height; i++) {
5163 pos = i * lineSize;
5164 j0 = i * width1;
5165
5166 if (data[pos - lineSize] !== data[pos]) {
5167 points[j0] = data[pos] ? 1 : 8;
5168 ++count;
5169 }
5170
5171 let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
5172
5173 for (j = 1; j < width; j++) {
5174 sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
5175
5176 if (POINT_TYPES[sum]) {
5177 points[j0 + j] = POINT_TYPES[sum];
5178 ++count;
5179 }
5180
5181 pos++;
5182 }
5183
5184 if (data[pos - lineSize] !== data[pos]) {
5185 points[j0 + j] = data[pos] ? 2 : 4;
5186 ++count;
5187 }
5188
5189 if (count > POINT_TO_PROCESS_LIMIT) {
5190 return null;
5191 }
5192 }
5193
5194 pos = lineSize * (height - 1);
5195 j0 = i * width1;
5196
5197 if (data[pos] !== 0) {
5198 points[j0] = 8;
5199 ++count;
5200 }
5201
5202 for (j = 1; j < width; j++) {
5203 if (data[pos] !== data[pos + 1]) {
5204 points[j0 + j] = data[pos] ? 4 : 8;
5205 ++count;
5206 }
5207
5208 pos++;
5209 }
5210
5211 if (data[pos] !== 0) {
5212 points[j0 + j] = 4;
5213 ++count;
5214 }
5215
5216 if (count > POINT_TO_PROCESS_LIMIT) {
5217 return null;
5218 }
5219
5220 const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
5221 const outlines = [];
5222
5223 for (i = 0; count && i <= height; i++) {
5224 let p = i * width1;
5225 const end = p + width;
5226
5227 while (p < end && !points[p]) {
5228 p++;
5229 }
5230
5231 if (p === end) {
5232 continue;
5233 }
5234
5235 const coords = [p % width1, i];
5236 const p0 = p;
5237 let type = points[p];
5238
5239 do {
5240 const step = steps[type];
5241
5242 do {
5243 p += step;
5244 } while (!points[p]);
5245
5246 const pp = points[p];
5247
5248 if (pp !== 5 && pp !== 10) {
5249 type = pp;
5250 points[p] = 0;
5251 } else {
5252 type = pp & 0x33 * type >> 4;
5253 points[p] &= type >> 2 | type << 2;
5254 }
5255
5256 coords.push(p % width1, p / width1 | 0);
5257
5258 if (!points[p]) {
5259 --count;
5260 }
5261 } while (p0 !== p);
5262
5263 outlines.push(coords);
5264 --i;
5265 }
5266
5267 const drawOutline = function (c) {
5268 c.save();
5269 c.scale(1 / width, -1 / height);
5270 c.translate(0, -height);
5271 c.beginPath();
5272
5273 for (let k = 0, kk = outlines.length; k < kk; k++) {
5274 const o = outlines[k];
5275 c.moveTo(o[0], o[1]);
5276
5277 for (let l = 2, ll = o.length; l < ll; l += 2) {
5278 c.lineTo(o[l], o[l + 1]);
5279 }
5280 }
5281
5282 c.fill();
5283 c.beginPath();
5284 c.restore();
5285 };
5286
5287 return drawOutline;
5288}
5289
5290class CanvasExtraState {
5291 constructor(width, height) {
5292 this.alphaIsShape = false;
5293 this.fontSize = 0;
5294 this.fontSizeScale = 1;
5295 this.textMatrix = _util.IDENTITY_MATRIX;
5296 this.textMatrixScale = 1;
5297 this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
5298 this.leading = 0;
5299 this.x = 0;
5300 this.y = 0;
5301 this.lineX = 0;
5302 this.lineY = 0;
5303 this.charSpacing = 0;
5304 this.wordSpacing = 0;
5305 this.textHScale = 1;
5306 this.textRenderingMode = _util.TextRenderingMode.FILL;
5307 this.textRise = 0;
5308 this.fillColor = "#000000";
5309 this.strokeColor = "#000000";
5310 this.patternFill = false;
5311 this.fillAlpha = 1;
5312 this.strokeAlpha = 1;
5313 this.lineWidth = 1;
5314 this.activeSMask = null;
5315 this.transferMaps = null;
5316 this.startNewPathAndClipBox([0, 0, width, height]);
5317 }
5318
5319 clone() {
5320 const clone = Object.create(this);
5321 clone.clipBox = this.clipBox.slice();
5322 return clone;
5323 }
5324
5325 setCurrentPoint(x, y) {
5326 this.x = x;
5327 this.y = y;
5328 }
5329
5330 updatePathMinMax(transform, x, y) {
5331 [x, y] = _util.Util.applyTransform([x, y], transform);
5332 this.minX = Math.min(this.minX, x);
5333 this.minY = Math.min(this.minY, y);
5334 this.maxX = Math.max(this.maxX, x);
5335 this.maxY = Math.max(this.maxY, y);
5336 }
5337
5338 updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3) {
5339 const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
5340
5341 this.updatePathMinMax(transform, box[0], box[1]);
5342 this.updatePathMinMax(transform, box[2], box[3]);
5343 }
5344
5345 getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5346 const box = [this.minX, this.minY, this.maxX, this.maxY];
5347
5348 if (pathType === _pattern_helper.PathType.STROKE) {
5349 if (!transform) {
5350 (0, _util.unreachable)("Stroke bounding box must include transform.");
5351 }
5352
5353 const scale = _util.Util.singularValueDecompose2dScale(transform);
5354
5355 const xStrokePad = scale[0] * this.lineWidth / 2;
5356 const yStrokePad = scale[1] * this.lineWidth / 2;
5357 box[0] -= xStrokePad;
5358 box[1] -= yStrokePad;
5359 box[2] += xStrokePad;
5360 box[3] += yStrokePad;
5361 }
5362
5363 return box;
5364 }
5365
5366 updateClipFromPath() {
5367 const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
5368
5369 this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
5370 }
5371
5372 startNewPathAndClipBox(box) {
5373 this.clipBox = box;
5374 this.minX = Infinity;
5375 this.minY = Infinity;
5376 this.maxX = 0;
5377 this.maxY = 0;
5378 }
5379
5380 getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5381 return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
5382 }
5383
5384}
5385
5386function putBinaryImageData(ctx, imgData, transferMaps = null) {
5387 if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
5388 ctx.putImageData(imgData, 0, 0);
5389 return;
5390 }
5391
5392 const height = imgData.height,
5393 width = imgData.width;
5394 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5395 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5396 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5397 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5398 let srcPos = 0,
5399 destPos;
5400 const src = imgData.data;
5401 const dest = chunkImgData.data;
5402 let i, j, thisChunkHeight, elemsInThisChunk;
5403 let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
5404
5405 if (transferMaps) {
5406 switch (transferMaps.length) {
5407 case 1:
5408 transferMapRed = transferMaps[0];
5409 transferMapGreen = transferMaps[0];
5410 transferMapBlue = transferMaps[0];
5411 transferMapGray = transferMaps[0];
5412 break;
5413
5414 case 4:
5415 transferMapRed = transferMaps[0];
5416 transferMapGreen = transferMaps[1];
5417 transferMapBlue = transferMaps[2];
5418 transferMapGray = transferMaps[3];
5419 break;
5420 }
5421 }
5422
5423 if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
5424 const srcLength = src.byteLength;
5425 const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
5426 const dest32DataLength = dest32.length;
5427 const fullSrcDiff = width + 7 >> 3;
5428 let white = 0xffffffff;
5429 let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
5430
5431 if (transferMapGray) {
5432 if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
5433 [white, black] = [black, white];
5434 }
5435 }
5436
5437 for (i = 0; i < totalChunks; i++) {
5438 thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5439 destPos = 0;
5440
5441 for (j = 0; j < thisChunkHeight; j++) {
5442 const srcDiff = srcLength - srcPos;
5443 let k = 0;
5444 const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
5445 const kEndUnrolled = kEnd & ~7;
5446 let mask = 0;
5447 let srcByte = 0;
5448
5449 for (; k < kEndUnrolled; k += 8) {
5450 srcByte = src[srcPos++];
5451 dest32[destPos++] = srcByte & 128 ? white : black;
5452 dest32[destPos++] = srcByte & 64 ? white : black;
5453 dest32[destPos++] = srcByte & 32 ? white : black;
5454 dest32[destPos++] = srcByte & 16 ? white : black;
5455 dest32[destPos++] = srcByte & 8 ? white : black;
5456 dest32[destPos++] = srcByte & 4 ? white : black;
5457 dest32[destPos++] = srcByte & 2 ? white : black;
5458 dest32[destPos++] = srcByte & 1 ? white : black;
5459 }
5460
5461 for (; k < kEnd; k++) {
5462 if (mask === 0) {
5463 srcByte = src[srcPos++];
5464 mask = 128;
5465 }
5466
5467 dest32[destPos++] = srcByte & mask ? white : black;
5468 mask >>= 1;
5469 }
5470 }
5471
5472 while (destPos < dest32DataLength) {
5473 dest32[destPos++] = 0;
5474 }
5475
5476 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5477 }
5478 } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
5479 const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5480 j = 0;
5481 elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
5482
5483 for (i = 0; i < fullChunks; i++) {
5484 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5485 srcPos += elemsInThisChunk;
5486
5487 if (hasTransferMaps) {
5488 for (let k = 0; k < elemsInThisChunk; k += 4) {
5489 if (transferMapRed) {
5490 dest[k + 0] = transferMapRed[dest[k + 0]];
5491 }
5492
5493 if (transferMapGreen) {
5494 dest[k + 1] = transferMapGreen[dest[k + 1]];
5495 }
5496
5497 if (transferMapBlue) {
5498 dest[k + 2] = transferMapBlue[dest[k + 2]];
5499 }
5500 }
5501 }
5502
5503 ctx.putImageData(chunkImgData, 0, j);
5504 j += FULL_CHUNK_HEIGHT;
5505 }
5506
5507 if (i < totalChunks) {
5508 elemsInThisChunk = width * partialChunkHeight * 4;
5509 dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5510
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
5517 if (transferMapGreen) {
5518 dest[k + 1] = transferMapGreen[dest[k + 1]];
5519 }
5520
5521 if (transferMapBlue) {
5522 dest[k + 2] = transferMapBlue[dest[k + 2]];
5523 }
5524 }
5525 }
5526
5527 ctx.putImageData(chunkImgData, 0, j);
5528 }
5529 } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
5530 const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5531 thisChunkHeight = FULL_CHUNK_HEIGHT;
5532 elemsInThisChunk = width * thisChunkHeight;
5533
5534 for (i = 0; i < totalChunks; i++) {
5535 if (i >= fullChunks) {
5536 thisChunkHeight = partialChunkHeight;
5537 elemsInThisChunk = width * thisChunkHeight;
5538 }
5539
5540 destPos = 0;
5541
5542 for (j = elemsInThisChunk; j--;) {
5543 dest[destPos++] = src[srcPos++];
5544 dest[destPos++] = src[srcPos++];
5545 dest[destPos++] = src[srcPos++];
5546 dest[destPos++] = 255;
5547 }
5548
5549 if (hasTransferMaps) {
5550 for (let k = 0; k < destPos; k += 4) {
5551 if (transferMapRed) {
5552 dest[k + 0] = transferMapRed[dest[k + 0]];
5553 }
5554
5555 if (transferMapGreen) {
5556 dest[k + 1] = transferMapGreen[dest[k + 1]];
5557 }
5558
5559 if (transferMapBlue) {
5560 dest[k + 2] = transferMapBlue[dest[k + 2]];
5561 }
5562 }
5563 }
5564
5565 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5566 }
5567 } else {
5568 throw new Error(`bad image kind: ${imgData.kind}`);
5569 }
5570}
5571
5572function putBinaryImageMask(ctx, imgData) {
5573 const height = imgData.height,
5574 width = imgData.width;
5575 const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5576 const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5577 const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5578 const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5579 let srcPos = 0;
5580 const src = imgData.data;
5581 const dest = chunkImgData.data;
5582
5583 for (let i = 0; i < totalChunks; i++) {
5584 const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5585 let destPos = 3;
5586
5587 for (let j = 0; j < thisChunkHeight; j++) {
5588 let elem,
5589 mask = 0;
5590
5591 for (let k = 0; k < width; k++) {
5592 if (!mask) {
5593 elem = src[srcPos++];
5594 mask = 128;
5595 }
5596
5597 dest[destPos] = elem & mask ? 0 : 255;
5598 destPos += 4;
5599 mask >>= 1;
5600 }
5601 }
5602
5603 ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5604 }
5605}
5606
5607function copyCtxState(sourceCtx, destCtx) {
5608 const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
5609
5610 for (let i = 0, ii = properties.length; i < ii; i++) {
5611 const property = properties[i];
5612
5613 if (sourceCtx[property] !== undefined) {
5614 destCtx[property] = sourceCtx[property];
5615 }
5616 }
5617
5618 if (sourceCtx.setLineDash !== undefined) {
5619 destCtx.setLineDash(sourceCtx.getLineDash());
5620 destCtx.lineDashOffset = sourceCtx.lineDashOffset;
5621 }
5622}
5623
5624function resetCtxToDefault(ctx) {
5625 ctx.strokeStyle = "#000000";
5626 ctx.fillStyle = "#000000";
5627 ctx.fillRule = "nonzero";
5628 ctx.globalAlpha = 1;
5629 ctx.lineWidth = 1;
5630 ctx.lineCap = "butt";
5631 ctx.lineJoin = "miter";
5632 ctx.miterLimit = 10;
5633 ctx.globalCompositeOperation = "source-over";
5634 ctx.font = "10px sans-serif";
5635
5636 if (ctx.setLineDash !== undefined) {
5637 ctx.setLineDash([]);
5638 ctx.lineDashOffset = 0;
5639 }
5640}
5641
5642function composeSMaskBackdrop(bytes, r0, g0, b0) {
5643 const length = bytes.length;
5644
5645 for (let i = 3; i < length; i += 4) {
5646 const alpha = bytes[i];
5647
5648 if (alpha === 0) {
5649 bytes[i - 3] = r0;
5650 bytes[i - 2] = g0;
5651 bytes[i - 1] = b0;
5652 } else if (alpha < 255) {
5653 const alpha_ = 255 - alpha;
5654 bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
5655 bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
5656 bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
5657 }
5658 }
5659}
5660
5661function composeSMaskAlpha(maskData, layerData, transferMap) {
5662 const length = maskData.length;
5663 const scale = 1 / 255;
5664
5665 for (let i = 3; i < length; i += 4) {
5666 const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
5667 layerData[i] = layerData[i] * alpha * scale | 0;
5668 }
5669}
5670
5671function composeSMaskLuminosity(maskData, layerData, transferMap) {
5672 const length = maskData.length;
5673
5674 for (let i = 3; i < length; i += 4) {
5675 const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
5676 layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
5677 }
5678}
5679
5680function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
5681 const hasBackdrop = !!backdrop;
5682 const r0 = hasBackdrop ? backdrop[0] : 0;
5683 const g0 = hasBackdrop ? backdrop[1] : 0;
5684 const b0 = hasBackdrop ? backdrop[2] : 0;
5685 let composeFn;
5686
5687 if (subtype === "Luminosity") {
5688 composeFn = composeSMaskLuminosity;
5689 } else {
5690 composeFn = composeSMaskAlpha;
5691 }
5692
5693 const PIXELS_TO_PROCESS = 1048576;
5694 const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
5695
5696 for (let row = 0; row < height; row += chunkSize) {
5697 const chunkHeight = Math.min(chunkSize, height - row);
5698 const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
5699 const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
5700
5701 if (hasBackdrop) {
5702 composeSMaskBackdrop(maskData.data, r0, g0, b0);
5703 }
5704
5705 composeFn(maskData.data, layerData.data, transferMap);
5706 layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
5707 }
5708}
5709
5710function composeSMask(ctx, smask, layerCtx, layerBox) {
5711 const layerOffsetX = layerBox[0];
5712 const layerOffsetY = layerBox[1];
5713 const layerWidth = layerBox[2] - layerOffsetX;
5714 const layerHeight = layerBox[3] - layerOffsetY;
5715
5716 if (layerWidth === 0 || layerHeight === 0) {
5717 return;
5718 }
5719
5720 genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
5721 ctx.save();
5722 ctx.globalAlpha = 1;
5723 ctx.globalCompositeOperation = "source-over";
5724 ctx.setTransform(1, 0, 0, 1, 0, 0);
5725 ctx.drawImage(layerCtx.canvas, 0, 0);
5726 ctx.restore();
5727}
5728
5729function getImageSmoothingEnabled(transform, interpolate) {
5730 const scale = _util.Util.singularValueDecompose2dScale(transform);
5731
5732 scale[0] = Math.fround(scale[0]);
5733 scale[1] = Math.fround(scale[1]);
5734 const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
5735
5736 if (interpolate !== undefined) {
5737 return interpolate;
5738 } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
5739 return true;
5740 }
5741
5742 return false;
5743}
5744
5745const LINE_CAP_STYLES = ["butt", "round", "square"];
5746const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
5747const NORMAL_CLIP = {};
5748const EO_CLIP = {};
5749
5750class CanvasGraphics {
5751 constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig, annotationCanvasMap) {
5752 this.ctx = canvasCtx;
5753 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
5754 this.stateStack = [];
5755 this.pendingClip = null;
5756 this.pendingEOFill = false;
5757 this.res = null;
5758 this.xobjs = null;
5759 this.commonObjs = commonObjs;
5760 this.objs = objs;
5761 this.canvasFactory = canvasFactory;
5762 this.imageLayer = imageLayer;
5763 this.groupStack = [];
5764 this.processingType3 = null;
5765 this.baseTransform = null;
5766 this.baseTransformStack = [];
5767 this.groupLevel = 0;
5768 this.smaskStack = [];
5769 this.smaskCounter = 0;
5770 this.tempSMask = null;
5771 this.suspendedCtx = null;
5772 this.contentVisible = true;
5773 this.markedContentStack = [];
5774 this.optionalContentConfig = optionalContentConfig;
5775 this.cachedCanvases = new CachedCanvases(this.canvasFactory);
5776 this.cachedPatterns = new Map();
5777 this.annotationCanvasMap = annotationCanvasMap;
5778 this.viewportScale = 1;
5779 this.outputScaleX = 1;
5780 this.outputScaleY = 1;
5781
5782 if (canvasCtx) {
5783 addContextCurrentTransform(canvasCtx);
5784 }
5785
5786 this._cachedGetSinglePixelWidth = null;
5787 }
5788
5789 beginDrawing({
5790 transform,
5791 viewport,
5792 transparency = false,
5793 background = null
5794 }) {
5795 const width = this.ctx.canvas.width;
5796 const height = this.ctx.canvas.height;
5797 this.ctx.save();
5798 this.ctx.fillStyle = background || "rgb(255, 255, 255)";
5799 this.ctx.fillRect(0, 0, width, height);
5800 this.ctx.restore();
5801
5802 if (transparency) {
5803 const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
5804 this.compositeCtx = this.ctx;
5805 this.transparentCanvas = transparentCanvas.canvas;
5806 this.ctx = transparentCanvas.context;
5807 this.ctx.save();
5808 this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
5809 }
5810
5811 this.ctx.save();
5812 resetCtxToDefault(this.ctx);
5813
5814 if (transform) {
5815 this.ctx.transform.apply(this.ctx, transform);
5816 this.outputScaleX = transform[0];
5817 this.outputScaleY = transform[0];
5818 }
5819
5820 this.ctx.transform.apply(this.ctx, viewport.transform);
5821 this.viewportScale = viewport.scale;
5822 this.baseTransform = this.ctx.mozCurrentTransform.slice();
5823 this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
5824
5825 if (this.imageLayer) {
5826 this.imageLayer.beginLayout();
5827 }
5828 }
5829
5830 executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
5831 const argsArray = operatorList.argsArray;
5832 const fnArray = operatorList.fnArray;
5833 let i = executionStartIdx || 0;
5834 const argsArrayLen = argsArray.length;
5835
5836 if (argsArrayLen === i) {
5837 return i;
5838 }
5839
5840 const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
5841 const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
5842 let steps = 0;
5843 const commonObjs = this.commonObjs;
5844 const objs = this.objs;
5845 let fnId;
5846
5847 while (true) {
5848 if (stepper !== undefined && i === stepper.nextBreakPoint) {
5849 stepper.breakIt(i, continueCallback);
5850 return i;
5851 }
5852
5853 fnId = fnArray[i];
5854
5855 if (fnId !== _util.OPS.dependency) {
5856 this[fnId].apply(this, argsArray[i]);
5857 } else {
5858 for (const depObjId of argsArray[i]) {
5859 const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
5860
5861 if (!objsPool.has(depObjId)) {
5862 objsPool.get(depObjId, continueCallback);
5863 return i;
5864 }
5865 }
5866 }
5867
5868 i++;
5869
5870 if (i === argsArrayLen) {
5871 return i;
5872 }
5873
5874 if (chunkOperations && ++steps > EXECUTION_STEPS) {
5875 if (Date.now() > endTime) {
5876 continueCallback();
5877 return i;
5878 }
5879
5880 steps = 0;
5881 }
5882 }
5883 }
5884
5885 endDrawing() {
5886 while (this.stateStack.length || this.current.activeSMask !== null) {
5887 this.restore();
5888 }
5889
5890 this.ctx.restore();
5891
5892 if (this.transparentCanvas) {
5893 this.ctx = this.compositeCtx;
5894 this.ctx.save();
5895 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
5896 this.ctx.drawImage(this.transparentCanvas, 0, 0);
5897 this.ctx.restore();
5898 this.transparentCanvas = null;
5899 }
5900
5901 this.cachedCanvases.clear();
5902 this.cachedPatterns.clear();
5903
5904 if (this.imageLayer) {
5905 this.imageLayer.endLayout();
5906 }
5907 }
5908
5909 _scaleImage(img, inverseTransform) {
5910 const width = img.width;
5911 const height = img.height;
5912 let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
5913 let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
5914 let paintWidth = width,
5915 paintHeight = height;
5916 let tmpCanvasId = "prescale1";
5917 let tmpCanvas, tmpCtx;
5918
5919 while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
5920 let newWidth = paintWidth,
5921 newHeight = paintHeight;
5922
5923 if (widthScale > 2 && paintWidth > 1) {
5924 newWidth = Math.ceil(paintWidth / 2);
5925 widthScale /= paintWidth / newWidth;
5926 }
5927
5928 if (heightScale > 2 && paintHeight > 1) {
5929 newHeight = Math.ceil(paintHeight / 2);
5930 heightScale /= paintHeight / newHeight;
5931 }
5932
5933 tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
5934 tmpCtx = tmpCanvas.context;
5935 tmpCtx.clearRect(0, 0, newWidth, newHeight);
5936 tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
5937 img = tmpCanvas.canvas;
5938 paintWidth = newWidth;
5939 paintHeight = newHeight;
5940 tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
5941 }
5942
5943 return {
5944 img,
5945 paintWidth,
5946 paintHeight
5947 };
5948 }
5949
5950 _createMaskCanvas(img) {
5951 const ctx = this.ctx;
5952 const width = img.width,
5953 height = img.height;
5954 const fillColor = this.current.fillColor;
5955 const isPatternFill = this.current.patternFill;
5956 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
5957 const maskCtx = maskCanvas.context;
5958 putBinaryImageMask(maskCtx, img);
5959 const objToCanvas = ctx.mozCurrentTransform;
5960
5961 let maskToCanvas = _util.Util.transform(objToCanvas, [1 / width, 0, 0, -1 / height, 0, 0]);
5962
5963 maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
5964
5965 const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
5966
5967 const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
5968
5969 const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
5970
5971 const drawnWidth = Math.ceil(rect[2] - rect[0]);
5972 const drawnHeight = Math.ceil(rect[3] - rect[1]);
5973 const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true);
5974 const fillCtx = fillCanvas.context;
5975 const offsetX = Math.min(cord1[0], cord2[0]);
5976 const offsetY = Math.min(cord1[1], cord2[1]);
5977 fillCtx.translate(-offsetX, -offsetY);
5978 fillCtx.transform.apply(fillCtx, maskToCanvas);
5979
5980 const scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
5981
5982 fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(fillCtx.mozCurrentTransform, img.interpolate);
5983 fillCtx.drawImage(scaled.img, 0, 0, scaled.img.width, scaled.img.height, 0, 0, width, height);
5984 fillCtx.globalCompositeOperation = "source-in";
5985
5986 const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]);
5987
5988 fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
5989 fillCtx.fillRect(0, 0, width, height);
5990 return {
5991 canvas: fillCanvas.canvas,
5992 offsetX: Math.round(offsetX),
5993 offsetY: Math.round(offsetY)
5994 };
5995 }
5996
5997 setLineWidth(width) {
5998 this.current.lineWidth = width;
5999 this.ctx.lineWidth = width;
6000 }
6001
6002 setLineCap(style) {
6003 this.ctx.lineCap = LINE_CAP_STYLES[style];
6004 }
6005
6006 setLineJoin(style) {
6007 this.ctx.lineJoin = LINE_JOIN_STYLES[style];
6008 }
6009
6010 setMiterLimit(limit) {
6011 this.ctx.miterLimit = limit;
6012 }
6013
6014 setDash(dashArray, dashPhase) {
6015 const ctx = this.ctx;
6016
6017 if (ctx.setLineDash !== undefined) {
6018 ctx.setLineDash(dashArray);
6019 ctx.lineDashOffset = dashPhase;
6020 }
6021 }
6022
6023 setRenderingIntent(intent) {}
6024
6025 setFlatness(flatness) {}
6026
6027 setGState(states) {
6028 for (let i = 0, ii = states.length; i < ii; i++) {
6029 const state = states[i];
6030 const key = state[0];
6031 const value = state[1];
6032
6033 switch (key) {
6034 case "LW":
6035 this.setLineWidth(value);
6036 break;
6037
6038 case "LC":
6039 this.setLineCap(value);
6040 break;
6041
6042 case "LJ":
6043 this.setLineJoin(value);
6044 break;
6045
6046 case "ML":
6047 this.setMiterLimit(value);
6048 break;
6049
6050 case "D":
6051 this.setDash(value[0], value[1]);
6052 break;
6053
6054 case "RI":
6055 this.setRenderingIntent(value);
6056 break;
6057
6058 case "FL":
6059 this.setFlatness(value);
6060 break;
6061
6062 case "Font":
6063 this.setFont(value[0], value[1]);
6064 break;
6065
6066 case "CA":
6067 this.current.strokeAlpha = state[1];
6068 break;
6069
6070 case "ca":
6071 this.current.fillAlpha = state[1];
6072 this.ctx.globalAlpha = state[1];
6073 break;
6074
6075 case "BM":
6076 this.ctx.globalCompositeOperation = value;
6077 break;
6078
6079 case "SMask":
6080 this.current.activeSMask = value ? this.tempSMask : null;
6081 this.tempSMask = null;
6082 this.checkSMaskState();
6083 break;
6084
6085 case "TR":
6086 this.current.transferMaps = value;
6087 }
6088 }
6089 }
6090
6091 checkSMaskState() {
6092 const inSMaskMode = !!this.suspendedCtx;
6093
6094 if (this.current.activeSMask && !inSMaskMode) {
6095 this.beginSMaskMode();
6096 } else if (!this.current.activeSMask && inSMaskMode) {
6097 this.endSMaskMode();
6098 }
6099 }
6100
6101 beginSMaskMode() {
6102 if (this.suspendedCtx) {
6103 throw new Error("beginSMaskMode called while already in smask mode");
6104 }
6105
6106 const drawnWidth = this.ctx.canvas.width;
6107 const drawnHeight = this.ctx.canvas.height;
6108 const cacheId = "smaskGroupAt" + this.groupLevel;
6109 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
6110 this.suspendedCtx = this.ctx;
6111 this.ctx = scratchCanvas.context;
6112 const ctx = this.ctx;
6113 ctx.setTransform.apply(ctx, this.suspendedCtx.mozCurrentTransform);
6114 copyCtxState(this.suspendedCtx, ctx);
6115 mirrorContextOperations(ctx, this.suspendedCtx);
6116 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
6117 }
6118
6119 endSMaskMode() {
6120 if (!this.suspendedCtx) {
6121 throw new Error("endSMaskMode called while not in smask mode");
6122 }
6123
6124 this.ctx._removeMirroring();
6125
6126 copyCtxState(this.ctx, this.suspendedCtx);
6127 this.ctx = this.suspendedCtx;
6128 this.current.activeSMask = null;
6129 this.suspendedCtx = null;
6130 }
6131
6132 compose(dirtyBox) {
6133 if (!this.current.activeSMask) {
6134 return;
6135 }
6136
6137 if (!dirtyBox) {
6138 dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
6139 } else {
6140 dirtyBox[0] = Math.floor(dirtyBox[0]);
6141 dirtyBox[1] = Math.floor(dirtyBox[1]);
6142 dirtyBox[2] = Math.ceil(dirtyBox[2]);
6143 dirtyBox[3] = Math.ceil(dirtyBox[3]);
6144 }
6145
6146 const smask = this.current.activeSMask;
6147 const suspendedCtx = this.suspendedCtx;
6148 composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
6149 this.ctx.save();
6150 this.ctx.setTransform(1, 0, 0, 1, 0, 0);
6151 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
6152 this.ctx.restore();
6153 }
6154
6155 save() {
6156 this.ctx.save();
6157 const old = this.current;
6158 this.stateStack.push(old);
6159 this.current = old.clone();
6160 }
6161
6162 restore() {
6163 if (this.stateStack.length === 0 && this.current.activeSMask) {
6164 this.endSMaskMode();
6165 }
6166
6167 if (this.stateStack.length !== 0) {
6168 this.current = this.stateStack.pop();
6169 this.ctx.restore();
6170 this.checkSMaskState();
6171 this.pendingClip = null;
6172 this._cachedGetSinglePixelWidth = null;
6173 }
6174 }
6175
6176 transform(a, b, c, d, e, f) {
6177 this.ctx.transform(a, b, c, d, e, f);
6178 this._cachedGetSinglePixelWidth = null;
6179 }
6180
6181 constructPath(ops, args) {
6182 const ctx = this.ctx;
6183 const current = this.current;
6184 let x = current.x,
6185 y = current.y;
6186 let startX, startY;
6187
6188 for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
6189 switch (ops[i] | 0) {
6190 case _util.OPS.rectangle:
6191 x = args[j++];
6192 y = args[j++];
6193 const width = args[j++];
6194 const height = args[j++];
6195 const xw = x + width;
6196 const yh = y + height;
6197 ctx.moveTo(x, y);
6198
6199 if (width === 0 || height === 0) {
6200 ctx.lineTo(xw, yh);
6201 } else {
6202 ctx.lineTo(xw, y);
6203 ctx.lineTo(xw, yh);
6204 ctx.lineTo(x, yh);
6205 }
6206
6207 current.updatePathMinMax(ctx.mozCurrentTransform, x, y);
6208 current.updatePathMinMax(ctx.mozCurrentTransform, xw, yh);
6209 ctx.closePath();
6210 break;
6211
6212 case _util.OPS.moveTo:
6213 x = args[j++];
6214 y = args[j++];
6215 ctx.moveTo(x, y);
6216 current.updatePathMinMax(ctx.mozCurrentTransform, x, y);
6217 break;
6218
6219 case _util.OPS.lineTo:
6220 x = args[j++];
6221 y = args[j++];
6222 ctx.lineTo(x, y);
6223 current.updatePathMinMax(ctx.mozCurrentTransform, x, y);
6224 break;
6225
6226 case _util.OPS.curveTo:
6227 startX = x;
6228 startY = y;
6229 x = args[j + 4];
6230 y = args[j + 5];
6231 ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
6232 current.updateCurvePathMinMax(ctx.mozCurrentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
6233 j += 6;
6234 break;
6235
6236 case _util.OPS.curveTo2:
6237 startX = x;
6238 startY = y;
6239 ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
6240 current.updateCurvePathMinMax(ctx.mozCurrentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
6241 x = args[j + 2];
6242 y = args[j + 3];
6243 j += 4;
6244 break;
6245
6246 case _util.OPS.curveTo3:
6247 startX = x;
6248 startY = y;
6249 x = args[j + 2];
6250 y = args[j + 3];
6251 ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
6252 current.updateCurvePathMinMax(ctx.mozCurrentTransform, startX, startY, args[j], args[j + 1], x, y, x, y);
6253 j += 4;
6254 break;
6255
6256 case _util.OPS.closePath:
6257 ctx.closePath();
6258 break;
6259 }
6260 }
6261
6262 current.setCurrentPoint(x, y);
6263 }
6264
6265 closePath() {
6266 this.ctx.closePath();
6267 }
6268
6269 stroke(consumePath) {
6270 consumePath = typeof consumePath !== "undefined" ? consumePath : true;
6271 const ctx = this.ctx;
6272 const strokeColor = this.current.strokeColor;
6273 ctx.globalAlpha = this.current.strokeAlpha;
6274
6275 if (this.contentVisible) {
6276 if (typeof strokeColor === "object" && strokeColor?.getPattern) {
6277 const lineWidth = this.getSinglePixelWidth();
6278 ctx.save();
6279 ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.STROKE);
6280 ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
6281 ctx.stroke();
6282 ctx.restore();
6283 } else {
6284 const lineWidth = this.getSinglePixelWidth();
6285
6286 if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
6287 ctx.save();
6288 ctx.resetTransform();
6289 ctx.lineWidth = Math.round(this._combinedScaleFactor);
6290 ctx.stroke();
6291 ctx.restore();
6292 } else {
6293 ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
6294 ctx.stroke();
6295 }
6296 }
6297 }
6298
6299 if (consumePath) {
6300 this.consumePath(this.current.getClippedPathBoundingBox());
6301 }
6302
6303 ctx.globalAlpha = this.current.fillAlpha;
6304 }
6305
6306 closeStroke() {
6307 this.closePath();
6308 this.stroke();
6309 }
6310
6311 fill(consumePath) {
6312 consumePath = typeof consumePath !== "undefined" ? consumePath : true;
6313 const ctx = this.ctx;
6314 const fillColor = this.current.fillColor;
6315 const isPatternFill = this.current.patternFill;
6316 let needRestore = false;
6317
6318 if (isPatternFill) {
6319 ctx.save();
6320 ctx.fillStyle = fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
6321 needRestore = true;
6322 }
6323
6324 const intersect = this.current.getClippedPathBoundingBox();
6325
6326 if (this.contentVisible && intersect !== null) {
6327 if (this.pendingEOFill) {
6328 ctx.fill("evenodd");
6329 this.pendingEOFill = false;
6330 } else {
6331 ctx.fill();
6332 }
6333 }
6334
6335 if (needRestore) {
6336 ctx.restore();
6337 }
6338
6339 if (consumePath) {
6340 this.consumePath(intersect);
6341 }
6342 }
6343
6344 eoFill() {
6345 this.pendingEOFill = true;
6346 this.fill();
6347 }
6348
6349 fillStroke() {
6350 this.fill(false);
6351 this.stroke(false);
6352 this.consumePath();
6353 }
6354
6355 eoFillStroke() {
6356 this.pendingEOFill = true;
6357 this.fillStroke();
6358 }
6359
6360 closeFillStroke() {
6361 this.closePath();
6362 this.fillStroke();
6363 }
6364
6365 closeEOFillStroke() {
6366 this.pendingEOFill = true;
6367 this.closePath();
6368 this.fillStroke();
6369 }
6370
6371 endPath() {
6372 this.consumePath();
6373 }
6374
6375 clip() {
6376 this.pendingClip = NORMAL_CLIP;
6377 }
6378
6379 eoClip() {
6380 this.pendingClip = EO_CLIP;
6381 }
6382
6383 beginText() {
6384 this.current.textMatrix = _util.IDENTITY_MATRIX;
6385 this.current.textMatrixScale = 1;
6386 this.current.x = this.current.lineX = 0;
6387 this.current.y = this.current.lineY = 0;
6388 }
6389
6390 endText() {
6391 const paths = this.pendingTextPaths;
6392 const ctx = this.ctx;
6393
6394 if (paths === undefined) {
6395 ctx.beginPath();
6396 return;
6397 }
6398
6399 ctx.save();
6400 ctx.beginPath();
6401
6402 for (let i = 0; i < paths.length; i++) {
6403 const path = paths[i];
6404 ctx.setTransform.apply(ctx, path.transform);
6405 ctx.translate(path.x, path.y);
6406 path.addToPath(ctx, path.fontSize);
6407 }
6408
6409 ctx.restore();
6410 ctx.clip();
6411 ctx.beginPath();
6412 delete this.pendingTextPaths;
6413 }
6414
6415 setCharSpacing(spacing) {
6416 this.current.charSpacing = spacing;
6417 }
6418
6419 setWordSpacing(spacing) {
6420 this.current.wordSpacing = spacing;
6421 }
6422
6423 setHScale(scale) {
6424 this.current.textHScale = scale / 100;
6425 }
6426
6427 setLeading(leading) {
6428 this.current.leading = -leading;
6429 }
6430
6431 setFont(fontRefName, size) {
6432 const fontObj = this.commonObjs.get(fontRefName);
6433 const current = this.current;
6434
6435 if (!fontObj) {
6436 throw new Error(`Can't find font for ${fontRefName}`);
6437 }
6438
6439 current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6440
6441 if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
6442 (0, _util.warn)("Invalid font matrix for font " + fontRefName);
6443 }
6444
6445 if (size < 0) {
6446 size = -size;
6447 current.fontDirection = -1;
6448 } else {
6449 current.fontDirection = 1;
6450 }
6451
6452 this.current.font = fontObj;
6453 this.current.fontSize = size;
6454
6455 if (fontObj.isType3Font) {
6456 return;
6457 }
6458
6459 const name = fontObj.loadedName || "sans-serif";
6460 let bold = "normal";
6461
6462 if (fontObj.black) {
6463 bold = "900";
6464 } else if (fontObj.bold) {
6465 bold = "bold";
6466 }
6467
6468 const italic = fontObj.italic ? "italic" : "normal";
6469 const typeface = `"${name}", ${fontObj.fallbackName}`;
6470 let browserFontSize = size;
6471
6472 if (size < MIN_FONT_SIZE) {
6473 browserFontSize = MIN_FONT_SIZE;
6474 } else if (size > MAX_FONT_SIZE) {
6475 browserFontSize = MAX_FONT_SIZE;
6476 }
6477
6478 this.current.fontSizeScale = size / browserFontSize;
6479 this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
6480 }
6481
6482 setTextRenderingMode(mode) {
6483 this.current.textRenderingMode = mode;
6484 }
6485
6486 setTextRise(rise) {
6487 this.current.textRise = rise;
6488 }
6489
6490 moveText(x, y) {
6491 this.current.x = this.current.lineX += x;
6492 this.current.y = this.current.lineY += y;
6493 }
6494
6495 setLeadingMoveText(x, y) {
6496 this.setLeading(-y);
6497 this.moveText(x, y);
6498 }
6499
6500 setTextMatrix(a, b, c, d, e, f) {
6501 this.current.textMatrix = [a, b, c, d, e, f];
6502 this.current.textMatrixScale = Math.hypot(a, b);
6503 this.current.x = this.current.lineX = 0;
6504 this.current.y = this.current.lineY = 0;
6505 }
6506
6507 nextLine() {
6508 this.moveText(0, this.current.leading);
6509 }
6510
6511 paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
6512 const ctx = this.ctx;
6513 const current = this.current;
6514 const font = current.font;
6515 const textRenderingMode = current.textRenderingMode;
6516 const fontSize = current.fontSize / current.fontSizeScale;
6517 const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6518 const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
6519 const patternFill = current.patternFill && !font.missingFile;
6520 let addToPath;
6521
6522 if (font.disableFontFace || isAddToPathSet || patternFill) {
6523 addToPath = font.getPathGenerator(this.commonObjs, character);
6524 }
6525
6526 if (font.disableFontFace || patternFill) {
6527 ctx.save();
6528 ctx.translate(x, y);
6529 ctx.beginPath();
6530 addToPath(ctx, fontSize);
6531
6532 if (patternTransform) {
6533 ctx.setTransform.apply(ctx, patternTransform);
6534 }
6535
6536 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6537 ctx.fill();
6538 }
6539
6540 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6541 if (resetLineWidthToOne) {
6542 ctx.resetTransform();
6543 ctx.lineWidth = Math.round(this._combinedScaleFactor);
6544 }
6545
6546 ctx.stroke();
6547 }
6548
6549 ctx.restore();
6550 } else {
6551 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6552 ctx.fillText(character, x, y);
6553 }
6554
6555 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6556 if (resetLineWidthToOne) {
6557 ctx.save();
6558 ctx.moveTo(x, y);
6559 ctx.resetTransform();
6560 ctx.lineWidth = Math.round(this._combinedScaleFactor);
6561 ctx.strokeText(character, 0, 0);
6562 ctx.restore();
6563 } else {
6564 ctx.strokeText(character, x, y);
6565 }
6566 }
6567 }
6568
6569 if (isAddToPathSet) {
6570 const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
6571 paths.push({
6572 transform: ctx.mozCurrentTransform,
6573 x,
6574 y,
6575 fontSize,
6576 addToPath
6577 });
6578 }
6579 }
6580
6581 get isFontSubpixelAAEnabled() {
6582 const {
6583 context: ctx
6584 } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
6585 ctx.scale(1.5, 1);
6586 ctx.fillText("I", 0, 10);
6587 const data = ctx.getImageData(0, 0, 10, 10).data;
6588 let enabled = false;
6589
6590 for (let i = 3; i < data.length; i += 4) {
6591 if (data[i] > 0 && data[i] < 255) {
6592 enabled = true;
6593 break;
6594 }
6595 }
6596
6597 return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
6598 }
6599
6600 showText(glyphs) {
6601 const current = this.current;
6602 const font = current.font;
6603
6604 if (font.isType3Font) {
6605 return this.showType3Text(glyphs);
6606 }
6607
6608 const fontSize = current.fontSize;
6609
6610 if (fontSize === 0) {
6611 return undefined;
6612 }
6613
6614 const ctx = this.ctx;
6615 const fontSizeScale = current.fontSizeScale;
6616 const charSpacing = current.charSpacing;
6617 const wordSpacing = current.wordSpacing;
6618 const fontDirection = current.fontDirection;
6619 const textHScale = current.textHScale * fontDirection;
6620 const glyphsLength = glyphs.length;
6621 const vertical = font.vertical;
6622 const spacingDir = vertical ? 1 : -1;
6623 const defaultVMetrics = font.defaultVMetrics;
6624 const widthAdvanceScale = fontSize * current.fontMatrix[0];
6625 const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
6626 ctx.save();
6627 ctx.transform.apply(ctx, current.textMatrix);
6628 ctx.translate(current.x, current.y + current.textRise);
6629
6630 if (fontDirection > 0) {
6631 ctx.scale(textHScale, -1);
6632 } else {
6633 ctx.scale(textHScale, 1);
6634 }
6635
6636 let patternTransform;
6637
6638 if (current.patternFill) {
6639 ctx.save();
6640 const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
6641 patternTransform = ctx.mozCurrentTransform;
6642 ctx.restore();
6643 ctx.fillStyle = pattern;
6644 }
6645
6646 let lineWidth = current.lineWidth;
6647 let resetLineWidthToOne = false;
6648 const scale = current.textMatrixScale;
6649
6650 if (scale === 0 || lineWidth === 0) {
6651 const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6652
6653 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6654 this._cachedGetSinglePixelWidth = null;
6655 lineWidth = this.getSinglePixelWidth();
6656 resetLineWidthToOne = lineWidth < 0;
6657 }
6658 } else {
6659 lineWidth /= scale;
6660 }
6661
6662 if (fontSizeScale !== 1.0) {
6663 ctx.scale(fontSizeScale, fontSizeScale);
6664 lineWidth /= fontSizeScale;
6665 }
6666
6667 ctx.lineWidth = lineWidth;
6668 let x = 0,
6669 i;
6670
6671 for (i = 0; i < glyphsLength; ++i) {
6672 const glyph = glyphs[i];
6673
6674 if ((0, _util.isNum)(glyph)) {
6675 x += spacingDir * glyph * fontSize / 1000;
6676 continue;
6677 }
6678
6679 let restoreNeeded = false;
6680 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6681 const character = glyph.fontChar;
6682 const accent = glyph.accent;
6683 let scaledX, scaledY;
6684 let width = glyph.width;
6685
6686 if (vertical) {
6687 const vmetric = glyph.vmetric || defaultVMetrics;
6688 const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
6689 const vy = vmetric[2] * widthAdvanceScale;
6690 width = vmetric ? -vmetric[0] : width;
6691 scaledX = vx / fontSizeScale;
6692 scaledY = (x + vy) / fontSizeScale;
6693 } else {
6694 scaledX = x / fontSizeScale;
6695 scaledY = 0;
6696 }
6697
6698 if (font.remeasure && width > 0) {
6699 const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
6700
6701 if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
6702 const characterScaleX = width / measuredWidth;
6703 restoreNeeded = true;
6704 ctx.save();
6705 ctx.scale(characterScaleX, 1);
6706 scaledX /= characterScaleX;
6707 } else if (width !== measuredWidth) {
6708 scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
6709 }
6710 }
6711
6712 if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
6713 if (simpleFillText && !accent) {
6714 ctx.fillText(character, scaledX, scaledY);
6715 } else {
6716 this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
6717
6718 if (accent) {
6719 const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
6720 const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
6721 this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
6722 }
6723 }
6724 }
6725
6726 let charWidth;
6727
6728 if (vertical) {
6729 charWidth = width * widthAdvanceScale - spacing * fontDirection;
6730 } else {
6731 charWidth = width * widthAdvanceScale + spacing * fontDirection;
6732 }
6733
6734 x += charWidth;
6735
6736 if (restoreNeeded) {
6737 ctx.restore();
6738 }
6739 }
6740
6741 if (vertical) {
6742 current.y -= x;
6743 } else {
6744 current.x += x * textHScale;
6745 }
6746
6747 ctx.restore();
6748 this.compose();
6749 return undefined;
6750 }
6751
6752 showType3Text(glyphs) {
6753 const ctx = this.ctx;
6754 const current = this.current;
6755 const font = current.font;
6756 const fontSize = current.fontSize;
6757 const fontDirection = current.fontDirection;
6758 const spacingDir = font.vertical ? 1 : -1;
6759 const charSpacing = current.charSpacing;
6760 const wordSpacing = current.wordSpacing;
6761 const textHScale = current.textHScale * fontDirection;
6762 const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6763 const glyphsLength = glyphs.length;
6764 const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
6765 let i, glyph, width, spacingLength;
6766
6767 if (isTextInvisible || fontSize === 0) {
6768 return;
6769 }
6770
6771 this._cachedGetSinglePixelWidth = null;
6772 ctx.save();
6773 ctx.transform.apply(ctx, current.textMatrix);
6774 ctx.translate(current.x, current.y);
6775 ctx.scale(textHScale, fontDirection);
6776
6777 for (i = 0; i < glyphsLength; ++i) {
6778 glyph = glyphs[i];
6779
6780 if ((0, _util.isNum)(glyph)) {
6781 spacingLength = spacingDir * glyph * fontSize / 1000;
6782 this.ctx.translate(spacingLength, 0);
6783 current.x += spacingLength * textHScale;
6784 continue;
6785 }
6786
6787 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6788 const operatorList = font.charProcOperatorList[glyph.operatorListId];
6789
6790 if (!operatorList) {
6791 (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
6792 continue;
6793 }
6794
6795 if (this.contentVisible) {
6796 this.processingType3 = glyph;
6797 this.save();
6798 ctx.scale(fontSize, fontSize);
6799 ctx.transform.apply(ctx, fontMatrix);
6800 this.executeOperatorList(operatorList);
6801 this.restore();
6802 }
6803
6804 const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
6805
6806 width = transformed[0] * fontSize + spacing;
6807 ctx.translate(width, 0);
6808 current.x += width * textHScale;
6809 }
6810
6811 ctx.restore();
6812 this.processingType3 = null;
6813 }
6814
6815 setCharWidth(xWidth, yWidth) {}
6816
6817 setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
6818 this.ctx.rect(llx, lly, urx - llx, ury - lly);
6819 this.clip();
6820 this.endPath();
6821 }
6822
6823 getColorN_Pattern(IR) {
6824 let pattern;
6825
6826 if (IR[0] === "TilingPattern") {
6827 const color = IR[1];
6828 const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
6829 const canvasGraphicsFactory = {
6830 createCanvasGraphics: ctx => {
6831 return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
6832 }
6833 };
6834 pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
6835 } else {
6836 pattern = this._getPattern(IR[1], IR[2]);
6837 }
6838
6839 return pattern;
6840 }
6841
6842 setStrokeColorN() {
6843 this.current.strokeColor = this.getColorN_Pattern(arguments);
6844 }
6845
6846 setFillColorN() {
6847 this.current.fillColor = this.getColorN_Pattern(arguments);
6848 this.current.patternFill = true;
6849 }
6850
6851 setStrokeRGBColor(r, g, b) {
6852 const color = _util.Util.makeHexColor(r, g, b);
6853
6854 this.ctx.strokeStyle = color;
6855 this.current.strokeColor = color;
6856 }
6857
6858 setFillRGBColor(r, g, b) {
6859 const color = _util.Util.makeHexColor(r, g, b);
6860
6861 this.ctx.fillStyle = color;
6862 this.current.fillColor = color;
6863 this.current.patternFill = false;
6864 }
6865
6866 _getPattern(objId, matrix = null) {
6867 let pattern;
6868
6869 if (this.cachedPatterns.has(objId)) {
6870 pattern = this.cachedPatterns.get(objId);
6871 } else {
6872 pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
6873 this.cachedPatterns.set(objId, pattern);
6874 }
6875
6876 if (matrix) {
6877 pattern.matrix = matrix;
6878 }
6879
6880 return pattern;
6881 }
6882
6883 shadingFill(objId) {
6884 if (!this.contentVisible) {
6885 return;
6886 }
6887
6888 const ctx = this.ctx;
6889 this.save();
6890
6891 const pattern = this._getPattern(objId);
6892
6893 ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.SHADING);
6894 const inv = ctx.mozCurrentTransformInverse;
6895
6896 if (inv) {
6897 const canvas = ctx.canvas;
6898 const width = canvas.width;
6899 const height = canvas.height;
6900
6901 const bl = _util.Util.applyTransform([0, 0], inv);
6902
6903 const br = _util.Util.applyTransform([0, height], inv);
6904
6905 const ul = _util.Util.applyTransform([width, 0], inv);
6906
6907 const ur = _util.Util.applyTransform([width, height], inv);
6908
6909 const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
6910 const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
6911 const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
6912 const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
6913 this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
6914 } else {
6915 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
6916 }
6917
6918 this.compose(this.current.getClippedPathBoundingBox());
6919 this.restore();
6920 }
6921
6922 beginInlineImage() {
6923 (0, _util.unreachable)("Should not call beginInlineImage");
6924 }
6925
6926 beginImageData() {
6927 (0, _util.unreachable)("Should not call beginImageData");
6928 }
6929
6930 paintFormXObjectBegin(matrix, bbox) {
6931 if (!this.contentVisible) {
6932 return;
6933 }
6934
6935 this.save();
6936 this.baseTransformStack.push(this.baseTransform);
6937
6938 if (Array.isArray(matrix) && matrix.length === 6) {
6939 this.transform.apply(this, matrix);
6940 }
6941
6942 this.baseTransform = this.ctx.mozCurrentTransform;
6943
6944 if (bbox) {
6945 const width = bbox[2] - bbox[0];
6946 const height = bbox[3] - bbox[1];
6947 this.ctx.rect(bbox[0], bbox[1], width, height);
6948 this.current.updatePathMinMax(this.ctx.mozCurrentTransform, bbox[0], bbox[1]);
6949 this.current.updatePathMinMax(this.ctx.mozCurrentTransform, bbox[2], bbox[3]);
6950 this.clip();
6951 this.endPath();
6952 }
6953 }
6954
6955 paintFormXObjectEnd() {
6956 if (!this.contentVisible) {
6957 return;
6958 }
6959
6960 this.restore();
6961 this.baseTransform = this.baseTransformStack.pop();
6962 }
6963
6964 beginGroup(group) {
6965 if (!this.contentVisible) {
6966 return;
6967 }
6968
6969 this.save();
6970 const suspendedCtx = this.suspendedCtx;
6971
6972 if (this.current.activeSMask) {
6973 this.suspendedCtx = null;
6974 this.current.activeSMask = null;
6975 }
6976
6977 const currentCtx = this.ctx;
6978
6979 if (!group.isolated) {
6980 (0, _util.info)("TODO: Support non-isolated groups.");
6981 }
6982
6983 if (group.knockout) {
6984 (0, _util.warn)("Knockout groups not supported.");
6985 }
6986
6987 const currentTransform = currentCtx.mozCurrentTransform;
6988
6989 if (group.matrix) {
6990 currentCtx.transform.apply(currentCtx, group.matrix);
6991 }
6992
6993 if (!group.bbox) {
6994 throw new Error("Bounding box is required.");
6995 }
6996
6997 let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
6998
6999 const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
7000 bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
7001 const offsetX = Math.floor(bounds[0]);
7002 const offsetY = Math.floor(bounds[1]);
7003 let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
7004 let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
7005 let scaleX = 1,
7006 scaleY = 1;
7007
7008 if (drawnWidth > MAX_GROUP_SIZE) {
7009 scaleX = drawnWidth / MAX_GROUP_SIZE;
7010 drawnWidth = MAX_GROUP_SIZE;
7011 }
7012
7013 if (drawnHeight > MAX_GROUP_SIZE) {
7014 scaleY = drawnHeight / MAX_GROUP_SIZE;
7015 drawnHeight = MAX_GROUP_SIZE;
7016 }
7017
7018 this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
7019 let cacheId = "groupAt" + this.groupLevel;
7020
7021 if (group.smask) {
7022 cacheId += "_smask_" + this.smaskCounter++ % 2;
7023 }
7024
7025 const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
7026 const groupCtx = scratchCanvas.context;
7027 groupCtx.scale(1 / scaleX, 1 / scaleY);
7028 groupCtx.translate(-offsetX, -offsetY);
7029 groupCtx.transform.apply(groupCtx, currentTransform);
7030
7031 if (group.smask) {
7032 this.smaskStack.push({
7033 canvas: scratchCanvas.canvas,
7034 context: groupCtx,
7035 offsetX,
7036 offsetY,
7037 scaleX,
7038 scaleY,
7039 subtype: group.smask.subtype,
7040 backdrop: group.smask.backdrop,
7041 transferMap: group.smask.transferMap || null,
7042 startTransformInverse: null
7043 });
7044 } else {
7045 currentCtx.setTransform(1, 0, 0, 1, 0, 0);
7046 currentCtx.translate(offsetX, offsetY);
7047 currentCtx.scale(scaleX, scaleY);
7048 currentCtx.save();
7049 }
7050
7051 copyCtxState(currentCtx, groupCtx);
7052 this.ctx = groupCtx;
7053 this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
7054 this.groupStack.push({
7055 ctx: currentCtx,
7056 suspendedCtx
7057 });
7058 this.groupLevel++;
7059 }
7060
7061 endGroup(group) {
7062 if (!this.contentVisible) {
7063 return;
7064 }
7065
7066 this.groupLevel--;
7067 const groupCtx = this.ctx;
7068 const {
7069 ctx,
7070 suspendedCtx
7071 } = this.groupStack.pop();
7072 this.ctx = ctx;
7073 this.ctx.imageSmoothingEnabled = false;
7074
7075 if (suspendedCtx) {
7076 this.suspendedCtx = suspendedCtx;
7077 }
7078
7079 if (group.smask) {
7080 this.tempSMask = this.smaskStack.pop();
7081 this.restore();
7082 } else {
7083 this.ctx.restore();
7084 const currentMtx = this.ctx.mozCurrentTransform;
7085 this.restore();
7086 this.ctx.save();
7087 this.ctx.setTransform.apply(this.ctx, currentMtx);
7088
7089 const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
7090
7091 this.ctx.drawImage(groupCtx.canvas, 0, 0);
7092 this.ctx.restore();
7093 this.compose(dirtyBox);
7094 }
7095 }
7096
7097 beginAnnotations() {
7098 this.save();
7099
7100 if (this.baseTransform) {
7101 this.ctx.setTransform.apply(this.ctx, this.baseTransform);
7102 }
7103 }
7104
7105 endAnnotations() {
7106 this.restore();
7107 }
7108
7109 beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
7110 this.save();
7111
7112 if (Array.isArray(rect) && rect.length === 4) {
7113 const width = rect[2] - rect[0];
7114 const height = rect[3] - rect[1];
7115
7116 if (hasOwnCanvas && this.annotationCanvasMap) {
7117 transform = transform.slice();
7118 transform[4] -= rect[0];
7119 transform[5] -= rect[1];
7120 rect = rect.slice();
7121 rect[0] = rect[1] = 0;
7122 rect[2] = width;
7123 rect[3] = height;
7124
7125 const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform);
7126
7127 const {
7128 viewportScale
7129 } = this;
7130 const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
7131 const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
7132 this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
7133 const {
7134 canvas,
7135 context
7136 } = this.annotationCanvas;
7137 canvas.style.width = `calc(${width}px * var(--viewport-scale-factor))`;
7138 canvas.style.height = `calc(${height}px * var(--viewport-scale-factor))`;
7139 this.annotationCanvasMap.set(id, canvas);
7140 this.annotationCanvas.savedCtx = this.ctx;
7141 this.ctx = context;
7142 this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
7143 addContextCurrentTransform(this.ctx);
7144 resetCtxToDefault(this.ctx);
7145 } else {
7146 resetCtxToDefault(this.ctx);
7147 this.ctx.rect(rect[0], rect[1], width, height);
7148 this.clip();
7149 this.endPath();
7150 }
7151 }
7152
7153 this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
7154 this.transform.apply(this, transform);
7155 this.transform.apply(this, matrix);
7156 }
7157
7158 endAnnotation() {
7159 if (this.annotationCanvas) {
7160 this.ctx = this.annotationCanvas.savedCtx;
7161 delete this.annotationCanvas.savedCtx;
7162 delete this.annotationCanvas;
7163 }
7164
7165 this.restore();
7166 }
7167
7168 paintImageMaskXObject(img) {
7169 if (!this.contentVisible) {
7170 return;
7171 }
7172
7173 const ctx = this.ctx;
7174 const width = img.width,
7175 height = img.height;
7176 const glyph = this.processingType3;
7177
7178 if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
7179 if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
7180 glyph.compiled = compileType3Glyph({
7181 data: img.data,
7182 width,
7183 height
7184 });
7185 } else {
7186 glyph.compiled = null;
7187 }
7188 }
7189
7190 if (glyph?.compiled) {
7191 glyph.compiled(ctx);
7192 return;
7193 }
7194
7195 const mask = this._createMaskCanvas(img);
7196
7197 const maskCanvas = mask.canvas;
7198 ctx.save();
7199 ctx.setTransform(1, 0, 0, 1, 0, 0);
7200 ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
7201 ctx.restore();
7202 this.compose();
7203 }
7204
7205 paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
7206 if (!this.contentVisible) {
7207 return;
7208 }
7209
7210 const ctx = this.ctx;
7211 ctx.save();
7212 const currentTransform = ctx.mozCurrentTransform;
7213 ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
7214
7215 const mask = this._createMaskCanvas(imgData);
7216
7217 ctx.setTransform(1, 0, 0, 1, 0, 0);
7218
7219 for (let i = 0, ii = positions.length; i < ii; i += 2) {
7220 const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
7221
7222 const [x, y] = _util.Util.applyTransform([0, 0], trans);
7223
7224 ctx.drawImage(mask.canvas, x, y);
7225 }
7226
7227 ctx.restore();
7228 this.compose();
7229 }
7230
7231 paintImageMaskXObjectGroup(images) {
7232 if (!this.contentVisible) {
7233 return;
7234 }
7235
7236 const ctx = this.ctx;
7237 const fillColor = this.current.fillColor;
7238 const isPatternFill = this.current.patternFill;
7239
7240 for (let i = 0, ii = images.length; i < ii; i++) {
7241 const image = images[i];
7242 const width = image.width,
7243 height = image.height;
7244 const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
7245 const maskCtx = maskCanvas.context;
7246 maskCtx.save();
7247 putBinaryImageMask(maskCtx, image);
7248 maskCtx.globalCompositeOperation = "source-in";
7249 maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL) : fillColor;
7250 maskCtx.fillRect(0, 0, width, height);
7251 maskCtx.restore();
7252 ctx.save();
7253 ctx.transform.apply(ctx, image.transform);
7254 ctx.scale(1, -1);
7255 ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
7256 ctx.restore();
7257 }
7258
7259 this.compose();
7260 }
7261
7262 paintImageXObject(objId) {
7263 if (!this.contentVisible) {
7264 return;
7265 }
7266
7267 const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
7268
7269 if (!imgData) {
7270 (0, _util.warn)("Dependent image isn't ready yet");
7271 return;
7272 }
7273
7274 this.paintInlineImageXObject(imgData);
7275 }
7276
7277 paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
7278 if (!this.contentVisible) {
7279 return;
7280 }
7281
7282 const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
7283
7284 if (!imgData) {
7285 (0, _util.warn)("Dependent image isn't ready yet");
7286 return;
7287 }
7288
7289 const width = imgData.width;
7290 const height = imgData.height;
7291 const map = [];
7292
7293 for (let i = 0, ii = positions.length; i < ii; i += 2) {
7294 map.push({
7295 transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
7296 x: 0,
7297 y: 0,
7298 w: width,
7299 h: height
7300 });
7301 }
7302
7303 this.paintInlineImageXObjectGroup(imgData, map);
7304 }
7305
7306 paintInlineImageXObject(imgData) {
7307 if (!this.contentVisible) {
7308 return;
7309 }
7310
7311 const width = imgData.width;
7312 const height = imgData.height;
7313 const ctx = this.ctx;
7314 this.save();
7315 ctx.scale(1 / width, -1 / height);
7316 let imgToPaint;
7317
7318 if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
7319 imgToPaint = imgData;
7320 } else {
7321 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
7322 const tmpCtx = tmpCanvas.context;
7323 putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
7324 imgToPaint = tmpCanvas.canvas;
7325 }
7326
7327 const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
7328
7329 ctx.imageSmoothingEnabled = getImageSmoothingEnabled(ctx.mozCurrentTransform, imgData.interpolate);
7330 ctx.drawImage(scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
7331
7332 if (this.imageLayer) {
7333 const position = this.getCanvasPosition(0, -height);
7334 this.imageLayer.appendImage({
7335 imgData,
7336 left: position[0],
7337 top: position[1],
7338 width: width / ctx.mozCurrentTransformInverse[0],
7339 height: height / ctx.mozCurrentTransformInverse[3]
7340 });
7341 }
7342
7343 this.compose();
7344 this.restore();
7345 }
7346
7347 paintInlineImageXObjectGroup(imgData, map) {
7348 if (!this.contentVisible) {
7349 return;
7350 }
7351
7352 const ctx = this.ctx;
7353 const w = imgData.width;
7354 const h = imgData.height;
7355 const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
7356 const tmpCtx = tmpCanvas.context;
7357 putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
7358
7359 for (let i = 0, ii = map.length; i < ii; i++) {
7360 const entry = map[i];
7361 ctx.save();
7362 ctx.transform.apply(ctx, entry.transform);
7363 ctx.scale(1, -1);
7364 ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
7365
7366 if (this.imageLayer) {
7367 const position = this.getCanvasPosition(entry.x, entry.y);
7368 this.imageLayer.appendImage({
7369 imgData,
7370 left: position[0],
7371 top: position[1],
7372 width: w,
7373 height: h
7374 });
7375 }
7376
7377 ctx.restore();
7378 }
7379
7380 this.compose();
7381 }
7382
7383 paintSolidColorImageMask() {
7384 if (!this.contentVisible) {
7385 return;
7386 }
7387
7388 this.ctx.fillRect(0, 0, 1, 1);
7389 this.compose();
7390 }
7391
7392 markPoint(tag) {}
7393
7394 markPointProps(tag, properties) {}
7395
7396 beginMarkedContent(tag) {
7397 this.markedContentStack.push({
7398 visible: true
7399 });
7400 }
7401
7402 beginMarkedContentProps(tag, properties) {
7403 if (tag === "OC") {
7404 this.markedContentStack.push({
7405 visible: this.optionalContentConfig.isVisible(properties)
7406 });
7407 } else {
7408 this.markedContentStack.push({
7409 visible: true
7410 });
7411 }
7412
7413 this.contentVisible = this.isContentVisible();
7414 }
7415
7416 endMarkedContent() {
7417 this.markedContentStack.pop();
7418 this.contentVisible = this.isContentVisible();
7419 }
7420
7421 beginCompat() {}
7422
7423 endCompat() {}
7424
7425 consumePath(clipBox) {
7426 if (this.pendingClip) {
7427 this.current.updateClipFromPath();
7428 }
7429
7430 if (!this.pendingClip) {
7431 this.compose(clipBox);
7432 }
7433
7434 const ctx = this.ctx;
7435
7436 if (this.pendingClip) {
7437 if (this.pendingClip === EO_CLIP) {
7438 ctx.clip("evenodd");
7439 } else {
7440 ctx.clip();
7441 }
7442
7443 this.pendingClip = null;
7444 }
7445
7446 this.current.startNewPathAndClipBox(this.current.clipBox);
7447 ctx.beginPath();
7448 }
7449
7450 getSinglePixelWidth() {
7451 if (this._cachedGetSinglePixelWidth === null) {
7452 const m = this.ctx.mozCurrentTransform;
7453 const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7454 const sqNorm1 = m[0] ** 2 + m[2] ** 2;
7455 const sqNorm2 = m[1] ** 2 + m[3] ** 2;
7456 const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
7457
7458 if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
7459 this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
7460 } else if (absDet > Number.EPSILON) {
7461 this._cachedGetSinglePixelWidth = pixelHeight;
7462 } else {
7463 this._cachedGetSinglePixelWidth = 1;
7464 }
7465 }
7466
7467 return this._cachedGetSinglePixelWidth;
7468 }
7469
7470 getCanvasPosition(x, y) {
7471 const transform = this.ctx.mozCurrentTransform;
7472 return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
7473 }
7474
7475 isContentVisible() {
7476 for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
7477 if (!this.markedContentStack[i].visible) {
7478 return false;
7479 }
7480 }
7481
7482 return true;
7483 }
7484
7485}
7486
7487exports.CanvasGraphics = CanvasGraphics;
7488
7489for (const op in _util.OPS) {
7490 if (CanvasGraphics.prototype[op] !== undefined) {
7491 CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
7492 }
7493}
7494
7495/***/ }),
7496/* 11 */
7497/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7498
7499
7500
7501Object.defineProperty(exports, "__esModule", ({
7502 value: true
7503}));
7504exports.TilingPattern = exports.PathType = void 0;
7505exports.getShadingPattern = getShadingPattern;
7506
7507var _util = __w_pdfjs_require__(2);
7508
7509const PathType = {
7510 FILL: "Fill",
7511 STROKE: "Stroke",
7512 SHADING: "Shading"
7513};
7514exports.PathType = PathType;
7515
7516function applyBoundingBox(ctx, bbox) {
7517 if (!bbox || typeof Path2D === "undefined") {
7518 return;
7519 }
7520
7521 const width = bbox[2] - bbox[0];
7522 const height = bbox[3] - bbox[1];
7523 const region = new Path2D();
7524 region.rect(bbox[0], bbox[1], width, height);
7525 ctx.clip(region);
7526}
7527
7528class BaseShadingPattern {
7529 constructor() {
7530 if (this.constructor === BaseShadingPattern) {
7531 (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
7532 }
7533 }
7534
7535 getPattern() {
7536 (0, _util.unreachable)("Abstract method `getPattern` called.");
7537 }
7538
7539}
7540
7541class RadialAxialShadingPattern extends BaseShadingPattern {
7542 constructor(IR) {
7543 super();
7544 this._type = IR[1];
7545 this._bbox = IR[2];
7546 this._colorStops = IR[3];
7547 this._p0 = IR[4];
7548 this._p1 = IR[5];
7549 this._r0 = IR[6];
7550 this._r1 = IR[7];
7551 this.matrix = null;
7552 }
7553
7554 _createGradient(ctx) {
7555 let grad;
7556
7557 if (this._type === "axial") {
7558 grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
7559 } else if (this._type === "radial") {
7560 grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
7561 }
7562
7563 for (const colorStop of this._colorStops) {
7564 grad.addColorStop(colorStop[0], colorStop[1]);
7565 }
7566
7567 return grad;
7568 }
7569
7570 getPattern(ctx, owner, inverse, pathType) {
7571 let pattern;
7572
7573 if (pathType === PathType.STROKE || pathType === PathType.FILL) {
7574 const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, ctx.mozCurrentTransform) || [0, 0, 0, 0];
7575 const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
7576 const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
7577 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
7578 const tmpCtx = tmpCanvas.context;
7579 tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7580 tmpCtx.beginPath();
7581 tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7582 tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
7583 inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
7584 tmpCtx.transform.apply(tmpCtx, owner.baseTransform);
7585
7586 if (this.matrix) {
7587 tmpCtx.transform.apply(tmpCtx, this.matrix);
7588 }
7589
7590 applyBoundingBox(tmpCtx, this._bbox);
7591 tmpCtx.fillStyle = this._createGradient(tmpCtx);
7592 tmpCtx.fill();
7593 pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
7594 const domMatrix = new DOMMatrix(inverse);
7595
7596 try {
7597 pattern.setTransform(domMatrix);
7598 } catch (ex) {
7599 (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
7600 }
7601 } else {
7602 applyBoundingBox(ctx, this._bbox);
7603 pattern = this._createGradient(ctx);
7604 }
7605
7606 return pattern;
7607 }
7608
7609}
7610
7611function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
7612 const coords = context.coords,
7613 colors = context.colors;
7614 const bytes = data.data,
7615 rowSize = data.width * 4;
7616 let tmp;
7617
7618 if (coords[p1 + 1] > coords[p2 + 1]) {
7619 tmp = p1;
7620 p1 = p2;
7621 p2 = tmp;
7622 tmp = c1;
7623 c1 = c2;
7624 c2 = tmp;
7625 }
7626
7627 if (coords[p2 + 1] > coords[p3 + 1]) {
7628 tmp = p2;
7629 p2 = p3;
7630 p3 = tmp;
7631 tmp = c2;
7632 c2 = c3;
7633 c3 = tmp;
7634 }
7635
7636 if (coords[p1 + 1] > coords[p2 + 1]) {
7637 tmp = p1;
7638 p1 = p2;
7639 p2 = tmp;
7640 tmp = c1;
7641 c1 = c2;
7642 c2 = tmp;
7643 }
7644
7645 const x1 = (coords[p1] + context.offsetX) * context.scaleX;
7646 const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
7647 const x2 = (coords[p2] + context.offsetX) * context.scaleX;
7648 const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
7649 const x3 = (coords[p3] + context.offsetX) * context.scaleX;
7650 const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
7651
7652 if (y1 >= y3) {
7653 return;
7654 }
7655
7656 const c1r = colors[c1],
7657 c1g = colors[c1 + 1],
7658 c1b = colors[c1 + 2];
7659 const c2r = colors[c2],
7660 c2g = colors[c2 + 1],
7661 c2b = colors[c2 + 2];
7662 const c3r = colors[c3],
7663 c3g = colors[c3 + 1],
7664 c3b = colors[c3 + 2];
7665 const minY = Math.round(y1),
7666 maxY = Math.round(y3);
7667 let xa, car, cag, cab;
7668 let xb, cbr, cbg, cbb;
7669
7670 for (let y = minY; y <= maxY; y++) {
7671 if (y < y2) {
7672 let k;
7673
7674 if (y < y1) {
7675 k = 0;
7676 } else {
7677 k = (y1 - y) / (y1 - y2);
7678 }
7679
7680 xa = x1 - (x1 - x2) * k;
7681 car = c1r - (c1r - c2r) * k;
7682 cag = c1g - (c1g - c2g) * k;
7683 cab = c1b - (c1b - c2b) * k;
7684 } else {
7685 let k;
7686
7687 if (y > y3) {
7688 k = 1;
7689 } else if (y2 === y3) {
7690 k = 0;
7691 } else {
7692 k = (y2 - y) / (y2 - y3);
7693 }
7694
7695 xa = x2 - (x2 - x3) * k;
7696 car = c2r - (c2r - c3r) * k;
7697 cag = c2g - (c2g - c3g) * k;
7698 cab = c2b - (c2b - c3b) * k;
7699 }
7700
7701 let k;
7702
7703 if (y < y1) {
7704 k = 0;
7705 } else if (y > y3) {
7706 k = 1;
7707 } else {
7708 k = (y1 - y) / (y1 - y3);
7709 }
7710
7711 xb = x1 - (x1 - x3) * k;
7712 cbr = c1r - (c1r - c3r) * k;
7713 cbg = c1g - (c1g - c3g) * k;
7714 cbb = c1b - (c1b - c3b) * k;
7715 const x1_ = Math.round(Math.min(xa, xb));
7716 const x2_ = Math.round(Math.max(xa, xb));
7717 let j = rowSize * y + x1_ * 4;
7718
7719 for (let x = x1_; x <= x2_; x++) {
7720 k = (xa - x) / (xa - xb);
7721
7722 if (k < 0) {
7723 k = 0;
7724 } else if (k > 1) {
7725 k = 1;
7726 }
7727
7728 bytes[j++] = car - (car - cbr) * k | 0;
7729 bytes[j++] = cag - (cag - cbg) * k | 0;
7730 bytes[j++] = cab - (cab - cbb) * k | 0;
7731 bytes[j++] = 255;
7732 }
7733 }
7734}
7735
7736function drawFigure(data, figure, context) {
7737 const ps = figure.coords;
7738 const cs = figure.colors;
7739 let i, ii;
7740
7741 switch (figure.type) {
7742 case "lattice":
7743 const verticesPerRow = figure.verticesPerRow;
7744 const rows = Math.floor(ps.length / verticesPerRow) - 1;
7745 const cols = verticesPerRow - 1;
7746
7747 for (i = 0; i < rows; i++) {
7748 let q = i * verticesPerRow;
7749
7750 for (let j = 0; j < cols; j++, q++) {
7751 drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
7752 drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
7753 }
7754 }
7755
7756 break;
7757
7758 case "triangles":
7759 for (i = 0, ii = ps.length; i < ii; i += 3) {
7760 drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
7761 }
7762
7763 break;
7764
7765 default:
7766 throw new Error("illegal figure");
7767 }
7768}
7769
7770class MeshShadingPattern extends BaseShadingPattern {
7771 constructor(IR) {
7772 super();
7773 this._coords = IR[2];
7774 this._colors = IR[3];
7775 this._figures = IR[4];
7776 this._bounds = IR[5];
7777 this._bbox = IR[7];
7778 this._background = IR[8];
7779 this.matrix = null;
7780 }
7781
7782 _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
7783 const EXPECTED_SCALE = 1.1;
7784 const MAX_PATTERN_SIZE = 3000;
7785 const BORDER_SIZE = 2;
7786 const offsetX = Math.floor(this._bounds[0]);
7787 const offsetY = Math.floor(this._bounds[1]);
7788 const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
7789 const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
7790 const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7791 const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7792 const scaleX = boundsWidth / width;
7793 const scaleY = boundsHeight / height;
7794 const context = {
7795 coords: this._coords,
7796 colors: this._colors,
7797 offsetX: -offsetX,
7798 offsetY: -offsetY,
7799 scaleX: 1 / scaleX,
7800 scaleY: 1 / scaleY
7801 };
7802 const paddedWidth = width + BORDER_SIZE * 2;
7803 const paddedHeight = height + BORDER_SIZE * 2;
7804 const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
7805 const tmpCtx = tmpCanvas.context;
7806 const data = tmpCtx.createImageData(width, height);
7807
7808 if (backgroundColor) {
7809 const bytes = data.data;
7810
7811 for (let i = 0, ii = bytes.length; i < ii; i += 4) {
7812 bytes[i] = backgroundColor[0];
7813 bytes[i + 1] = backgroundColor[1];
7814 bytes[i + 2] = backgroundColor[2];
7815 bytes[i + 3] = 255;
7816 }
7817 }
7818
7819 for (const figure of this._figures) {
7820 drawFigure(data, figure, context);
7821 }
7822
7823 tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
7824 const canvas = tmpCanvas.canvas;
7825 return {
7826 canvas,
7827 offsetX: offsetX - BORDER_SIZE * scaleX,
7828 offsetY: offsetY - BORDER_SIZE * scaleY,
7829 scaleX,
7830 scaleY
7831 };
7832 }
7833
7834 getPattern(ctx, owner, inverse, pathType) {
7835 applyBoundingBox(ctx, this._bbox);
7836 let scale;
7837
7838 if (pathType === PathType.SHADING) {
7839 scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
7840 } else {
7841 scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
7842
7843 if (this.matrix) {
7844 const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7845
7846 scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
7847 }
7848 }
7849
7850 const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
7851
7852 if (pathType !== PathType.SHADING) {
7853 ctx.setTransform.apply(ctx, owner.baseTransform);
7854
7855 if (this.matrix) {
7856 ctx.transform.apply(ctx, this.matrix);
7857 }
7858 }
7859
7860 ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
7861 ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
7862 return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
7863 }
7864
7865}
7866
7867class DummyShadingPattern extends BaseShadingPattern {
7868 getPattern() {
7869 return "hotpink";
7870 }
7871
7872}
7873
7874function getShadingPattern(IR) {
7875 switch (IR[0]) {
7876 case "RadialAxial":
7877 return new RadialAxialShadingPattern(IR);
7878
7879 case "Mesh":
7880 return new MeshShadingPattern(IR);
7881
7882 case "Dummy":
7883 return new DummyShadingPattern();
7884 }
7885
7886 throw new Error(`Unknown IR type: ${IR[0]}`);
7887}
7888
7889const PaintType = {
7890 COLORED: 1,
7891 UNCOLORED: 2
7892};
7893
7894class TilingPattern {
7895 static get MAX_PATTERN_SIZE() {
7896 return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
7897 }
7898
7899 constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
7900 this.operatorList = IR[2];
7901 this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
7902 this.bbox = IR[4];
7903 this.xstep = IR[5];
7904 this.ystep = IR[6];
7905 this.paintType = IR[7];
7906 this.tilingType = IR[8];
7907 this.color = color;
7908 this.ctx = ctx;
7909 this.canvasGraphicsFactory = canvasGraphicsFactory;
7910 this.baseTransform = baseTransform;
7911 }
7912
7913 createPatternCanvas(owner) {
7914 const operatorList = this.operatorList;
7915 const bbox = this.bbox;
7916 const xstep = this.xstep;
7917 const ystep = this.ystep;
7918 const paintType = this.paintType;
7919 const tilingType = this.tilingType;
7920 const color = this.color;
7921 const canvasGraphicsFactory = this.canvasGraphicsFactory;
7922 (0, _util.info)("TilingType: " + tilingType);
7923 const x0 = bbox[0],
7924 y0 = bbox[1],
7925 x1 = bbox[2],
7926 y1 = bbox[3];
7927
7928 const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7929
7930 const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
7931
7932 const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
7933 const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
7934 const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
7935 const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
7936 const tmpCtx = tmpCanvas.context;
7937 const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
7938 graphics.groupLevel = owner.groupLevel;
7939 this.setFillAndStrokeStyleToContext(graphics, paintType, color);
7940 let adjustedX0 = x0;
7941 let adjustedY0 = y0;
7942 let adjustedX1 = x1;
7943 let adjustedY1 = y1;
7944
7945 if (x0 < 0) {
7946 adjustedX0 = 0;
7947 adjustedX1 += Math.abs(x0);
7948 }
7949
7950 if (y0 < 0) {
7951 adjustedY0 = 0;
7952 adjustedY1 += Math.abs(y0);
7953 }
7954
7955 tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
7956 graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
7957 this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
7958 graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
7959 graphics.executeOperatorList(operatorList);
7960 graphics.endDrawing();
7961 return {
7962 canvas: tmpCanvas.canvas,
7963 scaleX: dimx.scale,
7964 scaleY: dimy.scale,
7965 offsetX: adjustedX0,
7966 offsetY: adjustedY0
7967 };
7968 }
7969
7970 getSizeAndScale(step, realOutputSize, scale) {
7971 step = Math.abs(step);
7972 const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
7973 let size = Math.ceil(step * scale);
7974
7975 if (size >= maxSize) {
7976 size = maxSize;
7977 } else {
7978 scale = size / step;
7979 }
7980
7981 return {
7982 scale,
7983 size
7984 };
7985 }
7986
7987 clipBbox(graphics, x0, y0, x1, y1) {
7988 const bboxWidth = x1 - x0;
7989 const bboxHeight = y1 - y0;
7990 graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
7991 graphics.clip();
7992 graphics.endPath();
7993 }
7994
7995 setFillAndStrokeStyleToContext(graphics, paintType, color) {
7996 const context = graphics.ctx,
7997 current = graphics.current;
7998
7999 switch (paintType) {
8000 case PaintType.COLORED:
8001 const ctx = this.ctx;
8002 context.fillStyle = ctx.fillStyle;
8003 context.strokeStyle = ctx.strokeStyle;
8004 current.fillColor = ctx.fillStyle;
8005 current.strokeColor = ctx.strokeStyle;
8006 break;
8007
8008 case PaintType.UNCOLORED:
8009 const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
8010
8011 context.fillStyle = cssColor;
8012 context.strokeStyle = cssColor;
8013 current.fillColor = cssColor;
8014 current.strokeColor = cssColor;
8015 break;
8016
8017 default:
8018 throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
8019 }
8020 }
8021
8022 getPattern(ctx, owner, inverse, pathType) {
8023 let matrix = inverse;
8024
8025 if (pathType !== PathType.SHADING) {
8026 matrix = _util.Util.transform(matrix, owner.baseTransform);
8027
8028 if (this.matrix) {
8029 matrix = _util.Util.transform(matrix, this.matrix);
8030 }
8031 }
8032
8033 const temporaryPatternCanvas = this.createPatternCanvas(owner);
8034 let domMatrix = new DOMMatrix(matrix);
8035 domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
8036 domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
8037 const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
8038
8039 try {
8040 pattern.setTransform(domMatrix);
8041 } catch (ex) {
8042 (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
8043 }
8044
8045 return pattern;
8046 }
8047
8048}
8049
8050exports.TilingPattern = TilingPattern;
8051
8052/***/ }),
8053/* 12 */
8054/***/ ((__unused_webpack_module, exports) => {
8055
8056
8057
8058Object.defineProperty(exports, "__esModule", ({
8059 value: true
8060}));
8061exports.GlobalWorkerOptions = void 0;
8062const GlobalWorkerOptions = Object.create(null);
8063exports.GlobalWorkerOptions = GlobalWorkerOptions;
8064GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
8065GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
8066
8067/***/ }),
8068/* 13 */
8069/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8070
8071
8072
8073Object.defineProperty(exports, "__esModule", ({
8074 value: true
8075}));
8076exports.MessageHandler = void 0;
8077
8078var _util = __w_pdfjs_require__(2);
8079
8080const CallbackKind = {
8081 UNKNOWN: 0,
8082 DATA: 1,
8083 ERROR: 2
8084};
8085const StreamKind = {
8086 UNKNOWN: 0,
8087 CANCEL: 1,
8088 CANCEL_COMPLETE: 2,
8089 CLOSE: 3,
8090 ENQUEUE: 4,
8091 ERROR: 5,
8092 PULL: 6,
8093 PULL_COMPLETE: 7,
8094 START_COMPLETE: 8
8095};
8096
8097function wrapReason(reason) {
8098 if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
8099 (0, _util.warn)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
8100 return reason;
8101 }
8102
8103 switch (reason.name) {
8104 case "AbortException":
8105 return new _util.AbortException(reason.message);
8106
8107 case "MissingPDFException":
8108 return new _util.MissingPDFException(reason.message);
8109
8110 case "PasswordException":
8111 return new _util.PasswordException(reason.message, reason.code);
8112
8113 case "UnexpectedResponseException":
8114 return new _util.UnexpectedResponseException(reason.message, reason.status);
8115
8116 case "UnknownErrorException":
8117 return new _util.UnknownErrorException(reason.message, reason.details);
8118
8119 default:
8120 return new _util.UnknownErrorException(reason.message, reason.toString());
8121 }
8122}
8123
8124class MessageHandler {
8125 constructor(sourceName, targetName, comObj) {
8126 this.sourceName = sourceName;
8127 this.targetName = targetName;
8128 this.comObj = comObj;
8129 this.callbackId = 1;
8130 this.streamId = 1;
8131 this.streamSinks = Object.create(null);
8132 this.streamControllers = Object.create(null);
8133 this.callbackCapabilities = Object.create(null);
8134 this.actionHandler = Object.create(null);
8135
8136 this._onComObjOnMessage = event => {
8137 const data = event.data;
8138
8139 if (data.targetName !== this.sourceName) {
8140 return;
8141 }
8142
8143 if (data.stream) {
8144 this._processStreamMessage(data);
8145
8146 return;
8147 }
8148
8149 if (data.callback) {
8150 const callbackId = data.callbackId;
8151 const capability = this.callbackCapabilities[callbackId];
8152
8153 if (!capability) {
8154 throw new Error(`Cannot resolve callback ${callbackId}`);
8155 }
8156
8157 delete this.callbackCapabilities[callbackId];
8158
8159 if (data.callback === CallbackKind.DATA) {
8160 capability.resolve(data.data);
8161 } else if (data.callback === CallbackKind.ERROR) {
8162 capability.reject(wrapReason(data.reason));
8163 } else {
8164 throw new Error("Unexpected callback case");
8165 }
8166
8167 return;
8168 }
8169
8170 const action = this.actionHandler[data.action];
8171
8172 if (!action) {
8173 throw new Error(`Unknown action from worker: ${data.action}`);
8174 }
8175
8176 if (data.callbackId) {
8177 const cbSourceName = this.sourceName;
8178 const cbTargetName = data.sourceName;
8179 new Promise(function (resolve) {
8180 resolve(action(data.data));
8181 }).then(function (result) {
8182 comObj.postMessage({
8183 sourceName: cbSourceName,
8184 targetName: cbTargetName,
8185 callback: CallbackKind.DATA,
8186 callbackId: data.callbackId,
8187 data: result
8188 });
8189 }, function (reason) {
8190 comObj.postMessage({
8191 sourceName: cbSourceName,
8192 targetName: cbTargetName,
8193 callback: CallbackKind.ERROR,
8194 callbackId: data.callbackId,
8195 reason: wrapReason(reason)
8196 });
8197 });
8198 return;
8199 }
8200
8201 if (data.streamId) {
8202 this._createStreamSink(data);
8203
8204 return;
8205 }
8206
8207 action(data.data);
8208 };
8209
8210 comObj.addEventListener("message", this._onComObjOnMessage);
8211 }
8212
8213 on(actionName, handler) {
8214 const ah = this.actionHandler;
8215
8216 if (ah[actionName]) {
8217 throw new Error(`There is already an actionName called "${actionName}"`);
8218 }
8219
8220 ah[actionName] = handler;
8221 }
8222
8223 send(actionName, data, transfers) {
8224 this.comObj.postMessage({
8225 sourceName: this.sourceName,
8226 targetName: this.targetName,
8227 action: actionName,
8228 data
8229 }, transfers);
8230 }
8231
8232 sendWithPromise(actionName, data, transfers) {
8233 const callbackId = this.callbackId++;
8234 const capability = (0, _util.createPromiseCapability)();
8235 this.callbackCapabilities[callbackId] = capability;
8236
8237 try {
8238 this.comObj.postMessage({
8239 sourceName: this.sourceName,
8240 targetName: this.targetName,
8241 action: actionName,
8242 callbackId,
8243 data
8244 }, transfers);
8245 } catch (ex) {
8246 capability.reject(ex);
8247 }
8248
8249 return capability.promise;
8250 }
8251
8252 sendWithStream(actionName, data, queueingStrategy, transfers) {
8253 const streamId = this.streamId++,
8254 sourceName = this.sourceName,
8255 targetName = this.targetName,
8256 comObj = this.comObj;
8257 return new ReadableStream({
8258 start: controller => {
8259 const startCapability = (0, _util.createPromiseCapability)();
8260 this.streamControllers[streamId] = {
8261 controller,
8262 startCall: startCapability,
8263 pullCall: null,
8264 cancelCall: null,
8265 isClosed: false
8266 };
8267 comObj.postMessage({
8268 sourceName,
8269 targetName,
8270 action: actionName,
8271 streamId,
8272 data,
8273 desiredSize: controller.desiredSize
8274 }, transfers);
8275 return startCapability.promise;
8276 },
8277 pull: controller => {
8278 const pullCapability = (0, _util.createPromiseCapability)();
8279 this.streamControllers[streamId].pullCall = pullCapability;
8280 comObj.postMessage({
8281 sourceName,
8282 targetName,
8283 stream: StreamKind.PULL,
8284 streamId,
8285 desiredSize: controller.desiredSize
8286 });
8287 return pullCapability.promise;
8288 },
8289 cancel: reason => {
8290 (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
8291 const cancelCapability = (0, _util.createPromiseCapability)();
8292 this.streamControllers[streamId].cancelCall = cancelCapability;
8293 this.streamControllers[streamId].isClosed = true;
8294 comObj.postMessage({
8295 sourceName,
8296 targetName,
8297 stream: StreamKind.CANCEL,
8298 streamId,
8299 reason: wrapReason(reason)
8300 });
8301 return cancelCapability.promise;
8302 }
8303 }, queueingStrategy);
8304 }
8305
8306 _createStreamSink(data) {
8307 const streamId = data.streamId,
8308 sourceName = this.sourceName,
8309 targetName = data.sourceName,
8310 comObj = this.comObj;
8311 const self = this,
8312 action = this.actionHandler[data.action];
8313 const streamSink = {
8314 enqueue(chunk, size = 1, transfers) {
8315 if (this.isCancelled) {
8316 return;
8317 }
8318
8319 const lastDesiredSize = this.desiredSize;
8320 this.desiredSize -= size;
8321
8322 if (lastDesiredSize > 0 && this.desiredSize <= 0) {
8323 this.sinkCapability = (0, _util.createPromiseCapability)();
8324 this.ready = this.sinkCapability.promise;
8325 }
8326
8327 comObj.postMessage({
8328 sourceName,
8329 targetName,
8330 stream: StreamKind.ENQUEUE,
8331 streamId,
8332 chunk
8333 }, transfers);
8334 },
8335
8336 close() {
8337 if (this.isCancelled) {
8338 return;
8339 }
8340
8341 this.isCancelled = true;
8342 comObj.postMessage({
8343 sourceName,
8344 targetName,
8345 stream: StreamKind.CLOSE,
8346 streamId
8347 });
8348 delete self.streamSinks[streamId];
8349 },
8350
8351 error(reason) {
8352 (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
8353
8354 if (this.isCancelled) {
8355 return;
8356 }
8357
8358 this.isCancelled = true;
8359 comObj.postMessage({
8360 sourceName,
8361 targetName,
8362 stream: StreamKind.ERROR,
8363 streamId,
8364 reason: wrapReason(reason)
8365 });
8366 },
8367
8368 sinkCapability: (0, _util.createPromiseCapability)(),
8369 onPull: null,
8370 onCancel: null,
8371 isCancelled: false,
8372 desiredSize: data.desiredSize,
8373 ready: null
8374 };
8375 streamSink.sinkCapability.resolve();
8376 streamSink.ready = streamSink.sinkCapability.promise;
8377 this.streamSinks[streamId] = streamSink;
8378 new Promise(function (resolve) {
8379 resolve(action(data.data, streamSink));
8380 }).then(function () {
8381 comObj.postMessage({
8382 sourceName,
8383 targetName,
8384 stream: StreamKind.START_COMPLETE,
8385 streamId,
8386 success: true
8387 });
8388 }, function (reason) {
8389 comObj.postMessage({
8390 sourceName,
8391 targetName,
8392 stream: StreamKind.START_COMPLETE,
8393 streamId,
8394 reason: wrapReason(reason)
8395 });
8396 });
8397 }
8398
8399 _processStreamMessage(data) {
8400 const streamId = data.streamId,
8401 sourceName = this.sourceName,
8402 targetName = data.sourceName,
8403 comObj = this.comObj;
8404 const streamController = this.streamControllers[streamId],
8405 streamSink = this.streamSinks[streamId];
8406
8407 switch (data.stream) {
8408 case StreamKind.START_COMPLETE:
8409 if (data.success) {
8410 streamController.startCall.resolve();
8411 } else {
8412 streamController.startCall.reject(wrapReason(data.reason));
8413 }
8414
8415 break;
8416
8417 case StreamKind.PULL_COMPLETE:
8418 if (data.success) {
8419 streamController.pullCall.resolve();
8420 } else {
8421 streamController.pullCall.reject(wrapReason(data.reason));
8422 }
8423
8424 break;
8425
8426 case StreamKind.PULL:
8427 if (!streamSink) {
8428 comObj.postMessage({
8429 sourceName,
8430 targetName,
8431 stream: StreamKind.PULL_COMPLETE,
8432 streamId,
8433 success: true
8434 });
8435 break;
8436 }
8437
8438 if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
8439 streamSink.sinkCapability.resolve();
8440 }
8441
8442 streamSink.desiredSize = data.desiredSize;
8443 new Promise(function (resolve) {
8444 resolve(streamSink.onPull && streamSink.onPull());
8445 }).then(function () {
8446 comObj.postMessage({
8447 sourceName,
8448 targetName,
8449 stream: StreamKind.PULL_COMPLETE,
8450 streamId,
8451 success: true
8452 });
8453 }, function (reason) {
8454 comObj.postMessage({
8455 sourceName,
8456 targetName,
8457 stream: StreamKind.PULL_COMPLETE,
8458 streamId,
8459 reason: wrapReason(reason)
8460 });
8461 });
8462 break;
8463
8464 case StreamKind.ENQUEUE:
8465 (0, _util.assert)(streamController, "enqueue should have stream controller");
8466
8467 if (streamController.isClosed) {
8468 break;
8469 }
8470
8471 streamController.controller.enqueue(data.chunk);
8472 break;
8473
8474 case StreamKind.CLOSE:
8475 (0, _util.assert)(streamController, "close should have stream controller");
8476
8477 if (streamController.isClosed) {
8478 break;
8479 }
8480
8481 streamController.isClosed = true;
8482 streamController.controller.close();
8483
8484 this._deleteStreamController(streamController, streamId);
8485
8486 break;
8487
8488 case StreamKind.ERROR:
8489 (0, _util.assert)(streamController, "error should have stream controller");
8490 streamController.controller.error(wrapReason(data.reason));
8491
8492 this._deleteStreamController(streamController, streamId);
8493
8494 break;
8495
8496 case StreamKind.CANCEL_COMPLETE:
8497 if (data.success) {
8498 streamController.cancelCall.resolve();
8499 } else {
8500 streamController.cancelCall.reject(wrapReason(data.reason));
8501 }
8502
8503 this._deleteStreamController(streamController, streamId);
8504
8505 break;
8506
8507 case StreamKind.CANCEL:
8508 if (!streamSink) {
8509 break;
8510 }
8511
8512 new Promise(function (resolve) {
8513 resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
8514 }).then(function () {
8515 comObj.postMessage({
8516 sourceName,
8517 targetName,
8518 stream: StreamKind.CANCEL_COMPLETE,
8519 streamId,
8520 success: true
8521 });
8522 }, function (reason) {
8523 comObj.postMessage({
8524 sourceName,
8525 targetName,
8526 stream: StreamKind.CANCEL_COMPLETE,
8527 streamId,
8528 reason: wrapReason(reason)
8529 });
8530 });
8531 streamSink.sinkCapability.reject(wrapReason(data.reason));
8532 streamSink.isCancelled = true;
8533 delete this.streamSinks[streamId];
8534 break;
8535
8536 default:
8537 throw new Error("Unexpected stream case");
8538 }
8539 }
8540
8541 async _deleteStreamController(streamController, streamId) {
8542 await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
8543 delete this.streamControllers[streamId];
8544 }
8545
8546 destroy() {
8547 this.comObj.removeEventListener("message", this._onComObjOnMessage);
8548 }
8549
8550}
8551
8552exports.MessageHandler = MessageHandler;
8553
8554/***/ }),
8555/* 14 */
8556/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8557
8558
8559
8560Object.defineProperty(exports, "__esModule", ({
8561 value: true
8562}));
8563exports.Metadata = void 0;
8564
8565var _util = __w_pdfjs_require__(2);
8566
8567class Metadata {
8568 #metadataMap;
8569 #data;
8570
8571 constructor({
8572 parsedData,
8573 rawData
8574 }) {
8575 this.#metadataMap = parsedData;
8576 this.#data = rawData;
8577 }
8578
8579 getRaw() {
8580 return this.#data;
8581 }
8582
8583 get(name) {
8584 return this.#metadataMap.get(name) ?? null;
8585 }
8586
8587 getAll() {
8588 return (0, _util.objectFromMap)(this.#metadataMap);
8589 }
8590
8591 has(name) {
8592 return this.#metadataMap.has(name);
8593 }
8594
8595}
8596
8597exports.Metadata = Metadata;
8598
8599/***/ }),
8600/* 15 */
8601/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8602
8603
8604
8605Object.defineProperty(exports, "__esModule", ({
8606 value: true
8607}));
8608exports.OptionalContentConfig = void 0;
8609
8610var _util = __w_pdfjs_require__(2);
8611
8612class OptionalContentGroup {
8613 constructor(name, intent) {
8614 this.visible = true;
8615 this.name = name;
8616 this.intent = intent;
8617 }
8618
8619}
8620
8621class OptionalContentConfig {
8622 constructor(data) {
8623 this.name = null;
8624 this.creator = null;
8625 this._order = null;
8626 this._groups = new Map();
8627
8628 if (data === null) {
8629 return;
8630 }
8631
8632 this.name = data.name;
8633 this.creator = data.creator;
8634 this._order = data.order;
8635
8636 for (const group of data.groups) {
8637 this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
8638 }
8639
8640 if (data.baseState === "OFF") {
8641 for (const group of this._groups) {
8642 group.visible = false;
8643 }
8644 }
8645
8646 for (const on of data.on) {
8647 this._groups.get(on).visible = true;
8648 }
8649
8650 for (const off of data.off) {
8651 this._groups.get(off).visible = false;
8652 }
8653 }
8654
8655 _evaluateVisibilityExpression(array) {
8656 const length = array.length;
8657
8658 if (length < 2) {
8659 return true;
8660 }
8661
8662 const operator = array[0];
8663
8664 for (let i = 1; i < length; i++) {
8665 const element = array[i];
8666 let state;
8667
8668 if (Array.isArray(element)) {
8669 state = this._evaluateVisibilityExpression(element);
8670 } else if (this._groups.has(element)) {
8671 state = this._groups.get(element).visible;
8672 } else {
8673 (0, _util.warn)(`Optional content group not found: ${element}`);
8674 return true;
8675 }
8676
8677 switch (operator) {
8678 case "And":
8679 if (!state) {
8680 return false;
8681 }
8682
8683 break;
8684
8685 case "Or":
8686 if (state) {
8687 return true;
8688 }
8689
8690 break;
8691
8692 case "Not":
8693 return !state;
8694
8695 default:
8696 return true;
8697 }
8698 }
8699
8700 return operator === "And";
8701 }
8702
8703 isVisible(group) {
8704 if (this._groups.size === 0) {
8705 return true;
8706 }
8707
8708 if (!group) {
8709 (0, _util.warn)("Optional content group not defined.");
8710 return true;
8711 }
8712
8713 if (group.type === "OCG") {
8714 if (!this._groups.has(group.id)) {
8715 (0, _util.warn)(`Optional content group not found: ${group.id}`);
8716 return true;
8717 }
8718
8719 return this._groups.get(group.id).visible;
8720 } else if (group.type === "OCMD") {
8721 if (group.expression) {
8722 return this._evaluateVisibilityExpression(group.expression);
8723 }
8724
8725 if (!group.policy || group.policy === "AnyOn") {
8726 for (const id of group.ids) {
8727 if (!this._groups.has(id)) {
8728 (0, _util.warn)(`Optional content group not found: ${id}`);
8729 return true;
8730 }
8731
8732 if (this._groups.get(id).visible) {
8733 return true;
8734 }
8735 }
8736
8737 return false;
8738 } else if (group.policy === "AllOn") {
8739 for (const id of group.ids) {
8740 if (!this._groups.has(id)) {
8741 (0, _util.warn)(`Optional content group not found: ${id}`);
8742 return true;
8743 }
8744
8745 if (!this._groups.get(id).visible) {
8746 return false;
8747 }
8748 }
8749
8750 return true;
8751 } else if (group.policy === "AnyOff") {
8752 for (const id of group.ids) {
8753 if (!this._groups.has(id)) {
8754 (0, _util.warn)(`Optional content group not found: ${id}`);
8755 return true;
8756 }
8757
8758 if (!this._groups.get(id).visible) {
8759 return true;
8760 }
8761 }
8762
8763 return false;
8764 } else if (group.policy === "AllOff") {
8765 for (const id of group.ids) {
8766 if (!this._groups.has(id)) {
8767 (0, _util.warn)(`Optional content group not found: ${id}`);
8768 return true;
8769 }
8770
8771 if (this._groups.get(id).visible) {
8772 return false;
8773 }
8774 }
8775
8776 return true;
8777 }
8778
8779 (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
8780 return true;
8781 }
8782
8783 (0, _util.warn)(`Unknown group type ${group.type}.`);
8784 return true;
8785 }
8786
8787 setVisibility(id, visible = true) {
8788 if (!this._groups.has(id)) {
8789 (0, _util.warn)(`Optional content group not found: ${id}`);
8790 return;
8791 }
8792
8793 this._groups.get(id).visible = !!visible;
8794 }
8795
8796 getOrder() {
8797 if (!this._groups.size) {
8798 return null;
8799 }
8800
8801 if (this._order) {
8802 return this._order.slice();
8803 }
8804
8805 return Array.from(this._groups.keys());
8806 }
8807
8808 getGroups() {
8809 return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null;
8810 }
8811
8812 getGroup(id) {
8813 return this._groups.get(id) || null;
8814 }
8815
8816}
8817
8818exports.OptionalContentConfig = OptionalContentConfig;
8819
8820/***/ }),
8821/* 16 */
8822/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8823
8824
8825
8826Object.defineProperty(exports, "__esModule", ({
8827 value: true
8828}));
8829exports.PDFDataTransportStream = void 0;
8830
8831var _util = __w_pdfjs_require__(2);
8832
8833var _display_utils = __w_pdfjs_require__(1);
8834
8835class PDFDataTransportStream {
8836 constructor(params, pdfDataRangeTransport) {
8837 (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
8838 this._queuedChunks = [];
8839 this._progressiveDone = params.progressiveDone || false;
8840 this._contentDispositionFilename = params.contentDispositionFilename || null;
8841 const initialData = params.initialData;
8842
8843 if (initialData?.length > 0) {
8844 const buffer = new Uint8Array(initialData).buffer;
8845
8846 this._queuedChunks.push(buffer);
8847 }
8848
8849 this._pdfDataRangeTransport = pdfDataRangeTransport;
8850 this._isStreamingSupported = !params.disableStream;
8851 this._isRangeSupported = !params.disableRange;
8852 this._contentLength = params.length;
8853 this._fullRequestReader = null;
8854 this._rangeReaders = [];
8855
8856 this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
8857 this._onReceiveData({
8858 begin,
8859 chunk
8860 });
8861 });
8862
8863 this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
8864 this._onProgress({
8865 loaded,
8866 total
8867 });
8868 });
8869
8870 this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
8871 this._onReceiveData({
8872 chunk
8873 });
8874 });
8875
8876 this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
8877 this._onProgressiveDone();
8878 });
8879
8880 this._pdfDataRangeTransport.transportReady();
8881 }
8882
8883 _onReceiveData(args) {
8884 const buffer = new Uint8Array(args.chunk).buffer;
8885
8886 if (args.begin === undefined) {
8887 if (this._fullRequestReader) {
8888 this._fullRequestReader._enqueue(buffer);
8889 } else {
8890 this._queuedChunks.push(buffer);
8891 }
8892 } else {
8893 const found = this._rangeReaders.some(function (rangeReader) {
8894 if (rangeReader._begin !== args.begin) {
8895 return false;
8896 }
8897
8898 rangeReader._enqueue(buffer);
8899
8900 return true;
8901 });
8902
8903 (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
8904 }
8905 }
8906
8907 get _progressiveDataLength() {
8908 return this._fullRequestReader?._loaded ?? 0;
8909 }
8910
8911 _onProgress(evt) {
8912 if (evt.total === undefined) {
8913 const firstReader = this._rangeReaders[0];
8914
8915 if (firstReader?.onProgress) {
8916 firstReader.onProgress({
8917 loaded: evt.loaded
8918 });
8919 }
8920 } else {
8921 const fullReader = this._fullRequestReader;
8922
8923 if (fullReader?.onProgress) {
8924 fullReader.onProgress({
8925 loaded: evt.loaded,
8926 total: evt.total
8927 });
8928 }
8929 }
8930 }
8931
8932 _onProgressiveDone() {
8933 if (this._fullRequestReader) {
8934 this._fullRequestReader.progressiveDone();
8935 }
8936
8937 this._progressiveDone = true;
8938 }
8939
8940 _removeRangeReader(reader) {
8941 const i = this._rangeReaders.indexOf(reader);
8942
8943 if (i >= 0) {
8944 this._rangeReaders.splice(i, 1);
8945 }
8946 }
8947
8948 getFullReader() {
8949 (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
8950 const queuedChunks = this._queuedChunks;
8951 this._queuedChunks = null;
8952 return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
8953 }
8954
8955 getRangeReader(begin, end) {
8956 if (end <= this._progressiveDataLength) {
8957 return null;
8958 }
8959
8960 const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
8961
8962 this._pdfDataRangeTransport.requestDataRange(begin, end);
8963
8964 this._rangeReaders.push(reader);
8965
8966 return reader;
8967 }
8968
8969 cancelAllRequests(reason) {
8970 if (this._fullRequestReader) {
8971 this._fullRequestReader.cancel(reason);
8972 }
8973
8974 for (const reader of this._rangeReaders.slice(0)) {
8975 reader.cancel(reason);
8976 }
8977
8978 this._pdfDataRangeTransport.abort();
8979 }
8980
8981}
8982
8983exports.PDFDataTransportStream = PDFDataTransportStream;
8984
8985class PDFDataTransportStreamReader {
8986 constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
8987 this._stream = stream;
8988 this._done = progressiveDone || false;
8989 this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
8990 this._queuedChunks = queuedChunks || [];
8991 this._loaded = 0;
8992
8993 for (const chunk of this._queuedChunks) {
8994 this._loaded += chunk.byteLength;
8995 }
8996
8997 this._requests = [];
8998 this._headersReady = Promise.resolve();
8999 stream._fullRequestReader = this;
9000 this.onProgress = null;
9001 }
9002
9003 _enqueue(chunk) {
9004 if (this._done) {
9005 return;
9006 }
9007
9008 if (this._requests.length > 0) {
9009 const requestCapability = this._requests.shift();
9010
9011 requestCapability.resolve({
9012 value: chunk,
9013 done: false
9014 });
9015 } else {
9016 this._queuedChunks.push(chunk);
9017 }
9018
9019 this._loaded += chunk.byteLength;
9020 }
9021
9022 get headersReady() {
9023 return this._headersReady;
9024 }
9025
9026 get filename() {
9027 return this._filename;
9028 }
9029
9030 get isRangeSupported() {
9031 return this._stream._isRangeSupported;
9032 }
9033
9034 get isStreamingSupported() {
9035 return this._stream._isStreamingSupported;
9036 }
9037
9038 get contentLength() {
9039 return this._stream._contentLength;
9040 }
9041
9042 async read() {
9043 if (this._queuedChunks.length > 0) {
9044 const chunk = this._queuedChunks.shift();
9045
9046 return {
9047 value: chunk,
9048 done: false
9049 };
9050 }
9051
9052 if (this._done) {
9053 return {
9054 value: undefined,
9055 done: true
9056 };
9057 }
9058
9059 const requestCapability = (0, _util.createPromiseCapability)();
9060
9061 this._requests.push(requestCapability);
9062
9063 return requestCapability.promise;
9064 }
9065
9066 cancel(reason) {
9067 this._done = true;
9068
9069 for (const requestCapability of this._requests) {
9070 requestCapability.resolve({
9071 value: undefined,
9072 done: true
9073 });
9074 }
9075
9076 this._requests.length = 0;
9077 }
9078
9079 progressiveDone() {
9080 if (this._done) {
9081 return;
9082 }
9083
9084 this._done = true;
9085 }
9086
9087}
9088
9089class PDFDataTransportStreamRangeReader {
9090 constructor(stream, begin, end) {
9091 this._stream = stream;
9092 this._begin = begin;
9093 this._end = end;
9094 this._queuedChunk = null;
9095 this._requests = [];
9096 this._done = false;
9097 this.onProgress = null;
9098 }
9099
9100 _enqueue(chunk) {
9101 if (this._done) {
9102 return;
9103 }
9104
9105 if (this._requests.length === 0) {
9106 this._queuedChunk = chunk;
9107 } else {
9108 const requestsCapability = this._requests.shift();
9109
9110 requestsCapability.resolve({
9111 value: chunk,
9112 done: false
9113 });
9114
9115 for (const requestCapability of this._requests) {
9116 requestCapability.resolve({
9117 value: undefined,
9118 done: true
9119 });
9120 }
9121
9122 this._requests.length = 0;
9123 }
9124
9125 this._done = true;
9126
9127 this._stream._removeRangeReader(this);
9128 }
9129
9130 get isStreamingSupported() {
9131 return false;
9132 }
9133
9134 async read() {
9135 if (this._queuedChunk) {
9136 const chunk = this._queuedChunk;
9137 this._queuedChunk = null;
9138 return {
9139 value: chunk,
9140 done: false
9141 };
9142 }
9143
9144 if (this._done) {
9145 return {
9146 value: undefined,
9147 done: true
9148 };
9149 }
9150
9151 const requestCapability = (0, _util.createPromiseCapability)();
9152
9153 this._requests.push(requestCapability);
9154
9155 return requestCapability.promise;
9156 }
9157
9158 cancel(reason) {
9159 this._done = true;
9160
9161 for (const requestCapability of this._requests) {
9162 requestCapability.resolve({
9163 value: undefined,
9164 done: true
9165 });
9166 }
9167
9168 this._requests.length = 0;
9169
9170 this._stream._removeRangeReader(this);
9171 }
9172
9173}
9174
9175/***/ }),
9176/* 17 */
9177/***/ ((__unused_webpack_module, exports) => {
9178
9179
9180
9181Object.defineProperty(exports, "__esModule", ({
9182 value: true
9183}));
9184exports.XfaText = void 0;
9185
9186class XfaText {
9187 static textContent(xfa) {
9188 const items = [];
9189 const output = {
9190 items,
9191 styles: Object.create(null)
9192 };
9193
9194 function walk(node) {
9195 if (!node) {
9196 return;
9197 }
9198
9199 let str = null;
9200 const name = node.name;
9201
9202 if (name === "#text") {
9203 str = node.value;
9204 } else if (!XfaText.shouldBuildText(name)) {
9205 return;
9206 } else if (node?.attributes?.textContent) {
9207 str = node.attributes.textContent;
9208 } else if (node.value) {
9209 str = node.value;
9210 }
9211
9212 if (str !== null) {
9213 items.push({
9214 str
9215 });
9216 }
9217
9218 if (!node.children) {
9219 return;
9220 }
9221
9222 for (const child of node.children) {
9223 walk(child);
9224 }
9225 }
9226
9227 walk(xfa);
9228 return output;
9229 }
9230
9231 static shouldBuildText(name) {
9232 return !(name === "textarea" || name === "input" || name === "option" || name === "select");
9233 }
9234
9235}
9236
9237exports.XfaText = XfaText;
9238
9239/***/ }),
9240/* 18 */
9241/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9242
9243
9244
9245Object.defineProperty(exports, "__esModule", ({
9246 value: true
9247}));
9248exports.AnnotationLayer = void 0;
9249
9250var _util = __w_pdfjs_require__(2);
9251
9252var _display_utils = __w_pdfjs_require__(1);
9253
9254var _annotation_storage = __w_pdfjs_require__(9);
9255
9256var _scripting_utils = __w_pdfjs_require__(19);
9257
9258var _xfa_layer = __w_pdfjs_require__(20);
9259
9260const DEFAULT_TAB_INDEX = 1000;
9261const GetElementsByNameSet = new WeakSet();
9262
9263class AnnotationElementFactory {
9264 static create(parameters) {
9265 const subtype = parameters.data.annotationType;
9266
9267 switch (subtype) {
9268 case _util.AnnotationType.LINK:
9269 return new LinkAnnotationElement(parameters);
9270
9271 case _util.AnnotationType.TEXT:
9272 return new TextAnnotationElement(parameters);
9273
9274 case _util.AnnotationType.WIDGET:
9275 const fieldType = parameters.data.fieldType;
9276
9277 switch (fieldType) {
9278 case "Tx":
9279 return new TextWidgetAnnotationElement(parameters);
9280
9281 case "Btn":
9282 if (parameters.data.radioButton) {
9283 return new RadioButtonWidgetAnnotationElement(parameters);
9284 } else if (parameters.data.checkBox) {
9285 return new CheckboxWidgetAnnotationElement(parameters);
9286 }
9287
9288 return new PushButtonWidgetAnnotationElement(parameters);
9289
9290 case "Ch":
9291 return new ChoiceWidgetAnnotationElement(parameters);
9292 }
9293
9294 return new WidgetAnnotationElement(parameters);
9295
9296 case _util.AnnotationType.POPUP:
9297 return new PopupAnnotationElement(parameters);
9298
9299 case _util.AnnotationType.FREETEXT:
9300 return new FreeTextAnnotationElement(parameters);
9301
9302 case _util.AnnotationType.LINE:
9303 return new LineAnnotationElement(parameters);
9304
9305 case _util.AnnotationType.SQUARE:
9306 return new SquareAnnotationElement(parameters);
9307
9308 case _util.AnnotationType.CIRCLE:
9309 return new CircleAnnotationElement(parameters);
9310
9311 case _util.AnnotationType.POLYLINE:
9312 return new PolylineAnnotationElement(parameters);
9313
9314 case _util.AnnotationType.CARET:
9315 return new CaretAnnotationElement(parameters);
9316
9317 case _util.AnnotationType.INK:
9318 return new InkAnnotationElement(parameters);
9319
9320 case _util.AnnotationType.POLYGON:
9321 return new PolygonAnnotationElement(parameters);
9322
9323 case _util.AnnotationType.HIGHLIGHT:
9324 return new HighlightAnnotationElement(parameters);
9325
9326 case _util.AnnotationType.UNDERLINE:
9327 return new UnderlineAnnotationElement(parameters);
9328
9329 case _util.AnnotationType.SQUIGGLY:
9330 return new SquigglyAnnotationElement(parameters);
9331
9332 case _util.AnnotationType.STRIKEOUT:
9333 return new StrikeOutAnnotationElement(parameters);
9334
9335 case _util.AnnotationType.STAMP:
9336 return new StampAnnotationElement(parameters);
9337
9338 case _util.AnnotationType.FILEATTACHMENT:
9339 return new FileAttachmentAnnotationElement(parameters);
9340
9341 default:
9342 return new AnnotationElement(parameters);
9343 }
9344 }
9345
9346}
9347
9348class AnnotationElement {
9349 constructor(parameters, {
9350 isRenderable = false,
9351 ignoreBorder = false,
9352 createQuadrilaterals = false
9353 } = {}) {
9354 this.isRenderable = isRenderable;
9355 this.data = parameters.data;
9356 this.layer = parameters.layer;
9357 this.page = parameters.page;
9358 this.viewport = parameters.viewport;
9359 this.linkService = parameters.linkService;
9360 this.downloadManager = parameters.downloadManager;
9361 this.imageResourcesPath = parameters.imageResourcesPath;
9362 this.renderForms = parameters.renderForms;
9363 this.svgFactory = parameters.svgFactory;
9364 this.annotationStorage = parameters.annotationStorage;
9365 this.enableScripting = parameters.enableScripting;
9366 this.hasJSActions = parameters.hasJSActions;
9367 this._fieldObjects = parameters.fieldObjects;
9368 this._mouseState = parameters.mouseState;
9369
9370 if (isRenderable) {
9371 this.container = this._createContainer(ignoreBorder);
9372 }
9373
9374 if (createQuadrilaterals) {
9375 this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
9376 }
9377 }
9378
9379 _createContainer(ignoreBorder = false) {
9380 const data = this.data,
9381 page = this.page,
9382 viewport = this.viewport;
9383 const container = document.createElement("section");
9384 let width = data.rect[2] - data.rect[0];
9385 let height = data.rect[3] - data.rect[1];
9386 container.setAttribute("data-annotation-id", data.id);
9387
9388 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]]);
9389
9390 if (data.hasOwnCanvas) {
9391 const transform = viewport.transform.slice();
9392
9393 const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale(transform);
9394
9395 width = Math.ceil(width * scaleX);
9396 height = Math.ceil(height * scaleY);
9397 rect[0] *= scaleX;
9398 rect[1] *= scaleY;
9399
9400 for (let i = 0; i < 4; i++) {
9401 transform[i] = Math.sign(transform[i]);
9402 }
9403
9404 container.style.transform = `matrix(${transform.join(",")})`;
9405 } else {
9406 container.style.transform = `matrix(${viewport.transform.join(",")})`;
9407 }
9408
9409 container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
9410
9411 if (!ignoreBorder && data.borderStyle.width > 0) {
9412 container.style.borderWidth = `${data.borderStyle.width}px`;
9413
9414 if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
9415 width -= 2 * data.borderStyle.width;
9416 height -= 2 * data.borderStyle.width;
9417 }
9418
9419 const horizontalRadius = data.borderStyle.horizontalCornerRadius;
9420 const verticalRadius = data.borderStyle.verticalCornerRadius;
9421
9422 if (horizontalRadius > 0 || verticalRadius > 0) {
9423 const radius = `${horizontalRadius}px / ${verticalRadius}px`;
9424 container.style.borderRadius = radius;
9425 }
9426
9427 switch (data.borderStyle.style) {
9428 case _util.AnnotationBorderStyleType.SOLID:
9429 container.style.borderStyle = "solid";
9430 break;
9431
9432 case _util.AnnotationBorderStyleType.DASHED:
9433 container.style.borderStyle = "dashed";
9434 break;
9435
9436 case _util.AnnotationBorderStyleType.BEVELED:
9437 (0, _util.warn)("Unimplemented border style: beveled");
9438 break;
9439
9440 case _util.AnnotationBorderStyleType.INSET:
9441 (0, _util.warn)("Unimplemented border style: inset");
9442 break;
9443
9444 case _util.AnnotationBorderStyleType.UNDERLINE:
9445 container.style.borderBottomStyle = "solid";
9446 break;
9447
9448 default:
9449 break;
9450 }
9451
9452 const borderColor = data.borderColor || data.color || null;
9453
9454 if (borderColor) {
9455 container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
9456 } else {
9457 container.style.borderWidth = 0;
9458 }
9459 }
9460
9461 container.style.left = `${rect[0]}px`;
9462 container.style.top = `${rect[1]}px`;
9463
9464 if (data.hasOwnCanvas) {
9465 container.style.width = container.style.height = "auto";
9466 } else {
9467 container.style.width = `${width}px`;
9468 container.style.height = `${height}px`;
9469 }
9470
9471 return container;
9472 }
9473
9474 _createQuadrilaterals(ignoreBorder = false) {
9475 if (!this.data.quadPoints) {
9476 return null;
9477 }
9478
9479 const quadrilaterals = [];
9480 const savedRect = this.data.rect;
9481
9482 for (const quadPoint of this.data.quadPoints) {
9483 this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
9484 quadrilaterals.push(this._createContainer(ignoreBorder));
9485 }
9486
9487 this.data.rect = savedRect;
9488 return quadrilaterals;
9489 }
9490
9491 _createPopup(trigger, data) {
9492 let container = this.container;
9493
9494 if (this.quadrilaterals) {
9495 trigger = trigger || this.quadrilaterals;
9496 container = this.quadrilaterals[0];
9497 }
9498
9499 if (!trigger) {
9500 trigger = document.createElement("div");
9501 trigger.style.height = container.style.height;
9502 trigger.style.width = container.style.width;
9503 container.appendChild(trigger);
9504 }
9505
9506 const popupElement = new PopupElement({
9507 container,
9508 trigger,
9509 color: data.color,
9510 titleObj: data.titleObj,
9511 modificationDate: data.modificationDate,
9512 contentsObj: data.contentsObj,
9513 richText: data.richText,
9514 hideWrapper: true
9515 });
9516 const popup = popupElement.render();
9517 popup.style.left = container.style.width;
9518 container.appendChild(popup);
9519 }
9520
9521 _renderQuadrilaterals(className) {
9522 for (const quadrilateral of this.quadrilaterals) {
9523 quadrilateral.className = className;
9524 }
9525
9526 return this.quadrilaterals;
9527 }
9528
9529 render() {
9530 (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
9531 }
9532
9533 _getElementsByName(name, skipId = null) {
9534 const fields = [];
9535
9536 if (this._fieldObjects) {
9537 const fieldObj = this._fieldObjects[name];
9538
9539 if (fieldObj) {
9540 for (const {
9541 page,
9542 id,
9543 exportValues
9544 } of fieldObj) {
9545 if (page === -1) {
9546 continue;
9547 }
9548
9549 if (id === skipId) {
9550 continue;
9551 }
9552
9553 const exportValue = typeof exportValues === "string" ? exportValues : null;
9554 const domElement = document.getElementById(id);
9555
9556 if (domElement && !GetElementsByNameSet.has(domElement)) {
9557 (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
9558 continue;
9559 }
9560
9561 fields.push({
9562 id,
9563 exportValue,
9564 domElement
9565 });
9566 }
9567 }
9568
9569 return fields;
9570 }
9571
9572 for (const domElement of document.getElementsByName(name)) {
9573 const {
9574 id,
9575 exportValue
9576 } = domElement;
9577
9578 if (id === skipId) {
9579 continue;
9580 }
9581
9582 if (!GetElementsByNameSet.has(domElement)) {
9583 continue;
9584 }
9585
9586 fields.push({
9587 id,
9588 exportValue,
9589 domElement
9590 });
9591 }
9592
9593 return fields;
9594 }
9595
9596 static get platform() {
9597 const platform = typeof navigator !== "undefined" ? navigator.platform : "";
9598 return (0, _util.shadow)(this, "platform", {
9599 isWin: platform.includes("Win"),
9600 isMac: platform.includes("Mac")
9601 });
9602 }
9603
9604}
9605
9606class LinkAnnotationElement extends AnnotationElement {
9607 constructor(parameters, options = null) {
9608 const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.resetForm || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"]));
9609 super(parameters, {
9610 isRenderable,
9611 ignoreBorder: !!options?.ignoreBorder,
9612 createQuadrilaterals: true
9613 });
9614 }
9615
9616 render() {
9617 const {
9618 data,
9619 linkService
9620 } = this;
9621 const link = document.createElement("a");
9622
9623 if (data.url) {
9624 if (!linkService.addLinkAttributes) {
9625 (0, _util.warn)("LinkAnnotationElement.render - missing `addLinkAttributes`-method on the `linkService`-instance.");
9626 }
9627
9628 linkService.addLinkAttributes?.(link, data.url, data.newWindow);
9629 } else if (data.action) {
9630 this._bindNamedAction(link, data.action);
9631 } else if (data.dest) {
9632 this._bindLink(link, data.dest);
9633 } else {
9634 let hasClickAction = false;
9635
9636 if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
9637 hasClickAction = true;
9638
9639 this._bindJSAction(link, data);
9640 }
9641
9642 if (data.resetForm) {
9643 this._bindResetFormAction(link, data.resetForm);
9644 } else if (!hasClickAction) {
9645 this._bindLink(link, "");
9646 }
9647 }
9648
9649 if (this.quadrilaterals) {
9650 return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
9651 const linkElement = index === 0 ? link : link.cloneNode();
9652 quadrilateral.appendChild(linkElement);
9653 return quadrilateral;
9654 });
9655 }
9656
9657 this.container.className = "linkAnnotation";
9658 this.container.appendChild(link);
9659 return this.container;
9660 }
9661
9662 _bindLink(link, destination) {
9663 link.href = this.linkService.getDestinationHash(destination);
9664
9665 link.onclick = () => {
9666 if (destination) {
9667 this.linkService.goToDestination(destination);
9668 }
9669
9670 return false;
9671 };
9672
9673 if (destination || destination === "") {
9674 link.className = "internalLink";
9675 }
9676 }
9677
9678 _bindNamedAction(link, action) {
9679 link.href = this.linkService.getAnchorUrl("");
9680
9681 link.onclick = () => {
9682 this.linkService.executeNamedAction(action);
9683 return false;
9684 };
9685
9686 link.className = "internalLink";
9687 }
9688
9689 _bindJSAction(link, data) {
9690 link.href = this.linkService.getAnchorUrl("");
9691 const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
9692
9693 for (const name of Object.keys(data.actions)) {
9694 const jsName = map.get(name);
9695
9696 if (!jsName) {
9697 continue;
9698 }
9699
9700 link[jsName] = () => {
9701 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9702 source: this,
9703 detail: {
9704 id: data.id,
9705 name
9706 }
9707 });
9708 return false;
9709 };
9710 }
9711
9712 if (!link.onclick) {
9713 link.onclick = () => false;
9714 }
9715
9716 link.className = "internalLink";
9717 }
9718
9719 _bindResetFormAction(link, resetForm) {
9720 const otherClickAction = link.onclick;
9721
9722 if (!otherClickAction) {
9723 link.href = this.linkService.getAnchorUrl("");
9724 }
9725
9726 link.className = "internalLink";
9727
9728 if (!this._fieldObjects) {
9729 (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
9730
9731 if (!otherClickAction) {
9732 link.onclick = () => false;
9733 }
9734
9735 return;
9736 }
9737
9738 link.onclick = () => {
9739 if (otherClickAction) {
9740 otherClickAction();
9741 }
9742
9743 const {
9744 fields: resetFormFields,
9745 refs: resetFormRefs,
9746 include
9747 } = resetForm;
9748 const allFields = [];
9749
9750 if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
9751 const fieldIds = new Set(resetFormRefs);
9752
9753 for (const fieldName of resetFormFields) {
9754 const fields = this._fieldObjects[fieldName] || [];
9755
9756 for (const {
9757 id
9758 } of fields) {
9759 fieldIds.add(id);
9760 }
9761 }
9762
9763 for (const fields of Object.values(this._fieldObjects)) {
9764 for (const field of fields) {
9765 if (fieldIds.has(field.id) === include) {
9766 allFields.push(field);
9767 }
9768 }
9769 }
9770 } else {
9771 for (const fields of Object.values(this._fieldObjects)) {
9772 allFields.push(...fields);
9773 }
9774 }
9775
9776 const storage = this.annotationStorage;
9777 const allIds = [];
9778
9779 for (const field of allFields) {
9780 const {
9781 id
9782 } = field;
9783 allIds.push(id);
9784
9785 switch (field.type) {
9786 case "text":
9787 {
9788 const value = field.defaultValue || "";
9789 storage.setValue(id, {
9790 value,
9791 valueAsString: value
9792 });
9793 break;
9794 }
9795
9796 case "checkbox":
9797 case "radiobutton":
9798 {
9799 const value = field.defaultValue === field.exportValues;
9800 storage.setValue(id, {
9801 value
9802 });
9803 break;
9804 }
9805
9806 case "combobox":
9807 case "listbox":
9808 {
9809 const value = field.defaultValue || "";
9810 storage.setValue(id, {
9811 value
9812 });
9813 break;
9814 }
9815
9816 default:
9817 continue;
9818 }
9819
9820 const domElement = document.getElementById(id);
9821
9822 if (!domElement || !GetElementsByNameSet.has(domElement)) {
9823 continue;
9824 }
9825
9826 domElement.dispatchEvent(new Event("resetform"));
9827 }
9828
9829 if (this.enableScripting) {
9830 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9831 source: this,
9832 detail: {
9833 id: "app",
9834 ids: allIds,
9835 name: "ResetForm"
9836 }
9837 });
9838 }
9839
9840 return false;
9841 };
9842 }
9843
9844}
9845
9846class TextAnnotationElement extends AnnotationElement {
9847 constructor(parameters) {
9848 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
9849 super(parameters, {
9850 isRenderable
9851 });
9852 }
9853
9854 render() {
9855 this.container.className = "textAnnotation";
9856 const image = document.createElement("img");
9857 image.style.height = this.container.style.height;
9858 image.style.width = this.container.style.width;
9859 image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
9860 image.alt = "[{{type}} Annotation]";
9861 image.dataset.l10nId = "text_annotation_type";
9862 image.dataset.l10nArgs = JSON.stringify({
9863 type: this.data.name
9864 });
9865
9866 if (!this.data.hasPopup) {
9867 this._createPopup(image, this.data);
9868 }
9869
9870 this.container.appendChild(image);
9871 return this.container;
9872 }
9873
9874}
9875
9876class WidgetAnnotationElement extends AnnotationElement {
9877 render() {
9878 if (this.data.alternativeText) {
9879 this.container.title = this.data.alternativeText;
9880 }
9881
9882 return this.container;
9883 }
9884
9885 _getKeyModifier(event) {
9886 const {
9887 isWin,
9888 isMac
9889 } = AnnotationElement.platform;
9890 return isWin && event.ctrlKey || isMac && event.metaKey;
9891 }
9892
9893 _setEventListener(element, baseName, eventName, valueGetter) {
9894 if (baseName.includes("mouse")) {
9895 element.addEventListener(baseName, event => {
9896 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9897 source: this,
9898 detail: {
9899 id: this.data.id,
9900 name: eventName,
9901 value: valueGetter(event),
9902 shift: event.shiftKey,
9903 modifier: this._getKeyModifier(event)
9904 }
9905 });
9906 });
9907 } else {
9908 element.addEventListener(baseName, event => {
9909 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9910 source: this,
9911 detail: {
9912 id: this.data.id,
9913 name: eventName,
9914 value: event.target.checked
9915 }
9916 });
9917 });
9918 }
9919 }
9920
9921 _setEventListeners(element, names, getter) {
9922 for (const [baseName, eventName] of names) {
9923 if (eventName === "Action" || this.data.actions?.[eventName]) {
9924 this._setEventListener(element, baseName, eventName, getter);
9925 }
9926 }
9927 }
9928
9929 _setBackgroundColor(element) {
9930 const color = this.data.backgroundColor || null;
9931 element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
9932 }
9933
9934 _dispatchEventFromSandbox(actions, jsEvent) {
9935 const setColor = (jsName, styleName, event) => {
9936 const color = event.detail[jsName];
9937 event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
9938 };
9939
9940 const commonActions = {
9941 display: event => {
9942 const hidden = event.detail.display % 2 === 1;
9943 event.target.style.visibility = hidden ? "hidden" : "visible";
9944 this.annotationStorage.setValue(this.data.id, {
9945 hidden,
9946 print: event.detail.display === 0 || event.detail.display === 3
9947 });
9948 },
9949 print: event => {
9950 this.annotationStorage.setValue(this.data.id, {
9951 print: event.detail.print
9952 });
9953 },
9954 hidden: event => {
9955 event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
9956 this.annotationStorage.setValue(this.data.id, {
9957 hidden: event.detail.hidden
9958 });
9959 },
9960 focus: event => {
9961 setTimeout(() => event.target.focus({
9962 preventScroll: false
9963 }), 0);
9964 },
9965 userName: event => {
9966 event.target.title = event.detail.userName;
9967 },
9968 readonly: event => {
9969 if (event.detail.readonly) {
9970 event.target.setAttribute("readonly", "");
9971 } else {
9972 event.target.removeAttribute("readonly");
9973 }
9974 },
9975 required: event => {
9976 if (event.detail.required) {
9977 event.target.setAttribute("required", "");
9978 } else {
9979 event.target.removeAttribute("required");
9980 }
9981 },
9982 bgColor: event => {
9983 setColor("bgColor", "backgroundColor", event);
9984 },
9985 fillColor: event => {
9986 setColor("fillColor", "backgroundColor", event);
9987 },
9988 fgColor: event => {
9989 setColor("fgColor", "color", event);
9990 },
9991 textColor: event => {
9992 setColor("textColor", "color", event);
9993 },
9994 borderColor: event => {
9995 setColor("borderColor", "borderColor", event);
9996 },
9997 strokeColor: event => {
9998 setColor("strokeColor", "borderColor", event);
9999 }
10000 };
10001
10002 for (const name of Object.keys(jsEvent.detail)) {
10003 const action = actions[name] || commonActions[name];
10004
10005 if (action) {
10006 action(jsEvent);
10007 }
10008 }
10009 }
10010
10011}
10012
10013class TextWidgetAnnotationElement extends WidgetAnnotationElement {
10014 constructor(parameters) {
10015 const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
10016 super(parameters, {
10017 isRenderable
10018 });
10019 }
10020
10021 setPropertyOnSiblings(base, key, value, keyInStorage) {
10022 const storage = this.annotationStorage;
10023
10024 for (const element of this._getElementsByName(base.name, base.id)) {
10025 if (element.domElement) {
10026 element.domElement[key] = value;
10027 }
10028
10029 storage.setValue(element.id, {
10030 [keyInStorage]: value
10031 });
10032 }
10033 }
10034
10035 render() {
10036 const storage = this.annotationStorage;
10037 const id = this.data.id;
10038 this.container.className = "textWidgetAnnotation";
10039 let element = null;
10040
10041 if (this.renderForms) {
10042 const storedData = storage.getValue(id, {
10043 value: this.data.fieldValue,
10044 valueAsString: this.data.fieldValue
10045 });
10046 const textContent = storedData.valueAsString || storedData.value || "";
10047 const elementData = {
10048 userValue: null,
10049 formattedValue: null,
10050 beforeInputSelectionRange: null,
10051 beforeInputValue: null
10052 };
10053
10054 if (this.data.multiLine) {
10055 element = document.createElement("textarea");
10056 element.textContent = textContent;
10057 } else {
10058 element = document.createElement("input");
10059 element.type = "text";
10060 element.setAttribute("value", textContent);
10061 }
10062
10063 GetElementsByNameSet.add(element);
10064 element.disabled = this.data.readOnly;
10065 element.name = this.data.fieldName;
10066 element.tabIndex = DEFAULT_TAB_INDEX;
10067 elementData.userValue = textContent;
10068 element.setAttribute("id", id);
10069 element.addEventListener("input", event => {
10070 storage.setValue(id, {
10071 value: event.target.value
10072 });
10073 this.setPropertyOnSiblings(element, "value", event.target.value, "value");
10074 });
10075 element.addEventListener("resetform", event => {
10076 const defaultValue = this.data.defaultFieldValue || "";
10077 element.value = elementData.userValue = defaultValue;
10078 delete elementData.formattedValue;
10079 });
10080
10081 let blurListener = event => {
10082 if (elementData.formattedValue) {
10083 event.target.value = elementData.formattedValue;
10084 }
10085
10086 event.target.scrollLeft = 0;
10087 elementData.beforeInputSelectionRange = null;
10088 };
10089
10090 if (this.enableScripting && this.hasJSActions) {
10091 element.addEventListener("focus", event => {
10092 if (elementData.userValue) {
10093 event.target.value = elementData.userValue;
10094 }
10095 });
10096 element.addEventListener("updatefromsandbox", jsEvent => {
10097 const actions = {
10098 value(event) {
10099 elementData.userValue = event.detail.value || "";
10100 storage.setValue(id, {
10101 value: elementData.userValue.toString()
10102 });
10103
10104 if (!elementData.formattedValue) {
10105 event.target.value = elementData.userValue;
10106 }
10107 },
10108
10109 valueAsString(event) {
10110 elementData.formattedValue = event.detail.valueAsString || "";
10111
10112 if (event.target !== document.activeElement) {
10113 event.target.value = elementData.formattedValue;
10114 }
10115
10116 storage.setValue(id, {
10117 formattedValue: elementData.formattedValue
10118 });
10119 },
10120
10121 selRange(event) {
10122 const [selStart, selEnd] = event.detail.selRange;
10123
10124 if (selStart >= 0 && selEnd < event.target.value.length) {
10125 event.target.setSelectionRange(selStart, selEnd);
10126 }
10127 }
10128
10129 };
10130
10131 this._dispatchEventFromSandbox(actions, jsEvent);
10132 });
10133 element.addEventListener("keydown", event => {
10134 elementData.beforeInputValue = event.target.value;
10135 let commitKey = -1;
10136
10137 if (event.key === "Escape") {
10138 commitKey = 0;
10139 } else if (event.key === "Enter") {
10140 commitKey = 2;
10141 } else if (event.key === "Tab") {
10142 commitKey = 3;
10143 }
10144
10145 if (commitKey === -1) {
10146 return;
10147 }
10148
10149 elementData.userValue = event.target.value;
10150 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10151 source: this,
10152 detail: {
10153 id,
10154 name: "Keystroke",
10155 value: event.target.value,
10156 willCommit: true,
10157 commitKey,
10158 selStart: event.target.selectionStart,
10159 selEnd: event.target.selectionEnd
10160 }
10161 });
10162 });
10163 const _blurListener = blurListener;
10164 blurListener = null;
10165 element.addEventListener("blur", event => {
10166 if (this._mouseState.isDown) {
10167 elementData.userValue = event.target.value;
10168 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10169 source: this,
10170 detail: {
10171 id,
10172 name: "Keystroke",
10173 value: event.target.value,
10174 willCommit: true,
10175 commitKey: 1,
10176 selStart: event.target.selectionStart,
10177 selEnd: event.target.selectionEnd
10178 }
10179 });
10180 }
10181
10182 _blurListener(event);
10183 });
10184 element.addEventListener("mousedown", event => {
10185 elementData.beforeInputValue = event.target.value;
10186 elementData.beforeInputSelectionRange = null;
10187 });
10188 element.addEventListener("keyup", event => {
10189 if (event.target.selectionStart === event.target.selectionEnd) {
10190 elementData.beforeInputSelectionRange = null;
10191 }
10192 });
10193 element.addEventListener("select", event => {
10194 elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd];
10195 });
10196
10197 if (this.data.actions?.Keystroke) {
10198 element.addEventListener("input", event => {
10199 let selStart = -1;
10200 let selEnd = -1;
10201
10202 if (elementData.beforeInputSelectionRange) {
10203 [selStart, selEnd] = elementData.beforeInputSelectionRange;
10204 }
10205
10206 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10207 source: this,
10208 detail: {
10209 id,
10210 name: "Keystroke",
10211 value: elementData.beforeInputValue,
10212 change: event.data,
10213 willCommit: false,
10214 selStart,
10215 selEnd
10216 }
10217 });
10218 });
10219 }
10220
10221 this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
10222 }
10223
10224 if (blurListener) {
10225 element.addEventListener("blur", blurListener);
10226 }
10227
10228 if (this.data.maxLen !== null) {
10229 element.maxLength = this.data.maxLen;
10230 }
10231
10232 if (this.data.comb) {
10233 const fieldWidth = this.data.rect[2] - this.data.rect[0];
10234 const combWidth = fieldWidth / this.data.maxLen;
10235 element.classList.add("comb");
10236 element.style.letterSpacing = `calc(${combWidth}px - 1ch)`;
10237 }
10238 } else {
10239 element = document.createElement("div");
10240 element.textContent = this.data.fieldValue;
10241 element.style.verticalAlign = "middle";
10242 element.style.display = "table-cell";
10243 }
10244
10245 this._setTextStyle(element);
10246
10247 this._setBackgroundColor(element);
10248
10249 this.container.appendChild(element);
10250 return this.container;
10251 }
10252
10253 _setTextStyle(element) {
10254 const TEXT_ALIGNMENT = ["left", "center", "right"];
10255 const {
10256 fontSize,
10257 fontColor
10258 } = this.data.defaultAppearanceData;
10259 const style = element.style;
10260
10261 if (fontSize) {
10262 style.fontSize = `${fontSize}px`;
10263 }
10264
10265 style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
10266
10267 if (this.data.textAlignment !== null) {
10268 style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
10269 }
10270 }
10271
10272}
10273
10274class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
10275 constructor(parameters) {
10276 super(parameters, {
10277 isRenderable: parameters.renderForms
10278 });
10279 }
10280
10281 render() {
10282 const storage = this.annotationStorage;
10283 const data = this.data;
10284 const id = data.id;
10285 let value = storage.getValue(id, {
10286 value: data.exportValue === data.fieldValue
10287 }).value;
10288
10289 if (typeof value === "string") {
10290 value = value !== "Off";
10291 storage.setValue(id, {
10292 value
10293 });
10294 }
10295
10296 this.container.className = "buttonWidgetAnnotation checkBox";
10297 const element = document.createElement("input");
10298 GetElementsByNameSet.add(element);
10299 element.disabled = data.readOnly;
10300 element.type = "checkbox";
10301 element.name = data.fieldName;
10302
10303 if (value) {
10304 element.setAttribute("checked", true);
10305 }
10306
10307 element.setAttribute("id", id);
10308 element.setAttribute("exportValue", data.exportValue);
10309 element.tabIndex = DEFAULT_TAB_INDEX;
10310 element.addEventListener("change", event => {
10311 const {
10312 name,
10313 checked
10314 } = event.target;
10315
10316 for (const checkbox of this._getElementsByName(name, id)) {
10317 const curChecked = checked && checkbox.exportValue === data.exportValue;
10318
10319 if (checkbox.domElement) {
10320 checkbox.domElement.checked = curChecked;
10321 }
10322
10323 storage.setValue(checkbox.id, {
10324 value: curChecked
10325 });
10326 }
10327
10328 storage.setValue(id, {
10329 value: checked
10330 });
10331 });
10332 element.addEventListener("resetform", event => {
10333 const defaultValue = data.defaultFieldValue || "Off";
10334 event.target.checked = defaultValue === data.exportValue;
10335 });
10336
10337 if (this.enableScripting && this.hasJSActions) {
10338 element.addEventListener("updatefromsandbox", jsEvent => {
10339 const actions = {
10340 value(event) {
10341 event.target.checked = event.detail.value !== "Off";
10342 storage.setValue(id, {
10343 value: event.target.checked
10344 });
10345 }
10346
10347 };
10348
10349 this._dispatchEventFromSandbox(actions, jsEvent);
10350 });
10351
10352 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);
10353 }
10354
10355 this._setBackgroundColor(element);
10356
10357 this.container.appendChild(element);
10358 return this.container;
10359 }
10360
10361}
10362
10363class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
10364 constructor(parameters) {
10365 super(parameters, {
10366 isRenderable: parameters.renderForms
10367 });
10368 }
10369
10370 render() {
10371 this.container.className = "buttonWidgetAnnotation radioButton";
10372 const storage = this.annotationStorage;
10373 const data = this.data;
10374 const id = data.id;
10375 let value = storage.getValue(id, {
10376 value: data.fieldValue === data.buttonValue
10377 }).value;
10378
10379 if (typeof value === "string") {
10380 value = value !== data.buttonValue;
10381 storage.setValue(id, {
10382 value
10383 });
10384 }
10385
10386 const element = document.createElement("input");
10387 GetElementsByNameSet.add(element);
10388 element.disabled = data.readOnly;
10389 element.type = "radio";
10390 element.name = data.fieldName;
10391
10392 if (value) {
10393 element.setAttribute("checked", true);
10394 }
10395
10396 element.setAttribute("id", id);
10397 element.tabIndex = DEFAULT_TAB_INDEX;
10398 element.addEventListener("change", event => {
10399 const {
10400 name,
10401 checked
10402 } = event.target;
10403
10404 for (const radio of this._getElementsByName(name, id)) {
10405 storage.setValue(radio.id, {
10406 value: false
10407 });
10408 }
10409
10410 storage.setValue(id, {
10411 value: checked
10412 });
10413 });
10414 element.addEventListener("resetform", event => {
10415 const defaultValue = data.defaultFieldValue;
10416 event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
10417 });
10418
10419 if (this.enableScripting && this.hasJSActions) {
10420 const pdfButtonValue = data.buttonValue;
10421 element.addEventListener("updatefromsandbox", jsEvent => {
10422 const actions = {
10423 value: event => {
10424 const checked = pdfButtonValue === event.detail.value;
10425
10426 for (const radio of this._getElementsByName(event.target.name)) {
10427 const curChecked = checked && radio.id === id;
10428
10429 if (radio.domElement) {
10430 radio.domElement.checked = curChecked;
10431 }
10432
10433 storage.setValue(radio.id, {
10434 value: curChecked
10435 });
10436 }
10437 }
10438 };
10439
10440 this._dispatchEventFromSandbox(actions, jsEvent);
10441 });
10442
10443 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);
10444 }
10445
10446 this._setBackgroundColor(element);
10447
10448 this.container.appendChild(element);
10449 return this.container;
10450 }
10451
10452}
10453
10454class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
10455 constructor(parameters) {
10456 super(parameters, {
10457 ignoreBorder: parameters.data.hasAppearance
10458 });
10459 }
10460
10461 render() {
10462 const container = super.render();
10463 container.className = "buttonWidgetAnnotation pushButton";
10464
10465 if (this.data.alternativeText) {
10466 container.title = this.data.alternativeText;
10467 }
10468
10469 return container;
10470 }
10471
10472}
10473
10474class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
10475 constructor(parameters) {
10476 super(parameters, {
10477 isRenderable: parameters.renderForms
10478 });
10479 }
10480
10481 render() {
10482 this.container.className = "choiceWidgetAnnotation";
10483 const storage = this.annotationStorage;
10484 const id = this.data.id;
10485 storage.getValue(id, {
10486 value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined
10487 });
10488 let {
10489 fontSize
10490 } = this.data.defaultAppearanceData;
10491
10492 if (!fontSize) {
10493 fontSize = 9;
10494 }
10495
10496 const fontSizeStyle = `calc(${fontSize}px * var(--zoom-factor))`;
10497 const selectElement = document.createElement("select");
10498 GetElementsByNameSet.add(selectElement);
10499 selectElement.disabled = this.data.readOnly;
10500 selectElement.name = this.data.fieldName;
10501 selectElement.setAttribute("id", id);
10502 selectElement.tabIndex = DEFAULT_TAB_INDEX;
10503 selectElement.style.fontSize = `${fontSize}px`;
10504
10505 if (!this.data.combo) {
10506 selectElement.size = this.data.options.length;
10507
10508 if (this.data.multiSelect) {
10509 selectElement.multiple = true;
10510 }
10511 }
10512
10513 selectElement.addEventListener("resetform", event => {
10514 const defaultValue = this.data.defaultFieldValue;
10515
10516 for (const option of selectElement.options) {
10517 option.selected = option.value === defaultValue;
10518 }
10519 });
10520
10521 for (const option of this.data.options) {
10522 const optionElement = document.createElement("option");
10523 optionElement.textContent = option.displayValue;
10524 optionElement.value = option.exportValue;
10525
10526 if (this.data.combo) {
10527 optionElement.style.fontSize = fontSizeStyle;
10528 }
10529
10530 if (this.data.fieldValue.includes(option.exportValue)) {
10531 optionElement.setAttribute("selected", true);
10532 }
10533
10534 selectElement.appendChild(optionElement);
10535 }
10536
10537 const getValue = (event, isExport) => {
10538 const name = isExport ? "value" : "textContent";
10539 const options = event.target.options;
10540
10541 if (!event.target.multiple) {
10542 return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
10543 }
10544
10545 return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
10546 };
10547
10548 const getItems = event => {
10549 const options = event.target.options;
10550 return Array.prototype.map.call(options, option => {
10551 return {
10552 displayValue: option.textContent,
10553 exportValue: option.value
10554 };
10555 });
10556 };
10557
10558 if (this.enableScripting && this.hasJSActions) {
10559 selectElement.addEventListener("updatefromsandbox", jsEvent => {
10560 const actions = {
10561 value(event) {
10562 const value = event.detail.value;
10563 const values = new Set(Array.isArray(value) ? value : [value]);
10564
10565 for (const option of selectElement.options) {
10566 option.selected = values.has(option.value);
10567 }
10568
10569 storage.setValue(id, {
10570 value: getValue(event, true)
10571 });
10572 },
10573
10574 multipleSelection(event) {
10575 selectElement.multiple = true;
10576 },
10577
10578 remove(event) {
10579 const options = selectElement.options;
10580 const index = event.detail.remove;
10581 options[index].selected = false;
10582 selectElement.remove(index);
10583
10584 if (options.length > 0) {
10585 const i = Array.prototype.findIndex.call(options, option => option.selected);
10586
10587 if (i === -1) {
10588 options[0].selected = true;
10589 }
10590 }
10591
10592 storage.setValue(id, {
10593 value: getValue(event, true),
10594 items: getItems(event)
10595 });
10596 },
10597
10598 clear(event) {
10599 while (selectElement.length !== 0) {
10600 selectElement.remove(0);
10601 }
10602
10603 storage.setValue(id, {
10604 value: null,
10605 items: []
10606 });
10607 },
10608
10609 insert(event) {
10610 const {
10611 index,
10612 displayValue,
10613 exportValue
10614 } = event.detail.insert;
10615 const optionElement = document.createElement("option");
10616 optionElement.textContent = displayValue;
10617 optionElement.value = exportValue;
10618 selectElement.insertBefore(optionElement, selectElement.children[index]);
10619 storage.setValue(id, {
10620 value: getValue(event, true),
10621 items: getItems(event)
10622 });
10623 },
10624
10625 items(event) {
10626 const {
10627 items
10628 } = event.detail;
10629
10630 while (selectElement.length !== 0) {
10631 selectElement.remove(0);
10632 }
10633
10634 for (const item of items) {
10635 const {
10636 displayValue,
10637 exportValue
10638 } = item;
10639 const optionElement = document.createElement("option");
10640 optionElement.textContent = displayValue;
10641 optionElement.value = exportValue;
10642 selectElement.appendChild(optionElement);
10643 }
10644
10645 if (selectElement.options.length > 0) {
10646 selectElement.options[0].selected = true;
10647 }
10648
10649 storage.setValue(id, {
10650 value: getValue(event, true),
10651 items: getItems(event)
10652 });
10653 },
10654
10655 indices(event) {
10656 const indices = new Set(event.detail.indices);
10657
10658 for (const option of event.target.options) {
10659 option.selected = indices.has(option.index);
10660 }
10661
10662 storage.setValue(id, {
10663 value: getValue(event, true)
10664 });
10665 },
10666
10667 editable(event) {
10668 event.target.disabled = !event.detail.editable;
10669 }
10670
10671 };
10672
10673 this._dispatchEventFromSandbox(actions, jsEvent);
10674 });
10675 selectElement.addEventListener("input", event => {
10676 const exportValue = getValue(event, true);
10677 const value = getValue(event, false);
10678 storage.setValue(id, {
10679 value: exportValue
10680 });
10681 this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10682 source: this,
10683 detail: {
10684 id,
10685 name: "Keystroke",
10686 value,
10687 changeEx: exportValue,
10688 willCommit: true,
10689 commitKey: 1,
10690 keyDown: false
10691 }
10692 });
10693 });
10694
10695 this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"]], event => event.target.checked);
10696 } else {
10697 selectElement.addEventListener("input", function (event) {
10698 storage.setValue(id, {
10699 value: getValue(event)
10700 });
10701 });
10702 }
10703
10704 this._setBackgroundColor(selectElement);
10705
10706 this.container.appendChild(selectElement);
10707 return this.container;
10708 }
10709
10710}
10711
10712class PopupAnnotationElement extends AnnotationElement {
10713 constructor(parameters) {
10714 const isRenderable = !!(parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
10715 super(parameters, {
10716 isRenderable
10717 });
10718 }
10719
10720 render() {
10721 const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
10722 this.container.className = "popupAnnotation";
10723
10724 if (IGNORE_TYPES.includes(this.data.parentType)) {
10725 return this.container;
10726 }
10727
10728 const selector = `[data-annotation-id="${this.data.parentId}"]`;
10729 const parentElements = this.layer.querySelectorAll(selector);
10730
10731 if (parentElements.length === 0) {
10732 return this.container;
10733 }
10734
10735 const popup = new PopupElement({
10736 container: this.container,
10737 trigger: Array.from(parentElements),
10738 color: this.data.color,
10739 titleObj: this.data.titleObj,
10740 modificationDate: this.data.modificationDate,
10741 contentsObj: this.data.contentsObj,
10742 richText: this.data.richText
10743 });
10744 const page = this.page;
10745
10746 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]]);
10747
10748 const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
10749 const popupTop = rect[1];
10750 this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}px`;
10751 this.container.style.left = `${popupLeft}px`;
10752 this.container.style.top = `${popupTop}px`;
10753 this.container.appendChild(popup.render());
10754 return this.container;
10755 }
10756
10757}
10758
10759class PopupElement {
10760 constructor(parameters) {
10761 this.container = parameters.container;
10762 this.trigger = parameters.trigger;
10763 this.color = parameters.color;
10764 this.titleObj = parameters.titleObj;
10765 this.modificationDate = parameters.modificationDate;
10766 this.contentsObj = parameters.contentsObj;
10767 this.richText = parameters.richText;
10768 this.hideWrapper = parameters.hideWrapper || false;
10769 this.pinned = false;
10770 }
10771
10772 render() {
10773 const BACKGROUND_ENLIGHT = 0.7;
10774 const wrapper = document.createElement("div");
10775 wrapper.className = "popupWrapper";
10776 this.hideElement = this.hideWrapper ? wrapper : this.container;
10777 this.hideElement.hidden = true;
10778 const popup = document.createElement("div");
10779 popup.className = "popup";
10780 const color = this.color;
10781
10782 if (color) {
10783 const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
10784 const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
10785 const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
10786 popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
10787 }
10788
10789 const title = document.createElement("h1");
10790 title.dir = this.titleObj.dir;
10791 title.textContent = this.titleObj.str;
10792 popup.appendChild(title);
10793
10794 const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
10795
10796 if (dateObject) {
10797 const modificationDate = document.createElement("span");
10798 modificationDate.className = "popupDate";
10799 modificationDate.textContent = "{{date}}, {{time}}";
10800 modificationDate.dataset.l10nId = "annotation_date_string";
10801 modificationDate.dataset.l10nArgs = JSON.stringify({
10802 date: dateObject.toLocaleDateString(),
10803 time: dateObject.toLocaleTimeString()
10804 });
10805 popup.appendChild(modificationDate);
10806 }
10807
10808 if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
10809 _xfa_layer.XfaLayer.render({
10810 xfaHtml: this.richText.html,
10811 intent: "richText",
10812 div: popup
10813 });
10814
10815 popup.lastChild.className = "richText popupContent";
10816 } else {
10817 const contents = this._formatContents(this.contentsObj);
10818
10819 popup.appendChild(contents);
10820 }
10821
10822 if (!Array.isArray(this.trigger)) {
10823 this.trigger = [this.trigger];
10824 }
10825
10826 for (const element of this.trigger) {
10827 element.addEventListener("click", this._toggle.bind(this));
10828 element.addEventListener("mouseover", this._show.bind(this, false));
10829 element.addEventListener("mouseout", this._hide.bind(this, false));
10830 }
10831
10832 popup.addEventListener("click", this._hide.bind(this, true));
10833 wrapper.appendChild(popup);
10834 return wrapper;
10835 }
10836
10837 _formatContents({
10838 str,
10839 dir
10840 }) {
10841 const p = document.createElement("p");
10842 p.className = "popupContent";
10843 p.dir = dir;
10844 const lines = str.split(/(?:\r\n?|\n)/);
10845
10846 for (let i = 0, ii = lines.length; i < ii; ++i) {
10847 const line = lines[i];
10848 p.appendChild(document.createTextNode(line));
10849
10850 if (i < ii - 1) {
10851 p.appendChild(document.createElement("br"));
10852 }
10853 }
10854
10855 return p;
10856 }
10857
10858 _toggle() {
10859 if (this.pinned) {
10860 this._hide(true);
10861 } else {
10862 this._show(true);
10863 }
10864 }
10865
10866 _show(pin = false) {
10867 if (pin) {
10868 this.pinned = true;
10869 }
10870
10871 if (this.hideElement.hidden) {
10872 this.hideElement.hidden = false;
10873 this.container.style.zIndex += 1;
10874 }
10875 }
10876
10877 _hide(unpin = true) {
10878 if (unpin) {
10879 this.pinned = false;
10880 }
10881
10882 if (!this.hideElement.hidden && !this.pinned) {
10883 this.hideElement.hidden = true;
10884 this.container.style.zIndex -= 1;
10885 }
10886 }
10887
10888}
10889
10890class FreeTextAnnotationElement extends AnnotationElement {
10891 constructor(parameters) {
10892 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
10893 super(parameters, {
10894 isRenderable,
10895 ignoreBorder: true
10896 });
10897 }
10898
10899 render() {
10900 this.container.className = "freeTextAnnotation";
10901
10902 if (!this.data.hasPopup) {
10903 this._createPopup(null, this.data);
10904 }
10905
10906 return this.container;
10907 }
10908
10909}
10910
10911class LineAnnotationElement extends AnnotationElement {
10912 constructor(parameters) {
10913 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
10914 super(parameters, {
10915 isRenderable,
10916 ignoreBorder: true
10917 });
10918 }
10919
10920 render() {
10921 this.container.className = "lineAnnotation";
10922 const data = this.data;
10923 const width = data.rect[2] - data.rect[0];
10924 const height = data.rect[3] - data.rect[1];
10925 const svg = this.svgFactory.create(width, height);
10926 const line = this.svgFactory.createElement("svg:line");
10927 line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
10928 line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
10929 line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
10930 line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
10931 line.setAttribute("stroke-width", data.borderStyle.width || 1);
10932 line.setAttribute("stroke", "transparent");
10933 line.setAttribute("fill", "transparent");
10934 svg.appendChild(line);
10935 this.container.append(svg);
10936
10937 this._createPopup(line, data);
10938
10939 return this.container;
10940 }
10941
10942}
10943
10944class SquareAnnotationElement extends AnnotationElement {
10945 constructor(parameters) {
10946 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
10947 super(parameters, {
10948 isRenderable,
10949 ignoreBorder: true
10950 });
10951 }
10952
10953 render() {
10954 this.container.className = "squareAnnotation";
10955 const data = this.data;
10956 const width = data.rect[2] - data.rect[0];
10957 const height = data.rect[3] - data.rect[1];
10958 const svg = this.svgFactory.create(width, height);
10959 const borderWidth = data.borderStyle.width;
10960 const square = this.svgFactory.createElement("svg:rect");
10961 square.setAttribute("x", borderWidth / 2);
10962 square.setAttribute("y", borderWidth / 2);
10963 square.setAttribute("width", width - borderWidth);
10964 square.setAttribute("height", height - borderWidth);
10965 square.setAttribute("stroke-width", borderWidth || 1);
10966 square.setAttribute("stroke", "transparent");
10967 square.setAttribute("fill", "transparent");
10968 svg.appendChild(square);
10969 this.container.append(svg);
10970
10971 this._createPopup(square, data);
10972
10973 return this.container;
10974 }
10975
10976}
10977
10978class CircleAnnotationElement extends AnnotationElement {
10979 constructor(parameters) {
10980 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
10981 super(parameters, {
10982 isRenderable,
10983 ignoreBorder: true
10984 });
10985 }
10986
10987 render() {
10988 this.container.className = "circleAnnotation";
10989 const data = this.data;
10990 const width = data.rect[2] - data.rect[0];
10991 const height = data.rect[3] - data.rect[1];
10992 const svg = this.svgFactory.create(width, height);
10993 const borderWidth = data.borderStyle.width;
10994 const circle = this.svgFactory.createElement("svg:ellipse");
10995 circle.setAttribute("cx", width / 2);
10996 circle.setAttribute("cy", height / 2);
10997 circle.setAttribute("rx", width / 2 - borderWidth / 2);
10998 circle.setAttribute("ry", height / 2 - borderWidth / 2);
10999 circle.setAttribute("stroke-width", borderWidth || 1);
11000 circle.setAttribute("stroke", "transparent");
11001 circle.setAttribute("fill", "transparent");
11002 svg.appendChild(circle);
11003 this.container.append(svg);
11004
11005 this._createPopup(circle, data);
11006
11007 return this.container;
11008 }
11009
11010}
11011
11012class PolylineAnnotationElement extends AnnotationElement {
11013 constructor(parameters) {
11014 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11015 super(parameters, {
11016 isRenderable,
11017 ignoreBorder: true
11018 });
11019 this.containerClassName = "polylineAnnotation";
11020 this.svgElementName = "svg:polyline";
11021 }
11022
11023 render() {
11024 this.container.className = this.containerClassName;
11025 const data = this.data;
11026 const width = data.rect[2] - data.rect[0];
11027 const height = data.rect[3] - data.rect[1];
11028 const svg = this.svgFactory.create(width, height);
11029 let points = [];
11030
11031 for (const coordinate of data.vertices) {
11032 const x = coordinate.x - data.rect[0];
11033 const y = data.rect[3] - coordinate.y;
11034 points.push(x + "," + y);
11035 }
11036
11037 points = points.join(" ");
11038 const polyline = this.svgFactory.createElement(this.svgElementName);
11039 polyline.setAttribute("points", points);
11040 polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
11041 polyline.setAttribute("stroke", "transparent");
11042 polyline.setAttribute("fill", "transparent");
11043 svg.appendChild(polyline);
11044 this.container.append(svg);
11045
11046 this._createPopup(polyline, data);
11047
11048 return this.container;
11049 }
11050
11051}
11052
11053class PolygonAnnotationElement extends PolylineAnnotationElement {
11054 constructor(parameters) {
11055 super(parameters);
11056 this.containerClassName = "polygonAnnotation";
11057 this.svgElementName = "svg:polygon";
11058 }
11059
11060}
11061
11062class CaretAnnotationElement extends AnnotationElement {
11063 constructor(parameters) {
11064 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11065 super(parameters, {
11066 isRenderable,
11067 ignoreBorder: true
11068 });
11069 }
11070
11071 render() {
11072 this.container.className = "caretAnnotation";
11073
11074 if (!this.data.hasPopup) {
11075 this._createPopup(null, this.data);
11076 }
11077
11078 return this.container;
11079 }
11080
11081}
11082
11083class InkAnnotationElement extends AnnotationElement {
11084 constructor(parameters) {
11085 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11086 super(parameters, {
11087 isRenderable,
11088 ignoreBorder: true
11089 });
11090 this.containerClassName = "inkAnnotation";
11091 this.svgElementName = "svg:polyline";
11092 }
11093
11094 render() {
11095 this.container.className = this.containerClassName;
11096 const data = this.data;
11097 const width = data.rect[2] - data.rect[0];
11098 const height = data.rect[3] - data.rect[1];
11099 const svg = this.svgFactory.create(width, height);
11100
11101 for (const inkList of data.inkLists) {
11102 let points = [];
11103
11104 for (const coordinate of inkList) {
11105 const x = coordinate.x - data.rect[0];
11106 const y = data.rect[3] - coordinate.y;
11107 points.push(`${x},${y}`);
11108 }
11109
11110 points = points.join(" ");
11111 const polyline = this.svgFactory.createElement(this.svgElementName);
11112 polyline.setAttribute("points", points);
11113 polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
11114 polyline.setAttribute("stroke", "transparent");
11115 polyline.setAttribute("fill", "transparent");
11116
11117 this._createPopup(polyline, data);
11118
11119 svg.appendChild(polyline);
11120 }
11121
11122 this.container.append(svg);
11123 return this.container;
11124 }
11125
11126}
11127
11128class HighlightAnnotationElement extends AnnotationElement {
11129 constructor(parameters) {
11130 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11131 super(parameters, {
11132 isRenderable,
11133 ignoreBorder: true,
11134 createQuadrilaterals: true
11135 });
11136 }
11137
11138 render() {
11139 if (!this.data.hasPopup) {
11140 this._createPopup(null, this.data);
11141 }
11142
11143 if (this.quadrilaterals) {
11144 return this._renderQuadrilaterals("highlightAnnotation");
11145 }
11146
11147 this.container.className = "highlightAnnotation";
11148 return this.container;
11149 }
11150
11151}
11152
11153class UnderlineAnnotationElement extends AnnotationElement {
11154 constructor(parameters) {
11155 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11156 super(parameters, {
11157 isRenderable,
11158 ignoreBorder: true,
11159 createQuadrilaterals: true
11160 });
11161 }
11162
11163 render() {
11164 if (!this.data.hasPopup) {
11165 this._createPopup(null, this.data);
11166 }
11167
11168 if (this.quadrilaterals) {
11169 return this._renderQuadrilaterals("underlineAnnotation");
11170 }
11171
11172 this.container.className = "underlineAnnotation";
11173 return this.container;
11174 }
11175
11176}
11177
11178class SquigglyAnnotationElement extends AnnotationElement {
11179 constructor(parameters) {
11180 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11181 super(parameters, {
11182 isRenderable,
11183 ignoreBorder: true,
11184 createQuadrilaterals: true
11185 });
11186 }
11187
11188 render() {
11189 if (!this.data.hasPopup) {
11190 this._createPopup(null, this.data);
11191 }
11192
11193 if (this.quadrilaterals) {
11194 return this._renderQuadrilaterals("squigglyAnnotation");
11195 }
11196
11197 this.container.className = "squigglyAnnotation";
11198 return this.container;
11199 }
11200
11201}
11202
11203class StrikeOutAnnotationElement extends AnnotationElement {
11204 constructor(parameters) {
11205 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11206 super(parameters, {
11207 isRenderable,
11208 ignoreBorder: true,
11209 createQuadrilaterals: true
11210 });
11211 }
11212
11213 render() {
11214 if (!this.data.hasPopup) {
11215 this._createPopup(null, this.data);
11216 }
11217
11218 if (this.quadrilaterals) {
11219 return this._renderQuadrilaterals("strikeoutAnnotation");
11220 }
11221
11222 this.container.className = "strikeoutAnnotation";
11223 return this.container;
11224 }
11225
11226}
11227
11228class StampAnnotationElement extends AnnotationElement {
11229 constructor(parameters) {
11230 const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11231 super(parameters, {
11232 isRenderable,
11233 ignoreBorder: true
11234 });
11235 }
11236
11237 render() {
11238 this.container.className = "stampAnnotation";
11239
11240 if (!this.data.hasPopup) {
11241 this._createPopup(null, this.data);
11242 }
11243
11244 return this.container;
11245 }
11246
11247}
11248
11249class FileAttachmentAnnotationElement extends AnnotationElement {
11250 constructor(parameters) {
11251 super(parameters, {
11252 isRenderable: true
11253 });
11254 const {
11255 filename,
11256 content
11257 } = this.data.file;
11258 this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
11259 this.content = content;
11260 this.linkService.eventBus?.dispatch("fileattachmentannotation", {
11261 source: this,
11262 id: (0, _util.stringToPDFString)(filename),
11263 filename,
11264 content
11265 });
11266 }
11267
11268 render() {
11269 this.container.className = "fileAttachmentAnnotation";
11270 const trigger = document.createElement("div");
11271 trigger.style.height = this.container.style.height;
11272 trigger.style.width = this.container.style.width;
11273 trigger.addEventListener("dblclick", this._download.bind(this));
11274
11275 if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
11276 this._createPopup(trigger, this.data);
11277 }
11278
11279 this.container.appendChild(trigger);
11280 return this.container;
11281 }
11282
11283 _download() {
11284 this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
11285 }
11286
11287}
11288
11289class AnnotationLayer {
11290 static render(parameters) {
11291 const sortedAnnotations = [],
11292 popupAnnotations = [];
11293
11294 for (const data of parameters.annotations) {
11295 if (!data) {
11296 continue;
11297 }
11298
11299 if (data.annotationType === _util.AnnotationType.POPUP) {
11300 popupAnnotations.push(data);
11301 continue;
11302 }
11303
11304 sortedAnnotations.push(data);
11305 }
11306
11307 if (popupAnnotations.length) {
11308 sortedAnnotations.push(...popupAnnotations);
11309 }
11310
11311 const div = parameters.div;
11312
11313 for (const data of sortedAnnotations) {
11314 const element = AnnotationElementFactory.create({
11315 data,
11316 layer: div,
11317 page: parameters.page,
11318 viewport: parameters.viewport,
11319 linkService: parameters.linkService,
11320 downloadManager: parameters.downloadManager,
11321 imageResourcesPath: parameters.imageResourcesPath || "",
11322 renderForms: parameters.renderForms !== false,
11323 svgFactory: new _display_utils.DOMSVGFactory(),
11324 annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
11325 enableScripting: parameters.enableScripting,
11326 hasJSActions: parameters.hasJSActions,
11327 fieldObjects: parameters.fieldObjects,
11328 mouseState: parameters.mouseState || {
11329 isDown: false
11330 }
11331 });
11332
11333 if (element.isRenderable) {
11334 const rendered = element.render();
11335
11336 if (data.hidden) {
11337 rendered.style.visibility = "hidden";
11338 }
11339
11340 if (Array.isArray(rendered)) {
11341 for (const renderedElement of rendered) {
11342 div.appendChild(renderedElement);
11343 }
11344 } else {
11345 if (element instanceof PopupAnnotationElement) {
11346 div.prepend(rendered);
11347 } else {
11348 div.appendChild(rendered);
11349 }
11350 }
11351 }
11352 }
11353
11354 this.#setAnnotationCanvasMap(div, parameters.annotationCanvasMap);
11355 }
11356
11357 static update(parameters) {
11358 const {
11359 page,
11360 viewport,
11361 annotations,
11362 annotationCanvasMap,
11363 div
11364 } = parameters;
11365 const transform = viewport.transform;
11366 const matrix = `matrix(${transform.join(",")})`;
11367 let scale, ownMatrix;
11368
11369 for (const data of annotations) {
11370 const elements = div.querySelectorAll(`[data-annotation-id="${data.id}"]`);
11371
11372 if (elements) {
11373 for (const element of elements) {
11374 if (data.hasOwnCanvas) {
11375 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]]);
11376
11377 if (!ownMatrix) {
11378 scale = Math.abs(transform[0] || transform[1]);
11379 const ownTransform = transform.slice();
11380
11381 for (let i = 0; i < 4; i++) {
11382 ownTransform[i] = Math.sign(ownTransform[i]);
11383 }
11384
11385 ownMatrix = `matrix(${ownTransform.join(",")})`;
11386 }
11387
11388 const left = rect[0] * scale;
11389 const top = rect[1] * scale;
11390 element.style.left = `${left}px`;
11391 element.style.top = `${top}px`;
11392 element.style.transformOrigin = `${-left}px ${-top}px`;
11393 element.style.transform = ownMatrix;
11394 } else {
11395 element.style.transform = matrix;
11396 }
11397 }
11398 }
11399 }
11400
11401 this.#setAnnotationCanvasMap(div, annotationCanvasMap);
11402 div.hidden = false;
11403 }
11404
11405 static #setAnnotationCanvasMap(div, annotationCanvasMap) {
11406 if (!annotationCanvasMap) {
11407 return;
11408 }
11409
11410 for (const [id, canvas] of annotationCanvasMap) {
11411 const element = div.querySelector(`[data-annotation-id="${id}"]`);
11412
11413 if (!element) {
11414 continue;
11415 }
11416
11417 const {
11418 firstChild
11419 } = element;
11420
11421 if (firstChild.nodeName === "CANVAS") {
11422 element.replaceChild(canvas, firstChild);
11423 } else {
11424 element.insertBefore(canvas, firstChild);
11425 }
11426 }
11427
11428 annotationCanvasMap.clear();
11429 }
11430
11431}
11432
11433exports.AnnotationLayer = AnnotationLayer;
11434
11435/***/ }),
11436/* 19 */
11437/***/ ((__unused_webpack_module, exports) => {
11438
11439
11440
11441Object.defineProperty(exports, "__esModule", ({
11442 value: true
11443}));
11444exports.ColorConverters = void 0;
11445
11446function makeColorComp(n) {
11447 return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
11448}
11449
11450class ColorConverters {
11451 static CMYK_G([c, y, m, k]) {
11452 return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
11453 }
11454
11455 static G_CMYK([g]) {
11456 return ["CMYK", 0, 0, 0, 1 - g];
11457 }
11458
11459 static G_RGB([g]) {
11460 return ["RGB", g, g, g];
11461 }
11462
11463 static G_HTML([g]) {
11464 const G = makeColorComp(g);
11465 return `#${G}${G}${G}`;
11466 }
11467
11468 static RGB_G([r, g, b]) {
11469 return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
11470 }
11471
11472 static RGB_HTML([r, g, b]) {
11473 const R = makeColorComp(r);
11474 const G = makeColorComp(g);
11475 const B = makeColorComp(b);
11476 return `#${R}${G}${B}`;
11477 }
11478
11479 static T_HTML() {
11480 return "#00000000";
11481 }
11482
11483 static CMYK_RGB([c, y, m, k]) {
11484 return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
11485 }
11486
11487 static CMYK_HTML(components) {
11488 return this.RGB_HTML(this.CMYK_RGB(components));
11489 }
11490
11491 static RGB_CMYK([r, g, b]) {
11492 const c = 1 - r;
11493 const m = 1 - g;
11494 const y = 1 - b;
11495 const k = Math.min(c, m, y);
11496 return ["CMYK", c, m, y, k];
11497 }
11498
11499}
11500
11501exports.ColorConverters = ColorConverters;
11502
11503/***/ }),
11504/* 20 */
11505/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11506
11507
11508
11509Object.defineProperty(exports, "__esModule", ({
11510 value: true
11511}));
11512exports.XfaLayer = void 0;
11513
11514var _util = __w_pdfjs_require__(2);
11515
11516var _xfa_text = __w_pdfjs_require__(17);
11517
11518class XfaLayer {
11519 static setupStorage(html, id, element, storage, intent) {
11520 const storedData = storage.getValue(id, {
11521 value: null
11522 });
11523
11524 switch (element.name) {
11525 case "textarea":
11526 if (storedData.value !== null) {
11527 html.textContent = storedData.value;
11528 }
11529
11530 if (intent === "print") {
11531 break;
11532 }
11533
11534 html.addEventListener("input", event => {
11535 storage.setValue(id, {
11536 value: event.target.value
11537 });
11538 });
11539 break;
11540
11541 case "input":
11542 if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
11543 if (storedData.value === element.attributes.xfaOn) {
11544 html.setAttribute("checked", true);
11545 } else if (storedData.value === element.attributes.xfaOff) {
11546 html.removeAttribute("checked");
11547 }
11548
11549 if (intent === "print") {
11550 break;
11551 }
11552
11553 html.addEventListener("change", event => {
11554 storage.setValue(id, {
11555 value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
11556 });
11557 });
11558 } else {
11559 if (storedData.value !== null) {
11560 html.setAttribute("value", storedData.value);
11561 }
11562
11563 if (intent === "print") {
11564 break;
11565 }
11566
11567 html.addEventListener("input", event => {
11568 storage.setValue(id, {
11569 value: event.target.value
11570 });
11571 });
11572 }
11573
11574 break;
11575
11576 case "select":
11577 if (storedData.value !== null) {
11578 for (const option of element.children) {
11579 if (option.attributes.value === storedData.value) {
11580 option.attributes.selected = true;
11581 }
11582 }
11583 }
11584
11585 html.addEventListener("input", event => {
11586 const options = event.target.options;
11587 const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
11588 storage.setValue(id, {
11589 value
11590 });
11591 });
11592 break;
11593 }
11594 }
11595
11596 static setAttributes({
11597 html,
11598 element,
11599 storage = null,
11600 intent,
11601 linkService
11602 }) {
11603 const {
11604 attributes
11605 } = element;
11606 const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
11607
11608 if (attributes.type === "radio") {
11609 attributes.name = `${attributes.name}-${intent}`;
11610 }
11611
11612 for (const [key, value] of Object.entries(attributes)) {
11613 if (value === null || value === undefined || key === "dataId") {
11614 continue;
11615 }
11616
11617 if (key !== "style") {
11618 if (key === "textContent") {
11619 html.textContent = value;
11620 } else if (key === "class") {
11621 if (value.length) {
11622 html.setAttribute(key, value.join(" "));
11623 }
11624 } else {
11625 if (isHTMLAnchorElement && (key === "href" || key === "newWindow")) {
11626 continue;
11627 }
11628
11629 html.setAttribute(key, value);
11630 }
11631 } else {
11632 Object.assign(html.style, value);
11633 }
11634 }
11635
11636 if (isHTMLAnchorElement) {
11637 if (!linkService.addLinkAttributes) {
11638 (0, _util.warn)("XfaLayer.setAttribute - missing `addLinkAttributes`-method on the `linkService`-instance.");
11639 }
11640
11641 linkService.addLinkAttributes?.(html, attributes.href, attributes.newWindow);
11642 }
11643
11644 if (storage && attributes.dataId) {
11645 this.setupStorage(html, attributes.dataId, element, storage);
11646 }
11647 }
11648
11649 static render(parameters) {
11650 const storage = parameters.annotationStorage;
11651 const linkService = parameters.linkService;
11652 const root = parameters.xfaHtml;
11653 const intent = parameters.intent || "display";
11654 const rootHtml = document.createElement(root.name);
11655
11656 if (root.attributes) {
11657 this.setAttributes({
11658 html: rootHtml,
11659 element: root,
11660 intent,
11661 linkService
11662 });
11663 }
11664
11665 const stack = [[root, -1, rootHtml]];
11666 const rootDiv = parameters.div;
11667 rootDiv.appendChild(rootHtml);
11668
11669 if (parameters.viewport) {
11670 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
11671 rootDiv.style.transform = transform;
11672 }
11673
11674 if (intent !== "richText") {
11675 rootDiv.setAttribute("class", "xfaLayer xfaFont");
11676 }
11677
11678 const textDivs = [];
11679
11680 while (stack.length > 0) {
11681 const [parent, i, html] = stack[stack.length - 1];
11682
11683 if (i + 1 === parent.children.length) {
11684 stack.pop();
11685 continue;
11686 }
11687
11688 const child = parent.children[++stack[stack.length - 1][1]];
11689
11690 if (child === null) {
11691 continue;
11692 }
11693
11694 const {
11695 name
11696 } = child;
11697
11698 if (name === "#text") {
11699 const node = document.createTextNode(child.value);
11700 textDivs.push(node);
11701 html.appendChild(node);
11702 continue;
11703 }
11704
11705 let childHtml;
11706
11707 if (child?.attributes?.xmlns) {
11708 childHtml = document.createElementNS(child.attributes.xmlns, name);
11709 } else {
11710 childHtml = document.createElement(name);
11711 }
11712
11713 html.appendChild(childHtml);
11714
11715 if (child.attributes) {
11716 this.setAttributes({
11717 html: childHtml,
11718 element: child,
11719 storage,
11720 intent,
11721 linkService
11722 });
11723 }
11724
11725 if (child.children && child.children.length > 0) {
11726 stack.push([child, -1, childHtml]);
11727 } else if (child.value) {
11728 const node = document.createTextNode(child.value);
11729
11730 if (_xfa_text.XfaText.shouldBuildText(name)) {
11731 textDivs.push(node);
11732 }
11733
11734 childHtml.appendChild(node);
11735 }
11736 }
11737
11738 for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
11739 el.setAttribute("readOnly", true);
11740 }
11741
11742 return {
11743 textDivs
11744 };
11745 }
11746
11747 static update(parameters) {
11748 const transform = `matrix(${parameters.viewport.transform.join(",")})`;
11749 parameters.div.style.transform = transform;
11750 parameters.div.hidden = false;
11751 }
11752
11753}
11754
11755exports.XfaLayer = XfaLayer;
11756
11757/***/ }),
11758/* 21 */
11759/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11760
11761
11762
11763Object.defineProperty(exports, "__esModule", ({
11764 value: true
11765}));
11766exports.renderTextLayer = renderTextLayer;
11767
11768var _util = __w_pdfjs_require__(2);
11769
11770const MAX_TEXT_DIVS_TO_RENDER = 100000;
11771const DEFAULT_FONT_SIZE = 30;
11772const DEFAULT_FONT_ASCENT = 0.8;
11773const ascentCache = new Map();
11774const AllWhitespaceRegexp = /^\s+$/g;
11775
11776function getAscent(fontFamily, ctx) {
11777 const cachedAscent = ascentCache.get(fontFamily);
11778
11779 if (cachedAscent) {
11780 return cachedAscent;
11781 }
11782
11783 ctx.save();
11784 ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
11785 const metrics = ctx.measureText("");
11786 let ascent = metrics.fontBoundingBoxAscent;
11787 let descent = Math.abs(metrics.fontBoundingBoxDescent);
11788
11789 if (ascent) {
11790 ctx.restore();
11791 const ratio = ascent / (ascent + descent);
11792 ascentCache.set(fontFamily, ratio);
11793 return ratio;
11794 }
11795
11796 ctx.strokeStyle = "red";
11797 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
11798 ctx.strokeText("g", 0, 0);
11799 let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
11800 descent = 0;
11801
11802 for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
11803 if (pixels[i] > 0) {
11804 descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
11805 break;
11806 }
11807 }
11808
11809 ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
11810 ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
11811 pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
11812 ascent = 0;
11813
11814 for (let i = 0, ii = pixels.length; i < ii; i += 4) {
11815 if (pixels[i] > 0) {
11816 ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
11817 break;
11818 }
11819 }
11820
11821 ctx.restore();
11822
11823 if (ascent) {
11824 const ratio = ascent / (ascent + descent);
11825 ascentCache.set(fontFamily, ratio);
11826 return ratio;
11827 }
11828
11829 ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
11830 return DEFAULT_FONT_ASCENT;
11831}
11832
11833function appendText(task, geom, styles, ctx) {
11834 const textDiv = document.createElement("span");
11835 const textDivProperties = task._enhanceTextSelection ? {
11836 angle: 0,
11837 canvasWidth: 0,
11838 hasText: geom.str !== "",
11839 hasEOL: geom.hasEOL,
11840 originalTransform: null,
11841 paddingBottom: 0,
11842 paddingLeft: 0,
11843 paddingRight: 0,
11844 paddingTop: 0,
11845 scale: 1
11846 } : {
11847 angle: 0,
11848 canvasWidth: 0,
11849 hasText: geom.str !== "",
11850 hasEOL: geom.hasEOL
11851 };
11852
11853 task._textDivs.push(textDiv);
11854
11855 const tx = _util.Util.transform(task._viewport.transform, geom.transform);
11856
11857 let angle = Math.atan2(tx[1], tx[0]);
11858 const style = styles[geom.fontName];
11859
11860 if (style.vertical) {
11861 angle += Math.PI / 2;
11862 }
11863
11864 const fontHeight = Math.hypot(tx[2], tx[3]);
11865 const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
11866 let left, top;
11867
11868 if (angle === 0) {
11869 left = tx[4];
11870 top = tx[5] - fontAscent;
11871 } else {
11872 left = tx[4] + fontAscent * Math.sin(angle);
11873 top = tx[5] - fontAscent * Math.cos(angle);
11874 }
11875
11876 textDiv.style.left = `${left}px`;
11877 textDiv.style.top = `${top}px`;
11878 textDiv.style.fontSize = `${fontHeight}px`;
11879 textDiv.style.fontFamily = style.fontFamily;
11880 textDiv.setAttribute("role", "presentation");
11881 textDiv.textContent = geom.str;
11882 textDiv.dir = geom.dir;
11883
11884 if (task._fontInspectorEnabled) {
11885 textDiv.dataset.fontName = geom.fontName;
11886 }
11887
11888 if (angle !== 0) {
11889 textDivProperties.angle = angle * (180 / Math.PI);
11890 }
11891
11892 let shouldScaleText = false;
11893
11894 if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
11895 shouldScaleText = true;
11896 } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
11897 const absScaleX = Math.abs(geom.transform[0]),
11898 absScaleY = Math.abs(geom.transform[3]);
11899
11900 if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
11901 shouldScaleText = true;
11902 }
11903 }
11904
11905 if (shouldScaleText) {
11906 if (style.vertical) {
11907 textDivProperties.canvasWidth = geom.height * task._viewport.scale;
11908 } else {
11909 textDivProperties.canvasWidth = geom.width * task._viewport.scale;
11910 }
11911 }
11912
11913 task._textDivProperties.set(textDiv, textDivProperties);
11914
11915 if (task._textContentStream) {
11916 task._layoutText(textDiv);
11917 }
11918
11919 if (task._enhanceTextSelection && textDivProperties.hasText) {
11920 let angleCos = 1,
11921 angleSin = 0;
11922
11923 if (angle !== 0) {
11924 angleCos = Math.cos(angle);
11925 angleSin = Math.sin(angle);
11926 }
11927
11928 const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
11929 const divHeight = fontHeight;
11930 let m, b;
11931
11932 if (angle !== 0) {
11933 m = [angleCos, angleSin, -angleSin, angleCos, left, top];
11934 b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
11935 } else {
11936 b = [left, top, left + divWidth, top + divHeight];
11937 }
11938
11939 task._bounds.push({
11940 left: b[0],
11941 top: b[1],
11942 right: b[2],
11943 bottom: b[3],
11944 div: textDiv,
11945 size: [divWidth, divHeight],
11946 m
11947 });
11948 }
11949}
11950
11951function render(task) {
11952 if (task._canceled) {
11953 return;
11954 }
11955
11956 const textDivs = task._textDivs;
11957 const capability = task._capability;
11958 const textDivsLength = textDivs.length;
11959
11960 if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
11961 task._renderingDone = true;
11962 capability.resolve();
11963 return;
11964 }
11965
11966 if (!task._textContentStream) {
11967 for (let i = 0; i < textDivsLength; i++) {
11968 task._layoutText(textDivs[i]);
11969 }
11970 }
11971
11972 task._renderingDone = true;
11973 capability.resolve();
11974}
11975
11976function findPositiveMin(ts, offset, count) {
11977 let result = 0;
11978
11979 for (let i = 0; i < count; i++) {
11980 const t = ts[offset++];
11981
11982 if (t > 0) {
11983 result = result ? Math.min(t, result) : t;
11984 }
11985 }
11986
11987 return result;
11988}
11989
11990function expand(task) {
11991 const bounds = task._bounds;
11992 const viewport = task._viewport;
11993 const expanded = expandBounds(viewport.width, viewport.height, bounds);
11994
11995 for (let i = 0; i < expanded.length; i++) {
11996 const div = bounds[i].div;
11997
11998 const divProperties = task._textDivProperties.get(div);
11999
12000 if (divProperties.angle === 0) {
12001 divProperties.paddingLeft = bounds[i].left - expanded[i].left;
12002 divProperties.paddingTop = bounds[i].top - expanded[i].top;
12003 divProperties.paddingRight = expanded[i].right - bounds[i].right;
12004 divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
12005
12006 task._textDivProperties.set(div, divProperties);
12007
12008 continue;
12009 }
12010
12011 const e = expanded[i],
12012 b = bounds[i];
12013 const m = b.m,
12014 c = m[0],
12015 s = m[1];
12016 const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
12017 const ts = new Float64Array(64);
12018
12019 for (let j = 0, jj = points.length; j < jj; j++) {
12020 const t = _util.Util.applyTransform(points[j], m);
12021
12022 ts[j + 0] = c && (e.left - t[0]) / c;
12023 ts[j + 4] = s && (e.top - t[1]) / s;
12024 ts[j + 8] = c && (e.right - t[0]) / c;
12025 ts[j + 12] = s && (e.bottom - t[1]) / s;
12026 ts[j + 16] = s && (e.left - t[0]) / -s;
12027 ts[j + 20] = c && (e.top - t[1]) / c;
12028 ts[j + 24] = s && (e.right - t[0]) / -s;
12029 ts[j + 28] = c && (e.bottom - t[1]) / c;
12030 ts[j + 32] = c && (e.left - t[0]) / -c;
12031 ts[j + 36] = s && (e.top - t[1]) / -s;
12032 ts[j + 40] = c && (e.right - t[0]) / -c;
12033 ts[j + 44] = s && (e.bottom - t[1]) / -s;
12034 ts[j + 48] = s && (e.left - t[0]) / s;
12035 ts[j + 52] = c && (e.top - t[1]) / -c;
12036 ts[j + 56] = s && (e.right - t[0]) / s;
12037 ts[j + 60] = c && (e.bottom - t[1]) / -c;
12038 }
12039
12040 const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
12041 divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
12042 divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
12043 divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
12044 divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
12045
12046 task._textDivProperties.set(div, divProperties);
12047 }
12048}
12049
12050function expandBounds(width, height, boxes) {
12051 const bounds = boxes.map(function (box, i) {
12052 return {
12053 x1: box.left,
12054 y1: box.top,
12055 x2: box.right,
12056 y2: box.bottom,
12057 index: i,
12058 x1New: undefined,
12059 x2New: undefined
12060 };
12061 });
12062 expandBoundsLTR(width, bounds);
12063 const expanded = new Array(boxes.length);
12064
12065 for (const b of bounds) {
12066 const i = b.index;
12067 expanded[i] = {
12068 left: b.x1New,
12069 top: 0,
12070 right: b.x2New,
12071 bottom: 0
12072 };
12073 }
12074
12075 boxes.map(function (box, i) {
12076 const e = expanded[i],
12077 b = bounds[i];
12078 b.x1 = box.top;
12079 b.y1 = width - e.right;
12080 b.x2 = box.bottom;
12081 b.y2 = width - e.left;
12082 b.index = i;
12083 b.x1New = undefined;
12084 b.x2New = undefined;
12085 });
12086 expandBoundsLTR(height, bounds);
12087
12088 for (const b of bounds) {
12089 const i = b.index;
12090 expanded[i].top = b.x1New;
12091 expanded[i].bottom = b.x2New;
12092 }
12093
12094 return expanded;
12095}
12096
12097function expandBoundsLTR(width, bounds) {
12098 bounds.sort(function (a, b) {
12099 return a.x1 - b.x1 || a.index - b.index;
12100 });
12101 const fakeBoundary = {
12102 x1: -Infinity,
12103 y1: -Infinity,
12104 x2: 0,
12105 y2: Infinity,
12106 index: -1,
12107 x1New: 0,
12108 x2New: 0
12109 };
12110 const horizon = [{
12111 start: -Infinity,
12112 end: Infinity,
12113 boundary: fakeBoundary
12114 }];
12115
12116 for (const boundary of bounds) {
12117 let i = 0;
12118
12119 while (i < horizon.length && horizon[i].end <= boundary.y1) {
12120 i++;
12121 }
12122
12123 let j = horizon.length - 1;
12124
12125 while (j >= 0 && horizon[j].start >= boundary.y2) {
12126 j--;
12127 }
12128
12129 let horizonPart, affectedBoundary;
12130 let q,
12131 k,
12132 maxXNew = -Infinity;
12133
12134 for (q = i; q <= j; q++) {
12135 horizonPart = horizon[q];
12136 affectedBoundary = horizonPart.boundary;
12137 let xNew;
12138
12139 if (affectedBoundary.x2 > boundary.x1) {
12140 xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
12141 } else if (affectedBoundary.x2New === undefined) {
12142 xNew = (affectedBoundary.x2 + boundary.x1) / 2;
12143 } else {
12144 xNew = affectedBoundary.x2New;
12145 }
12146
12147 if (xNew > maxXNew) {
12148 maxXNew = xNew;
12149 }
12150 }
12151
12152 boundary.x1New = maxXNew;
12153
12154 for (q = i; q <= j; q++) {
12155 horizonPart = horizon[q];
12156 affectedBoundary = horizonPart.boundary;
12157
12158 if (affectedBoundary.x2New === undefined) {
12159 if (affectedBoundary.x2 > boundary.x1) {
12160 if (affectedBoundary.index > boundary.index) {
12161 affectedBoundary.x2New = affectedBoundary.x2;
12162 }
12163 } else {
12164 affectedBoundary.x2New = maxXNew;
12165 }
12166 } else if (affectedBoundary.x2New > maxXNew) {
12167 affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
12168 }
12169 }
12170
12171 const changedHorizon = [];
12172 let lastBoundary = null;
12173
12174 for (q = i; q <= j; q++) {
12175 horizonPart = horizon[q];
12176 affectedBoundary = horizonPart.boundary;
12177 const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
12178
12179 if (lastBoundary === useBoundary) {
12180 changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
12181 } else {
12182 changedHorizon.push({
12183 start: horizonPart.start,
12184 end: horizonPart.end,
12185 boundary: useBoundary
12186 });
12187 lastBoundary = useBoundary;
12188 }
12189 }
12190
12191 if (horizon[i].start < boundary.y1) {
12192 changedHorizon[0].start = boundary.y1;
12193 changedHorizon.unshift({
12194 start: horizon[i].start,
12195 end: boundary.y1,
12196 boundary: horizon[i].boundary
12197 });
12198 }
12199
12200 if (boundary.y2 < horizon[j].end) {
12201 changedHorizon[changedHorizon.length - 1].end = boundary.y2;
12202 changedHorizon.push({
12203 start: boundary.y2,
12204 end: horizon[j].end,
12205 boundary: horizon[j].boundary
12206 });
12207 }
12208
12209 for (q = i; q <= j; q++) {
12210 horizonPart = horizon[q];
12211 affectedBoundary = horizonPart.boundary;
12212
12213 if (affectedBoundary.x2New !== undefined) {
12214 continue;
12215 }
12216
12217 let used = false;
12218
12219 for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
12220 used = horizon[k].boundary === affectedBoundary;
12221 }
12222
12223 for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
12224 used = horizon[k].boundary === affectedBoundary;
12225 }
12226
12227 for (k = 0; !used && k < changedHorizon.length; k++) {
12228 used = changedHorizon[k].boundary === affectedBoundary;
12229 }
12230
12231 if (!used) {
12232 affectedBoundary.x2New = maxXNew;
12233 }
12234 }
12235
12236 Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
12237 }
12238
12239 for (const horizonPart of horizon) {
12240 const affectedBoundary = horizonPart.boundary;
12241
12242 if (affectedBoundary.x2New === undefined) {
12243 affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
12244 }
12245 }
12246}
12247
12248class TextLayerRenderTask {
12249 constructor({
12250 textContent,
12251 textContentStream,
12252 container,
12253 viewport,
12254 textDivs,
12255 textContentItemsStr,
12256 enhanceTextSelection
12257 }) {
12258 this._textContent = textContent;
12259 this._textContentStream = textContentStream;
12260 this._container = container;
12261 this._document = container.ownerDocument;
12262 this._viewport = viewport;
12263 this._textDivs = textDivs || [];
12264 this._textContentItemsStr = textContentItemsStr || [];
12265 this._enhanceTextSelection = !!enhanceTextSelection;
12266 this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
12267 this._reader = null;
12268 this._layoutTextLastFontSize = null;
12269 this._layoutTextLastFontFamily = null;
12270 this._layoutTextCtx = null;
12271 this._textDivProperties = new WeakMap();
12272 this._renderingDone = false;
12273 this._canceled = false;
12274 this._capability = (0, _util.createPromiseCapability)();
12275 this._renderTimer = null;
12276 this._bounds = [];
12277
12278 this._capability.promise.finally(() => {
12279 if (!this._enhanceTextSelection) {
12280 this._textDivProperties = null;
12281 }
12282
12283 if (this._layoutTextCtx) {
12284 this._layoutTextCtx.canvas.width = 0;
12285 this._layoutTextCtx.canvas.height = 0;
12286 this._layoutTextCtx = null;
12287 }
12288 }).catch(() => {});
12289 }
12290
12291 get promise() {
12292 return this._capability.promise;
12293 }
12294
12295 cancel() {
12296 this._canceled = true;
12297
12298 if (this._reader) {
12299 this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
12300
12301 this._reader = null;
12302 }
12303
12304 if (this._renderTimer !== null) {
12305 clearTimeout(this._renderTimer);
12306 this._renderTimer = null;
12307 }
12308
12309 this._capability.reject(new Error("TextLayer task cancelled."));
12310 }
12311
12312 _processItems(items, styleCache) {
12313 for (let i = 0, len = items.length; i < len; i++) {
12314 if (items[i].str === undefined) {
12315 if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
12316 const parent = this._container;
12317 this._container = document.createElement("span");
12318
12319 this._container.classList.add("markedContent");
12320
12321 if (items[i].id !== null) {
12322 this._container.setAttribute("id", `${items[i].id}`);
12323 }
12324
12325 parent.appendChild(this._container);
12326 } else if (items[i].type === "endMarkedContent") {
12327 this._container = this._container.parentNode;
12328 }
12329
12330 continue;
12331 }
12332
12333 this._textContentItemsStr.push(items[i].str);
12334
12335 appendText(this, items[i], styleCache, this._layoutTextCtx);
12336 }
12337 }
12338
12339 _layoutText(textDiv) {
12340 const textDivProperties = this._textDivProperties.get(textDiv);
12341
12342 let transform = "";
12343
12344 if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
12345 const {
12346 fontSize,
12347 fontFamily
12348 } = textDiv.style;
12349
12350 if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
12351 this._layoutTextCtx.font = `${fontSize} ${fontFamily}`;
12352 this._layoutTextLastFontSize = fontSize;
12353 this._layoutTextLastFontFamily = fontFamily;
12354 }
12355
12356 const {
12357 width
12358 } = this._layoutTextCtx.measureText(textDiv.textContent);
12359
12360 if (width > 0) {
12361 const scale = textDivProperties.canvasWidth / width;
12362
12363 if (this._enhanceTextSelection) {
12364 textDivProperties.scale = scale;
12365 }
12366
12367 transform = `scaleX(${scale})`;
12368 }
12369 }
12370
12371 if (textDivProperties.angle !== 0) {
12372 transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
12373 }
12374
12375 if (transform.length > 0) {
12376 if (this._enhanceTextSelection) {
12377 textDivProperties.originalTransform = transform;
12378 }
12379
12380 textDiv.style.transform = transform;
12381 }
12382
12383 if (textDivProperties.hasText) {
12384 this._container.appendChild(textDiv);
12385 }
12386
12387 if (textDivProperties.hasEOL) {
12388 const br = document.createElement("br");
12389 br.setAttribute("role", "presentation");
12390
12391 this._container.appendChild(br);
12392 }
12393 }
12394
12395 _render(timeout = 0) {
12396 const capability = (0, _util.createPromiseCapability)();
12397 let styleCache = Object.create(null);
12398
12399 const canvas = this._document.createElement("canvas");
12400
12401 canvas.height = canvas.width = DEFAULT_FONT_SIZE;
12402 canvas.mozOpaque = true;
12403 this._layoutTextCtx = canvas.getContext("2d", {
12404 alpha: false
12405 });
12406
12407 if (this._textContent) {
12408 const textItems = this._textContent.items;
12409 const textStyles = this._textContent.styles;
12410
12411 this._processItems(textItems, textStyles);
12412
12413 capability.resolve();
12414 } else if (this._textContentStream) {
12415 const pump = () => {
12416 this._reader.read().then(({
12417 value,
12418 done
12419 }) => {
12420 if (done) {
12421 capability.resolve();
12422 return;
12423 }
12424
12425 Object.assign(styleCache, value.styles);
12426
12427 this._processItems(value.items, styleCache);
12428
12429 pump();
12430 }, capability.reject);
12431 };
12432
12433 this._reader = this._textContentStream.getReader();
12434 pump();
12435 } else {
12436 throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');
12437 }
12438
12439 capability.promise.then(() => {
12440 styleCache = null;
12441
12442 if (!timeout) {
12443 render(this);
12444 } else {
12445 this._renderTimer = setTimeout(() => {
12446 render(this);
12447 this._renderTimer = null;
12448 }, timeout);
12449 }
12450 }, this._capability.reject);
12451 }
12452
12453 expandTextDivs(expandDivs = false) {
12454 if (!this._enhanceTextSelection || !this._renderingDone) {
12455 return;
12456 }
12457
12458 if (this._bounds !== null) {
12459 expand(this);
12460 this._bounds = null;
12461 }
12462
12463 const transformBuf = [],
12464 paddingBuf = [];
12465
12466 for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
12467 const div = this._textDivs[i];
12468
12469 const divProps = this._textDivProperties.get(div);
12470
12471 if (!divProps.hasText) {
12472 continue;
12473 }
12474
12475 if (expandDivs) {
12476 transformBuf.length = 0;
12477 paddingBuf.length = 0;
12478
12479 if (divProps.originalTransform) {
12480 transformBuf.push(divProps.originalTransform);
12481 }
12482
12483 if (divProps.paddingTop > 0) {
12484 paddingBuf.push(`${divProps.paddingTop}px`);
12485 transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
12486 } else {
12487 paddingBuf.push(0);
12488 }
12489
12490 if (divProps.paddingRight > 0) {
12491 paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
12492 } else {
12493 paddingBuf.push(0);
12494 }
12495
12496 if (divProps.paddingBottom > 0) {
12497 paddingBuf.push(`${divProps.paddingBottom}px`);
12498 } else {
12499 paddingBuf.push(0);
12500 }
12501
12502 if (divProps.paddingLeft > 0) {
12503 paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
12504 transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
12505 } else {
12506 paddingBuf.push(0);
12507 }
12508
12509 div.style.padding = paddingBuf.join(" ");
12510
12511 if (transformBuf.length) {
12512 div.style.transform = transformBuf.join(" ");
12513 }
12514 } else {
12515 div.style.padding = null;
12516 div.style.transform = divProps.originalTransform;
12517 }
12518 }
12519 }
12520
12521}
12522
12523function renderTextLayer(renderParameters) {
12524 const task = new TextLayerRenderTask({
12525 textContent: renderParameters.textContent,
12526 textContentStream: renderParameters.textContentStream,
12527 container: renderParameters.container,
12528 viewport: renderParameters.viewport,
12529 textDivs: renderParameters.textDivs,
12530 textContentItemsStr: renderParameters.textContentItemsStr,
12531 enhanceTextSelection: renderParameters.enhanceTextSelection
12532 });
12533
12534 task._render(renderParameters.timeout);
12535
12536 return task;
12537}
12538
12539/***/ }),
12540/* 22 */
12541/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
12542
12543
12544
12545Object.defineProperty(exports, "__esModule", ({
12546 value: true
12547}));
12548exports.SVGGraphics = void 0;
12549
12550var _util = __w_pdfjs_require__(2);
12551
12552var _display_utils = __w_pdfjs_require__(1);
12553
12554var _is_node = __w_pdfjs_require__(4);
12555
12556let SVGGraphics = class {
12557 constructor() {
12558 (0, _util.unreachable)("Not implemented: SVGGraphics");
12559 }
12560
12561};
12562exports.SVGGraphics = SVGGraphics;
12563{
12564 const SVG_DEFAULTS = {
12565 fontStyle: "normal",
12566 fontWeight: "normal",
12567 fillColor: "#000000"
12568 };
12569 const XML_NS = "http://www.w3.org/XML/1998/namespace";
12570 const XLINK_NS = "http://www.w3.org/1999/xlink";
12571 const LINE_CAP_STYLES = ["butt", "round", "square"];
12572 const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
12573
12574 const convertImgDataToPng = function () {
12575 const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
12576 const CHUNK_WRAPPER_SIZE = 12;
12577 const crcTable = new Int32Array(256);
12578
12579 for (let i = 0; i < 256; i++) {
12580 let c = i;
12581
12582 for (let h = 0; h < 8; h++) {
12583 if (c & 1) {
12584 c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
12585 } else {
12586 c = c >> 1 & 0x7fffffff;
12587 }
12588 }
12589
12590 crcTable[i] = c;
12591 }
12592
12593 function crc32(data, start, end) {
12594 let crc = -1;
12595
12596 for (let i = start; i < end; i++) {
12597 const a = (crc ^ data[i]) & 0xff;
12598 const b = crcTable[a];
12599 crc = crc >>> 8 ^ b;
12600 }
12601
12602 return crc ^ -1;
12603 }
12604
12605 function writePngChunk(type, body, data, offset) {
12606 let p = offset;
12607 const len = body.length;
12608 data[p] = len >> 24 & 0xff;
12609 data[p + 1] = len >> 16 & 0xff;
12610 data[p + 2] = len >> 8 & 0xff;
12611 data[p + 3] = len & 0xff;
12612 p += 4;
12613 data[p] = type.charCodeAt(0) & 0xff;
12614 data[p + 1] = type.charCodeAt(1) & 0xff;
12615 data[p + 2] = type.charCodeAt(2) & 0xff;
12616 data[p + 3] = type.charCodeAt(3) & 0xff;
12617 p += 4;
12618 data.set(body, p);
12619 p += body.length;
12620 const crc = crc32(data, offset + 4, p);
12621 data[p] = crc >> 24 & 0xff;
12622 data[p + 1] = crc >> 16 & 0xff;
12623 data[p + 2] = crc >> 8 & 0xff;
12624 data[p + 3] = crc & 0xff;
12625 }
12626
12627 function adler32(data, start, end) {
12628 let a = 1;
12629 let b = 0;
12630
12631 for (let i = start; i < end; ++i) {
12632 a = (a + (data[i] & 0xff)) % 65521;
12633 b = (b + a) % 65521;
12634 }
12635
12636 return b << 16 | a;
12637 }
12638
12639 function deflateSync(literals) {
12640 if (!_is_node.isNodeJS) {
12641 return deflateSyncUncompressed(literals);
12642 }
12643
12644 try {
12645 let input;
12646
12647 if (parseInt(process.versions.node) >= 8) {
12648 input = literals;
12649 } else {
12650 input = Buffer.from(literals);
12651 }
12652
12653 const output = require("zlib").deflateSync(input, {
12654 level: 9
12655 });
12656
12657 return output instanceof Uint8Array ? output : new Uint8Array(output);
12658 } catch (e) {
12659 (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
12660 }
12661
12662 return deflateSyncUncompressed(literals);
12663 }
12664
12665 function deflateSyncUncompressed(literals) {
12666 let len = literals.length;
12667 const maxBlockLength = 0xffff;
12668 const deflateBlocks = Math.ceil(len / maxBlockLength);
12669 const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
12670 let pi = 0;
12671 idat[pi++] = 0x78;
12672 idat[pi++] = 0x9c;
12673 let pos = 0;
12674
12675 while (len > maxBlockLength) {
12676 idat[pi++] = 0x00;
12677 idat[pi++] = 0xff;
12678 idat[pi++] = 0xff;
12679 idat[pi++] = 0x00;
12680 idat[pi++] = 0x00;
12681 idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
12682 pi += maxBlockLength;
12683 pos += maxBlockLength;
12684 len -= maxBlockLength;
12685 }
12686
12687 idat[pi++] = 0x01;
12688 idat[pi++] = len & 0xff;
12689 idat[pi++] = len >> 8 & 0xff;
12690 idat[pi++] = ~len & 0xffff & 0xff;
12691 idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
12692 idat.set(literals.subarray(pos), pi);
12693 pi += literals.length - pos;
12694 const adler = adler32(literals, 0, literals.length);
12695 idat[pi++] = adler >> 24 & 0xff;
12696 idat[pi++] = adler >> 16 & 0xff;
12697 idat[pi++] = adler >> 8 & 0xff;
12698 idat[pi++] = adler & 0xff;
12699 return idat;
12700 }
12701
12702 function encode(imgData, kind, forceDataSchema, isMask) {
12703 const width = imgData.width;
12704 const height = imgData.height;
12705 let bitDepth, colorType, lineSize;
12706 const bytes = imgData.data;
12707
12708 switch (kind) {
12709 case _util.ImageKind.GRAYSCALE_1BPP:
12710 colorType = 0;
12711 bitDepth = 1;
12712 lineSize = width + 7 >> 3;
12713 break;
12714
12715 case _util.ImageKind.RGB_24BPP:
12716 colorType = 2;
12717 bitDepth = 8;
12718 lineSize = width * 3;
12719 break;
12720
12721 case _util.ImageKind.RGBA_32BPP:
12722 colorType = 6;
12723 bitDepth = 8;
12724 lineSize = width * 4;
12725 break;
12726
12727 default:
12728 throw new Error("invalid format");
12729 }
12730
12731 const literals = new Uint8Array((1 + lineSize) * height);
12732 let offsetLiterals = 0,
12733 offsetBytes = 0;
12734
12735 for (let y = 0; y < height; ++y) {
12736 literals[offsetLiterals++] = 0;
12737 literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
12738 offsetBytes += lineSize;
12739 offsetLiterals += lineSize;
12740 }
12741
12742 if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
12743 offsetLiterals = 0;
12744
12745 for (let y = 0; y < height; y++) {
12746 offsetLiterals++;
12747
12748 for (let i = 0; i < lineSize; i++) {
12749 literals[offsetLiterals++] ^= 0xff;
12750 }
12751 }
12752 }
12753
12754 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]);
12755 const idat = deflateSync(literals);
12756 const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
12757 const data = new Uint8Array(pngLength);
12758 let offset = 0;
12759 data.set(PNG_HEADER, offset);
12760 offset += PNG_HEADER.length;
12761 writePngChunk("IHDR", ihdr, data, offset);
12762 offset += CHUNK_WRAPPER_SIZE + ihdr.length;
12763 writePngChunk("IDATA", idat, data, offset);
12764 offset += CHUNK_WRAPPER_SIZE + idat.length;
12765 writePngChunk("IEND", new Uint8Array(0), data, offset);
12766 return (0, _util.createObjectURL)(data, "image/png", forceDataSchema);
12767 }
12768
12769 return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
12770 const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
12771 return encode(imgData, kind, forceDataSchema, isMask);
12772 };
12773 }();
12774
12775 class SVGExtraState {
12776 constructor() {
12777 this.fontSizeScale = 1;
12778 this.fontWeight = SVG_DEFAULTS.fontWeight;
12779 this.fontSize = 0;
12780 this.textMatrix = _util.IDENTITY_MATRIX;
12781 this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
12782 this.leading = 0;
12783 this.textRenderingMode = _util.TextRenderingMode.FILL;
12784 this.textMatrixScale = 1;
12785 this.x = 0;
12786 this.y = 0;
12787 this.lineX = 0;
12788 this.lineY = 0;
12789 this.charSpacing = 0;
12790 this.wordSpacing = 0;
12791 this.textHScale = 1;
12792 this.textRise = 0;
12793 this.fillColor = SVG_DEFAULTS.fillColor;
12794 this.strokeColor = "#000000";
12795 this.fillAlpha = 1;
12796 this.strokeAlpha = 1;
12797 this.lineWidth = 1;
12798 this.lineJoin = "";
12799 this.lineCap = "";
12800 this.miterLimit = 0;
12801 this.dashArray = [];
12802 this.dashPhase = 0;
12803 this.dependencies = [];
12804 this.activeClipUrl = null;
12805 this.clipGroup = null;
12806 this.maskId = "";
12807 }
12808
12809 clone() {
12810 return Object.create(this);
12811 }
12812
12813 setCurrentPoint(x, y) {
12814 this.x = x;
12815 this.y = y;
12816 }
12817
12818 }
12819
12820 function opListToTree(opList) {
12821 let opTree = [];
12822 const tmp = [];
12823
12824 for (const opListElement of opList) {
12825 if (opListElement.fn === "save") {
12826 opTree.push({
12827 fnId: 92,
12828 fn: "group",
12829 items: []
12830 });
12831 tmp.push(opTree);
12832 opTree = opTree[opTree.length - 1].items;
12833 continue;
12834 }
12835
12836 if (opListElement.fn === "restore") {
12837 opTree = tmp.pop();
12838 } else {
12839 opTree.push(opListElement);
12840 }
12841 }
12842
12843 return opTree;
12844 }
12845
12846 function pf(value) {
12847 if (Number.isInteger(value)) {
12848 return value.toString();
12849 }
12850
12851 const s = value.toFixed(10);
12852 let i = s.length - 1;
12853
12854 if (s[i] !== "0") {
12855 return s;
12856 }
12857
12858 do {
12859 i--;
12860 } while (s[i] === "0");
12861
12862 return s.substring(0, s[i] === "." ? i : i + 1);
12863 }
12864
12865 function pm(m) {
12866 if (m[4] === 0 && m[5] === 0) {
12867 if (m[1] === 0 && m[2] === 0) {
12868 if (m[0] === 1 && m[3] === 1) {
12869 return "";
12870 }
12871
12872 return `scale(${pf(m[0])} ${pf(m[3])})`;
12873 }
12874
12875 if (m[0] === m[3] && m[1] === -m[2]) {
12876 const a = Math.acos(m[0]) * 180 / Math.PI;
12877 return `rotate(${pf(a)})`;
12878 }
12879 } else {
12880 if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
12881 return `translate(${pf(m[4])} ${pf(m[5])})`;
12882 }
12883 }
12884
12885 return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
12886 }
12887
12888 let clipCount = 0;
12889 let maskCount = 0;
12890 let shadingCount = 0;
12891 exports.SVGGraphics = SVGGraphics = class {
12892 constructor(commonObjs, objs, forceDataSchema = false) {
12893 this.svgFactory = new _display_utils.DOMSVGFactory();
12894 this.current = new SVGExtraState();
12895 this.transformMatrix = _util.IDENTITY_MATRIX;
12896 this.transformStack = [];
12897 this.extraStack = [];
12898 this.commonObjs = commonObjs;
12899 this.objs = objs;
12900 this.pendingClip = null;
12901 this.pendingEOFill = false;
12902 this.embedFonts = false;
12903 this.embeddedFonts = Object.create(null);
12904 this.cssStyle = null;
12905 this.forceDataSchema = !!forceDataSchema;
12906 this._operatorIdMapping = [];
12907
12908 for (const op in _util.OPS) {
12909 this._operatorIdMapping[_util.OPS[op]] = op;
12910 }
12911 }
12912
12913 save() {
12914 this.transformStack.push(this.transformMatrix);
12915 const old = this.current;
12916 this.extraStack.push(old);
12917 this.current = old.clone();
12918 }
12919
12920 restore() {
12921 this.transformMatrix = this.transformStack.pop();
12922 this.current = this.extraStack.pop();
12923 this.pendingClip = null;
12924 this.tgrp = null;
12925 }
12926
12927 group(items) {
12928 this.save();
12929 this.executeOpTree(items);
12930 this.restore();
12931 }
12932
12933 loadDependencies(operatorList) {
12934 const fnArray = operatorList.fnArray;
12935 const argsArray = operatorList.argsArray;
12936
12937 for (let i = 0, ii = fnArray.length; i < ii; i++) {
12938 if (fnArray[i] !== _util.OPS.dependency) {
12939 continue;
12940 }
12941
12942 for (const obj of argsArray[i]) {
12943 const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
12944 const promise = new Promise(resolve => {
12945 objsPool.get(obj, resolve);
12946 });
12947 this.current.dependencies.push(promise);
12948 }
12949 }
12950
12951 return Promise.all(this.current.dependencies);
12952 }
12953
12954 transform(a, b, c, d, e, f) {
12955 const transformMatrix = [a, b, c, d, e, f];
12956 this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
12957 this.tgrp = null;
12958 }
12959
12960 getSVG(operatorList, viewport) {
12961 this.viewport = viewport;
12962
12963 const svgElement = this._initialize(viewport);
12964
12965 return this.loadDependencies(operatorList).then(() => {
12966 this.transformMatrix = _util.IDENTITY_MATRIX;
12967 this.executeOpTree(this.convertOpList(operatorList));
12968 return svgElement;
12969 });
12970 }
12971
12972 convertOpList(operatorList) {
12973 const operatorIdMapping = this._operatorIdMapping;
12974 const argsArray = operatorList.argsArray;
12975 const fnArray = operatorList.fnArray;
12976 const opList = [];
12977
12978 for (let i = 0, ii = fnArray.length; i < ii; i++) {
12979 const fnId = fnArray[i];
12980 opList.push({
12981 fnId,
12982 fn: operatorIdMapping[fnId],
12983 args: argsArray[i]
12984 });
12985 }
12986
12987 return opListToTree(opList);
12988 }
12989
12990 executeOpTree(opTree) {
12991 for (const opTreeElement of opTree) {
12992 const fn = opTreeElement.fn;
12993 const fnId = opTreeElement.fnId;
12994 const args = opTreeElement.args;
12995
12996 switch (fnId | 0) {
12997 case _util.OPS.beginText:
12998 this.beginText();
12999 break;
13000
13001 case _util.OPS.dependency:
13002 break;
13003
13004 case _util.OPS.setLeading:
13005 this.setLeading(args);
13006 break;
13007
13008 case _util.OPS.setLeadingMoveText:
13009 this.setLeadingMoveText(args[0], args[1]);
13010 break;
13011
13012 case _util.OPS.setFont:
13013 this.setFont(args);
13014 break;
13015
13016 case _util.OPS.showText:
13017 this.showText(args[0]);
13018 break;
13019
13020 case _util.OPS.showSpacedText:
13021 this.showText(args[0]);
13022 break;
13023
13024 case _util.OPS.endText:
13025 this.endText();
13026 break;
13027
13028 case _util.OPS.moveText:
13029 this.moveText(args[0], args[1]);
13030 break;
13031
13032 case _util.OPS.setCharSpacing:
13033 this.setCharSpacing(args[0]);
13034 break;
13035
13036 case _util.OPS.setWordSpacing:
13037 this.setWordSpacing(args[0]);
13038 break;
13039
13040 case _util.OPS.setHScale:
13041 this.setHScale(args[0]);
13042 break;
13043
13044 case _util.OPS.setTextMatrix:
13045 this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
13046 break;
13047
13048 case _util.OPS.setTextRise:
13049 this.setTextRise(args[0]);
13050 break;
13051
13052 case _util.OPS.setTextRenderingMode:
13053 this.setTextRenderingMode(args[0]);
13054 break;
13055
13056 case _util.OPS.setLineWidth:
13057 this.setLineWidth(args[0]);
13058 break;
13059
13060 case _util.OPS.setLineJoin:
13061 this.setLineJoin(args[0]);
13062 break;
13063
13064 case _util.OPS.setLineCap:
13065 this.setLineCap(args[0]);
13066 break;
13067
13068 case _util.OPS.setMiterLimit:
13069 this.setMiterLimit(args[0]);
13070 break;
13071
13072 case _util.OPS.setFillRGBColor:
13073 this.setFillRGBColor(args[0], args[1], args[2]);
13074 break;
13075
13076 case _util.OPS.setStrokeRGBColor:
13077 this.setStrokeRGBColor(args[0], args[1], args[2]);
13078 break;
13079
13080 case _util.OPS.setStrokeColorN:
13081 this.setStrokeColorN(args);
13082 break;
13083
13084 case _util.OPS.setFillColorN:
13085 this.setFillColorN(args);
13086 break;
13087
13088 case _util.OPS.shadingFill:
13089 this.shadingFill(args[0]);
13090 break;
13091
13092 case _util.OPS.setDash:
13093 this.setDash(args[0], args[1]);
13094 break;
13095
13096 case _util.OPS.setRenderingIntent:
13097 this.setRenderingIntent(args[0]);
13098 break;
13099
13100 case _util.OPS.setFlatness:
13101 this.setFlatness(args[0]);
13102 break;
13103
13104 case _util.OPS.setGState:
13105 this.setGState(args[0]);
13106 break;
13107
13108 case _util.OPS.fill:
13109 this.fill();
13110 break;
13111
13112 case _util.OPS.eoFill:
13113 this.eoFill();
13114 break;
13115
13116 case _util.OPS.stroke:
13117 this.stroke();
13118 break;
13119
13120 case _util.OPS.fillStroke:
13121 this.fillStroke();
13122 break;
13123
13124 case _util.OPS.eoFillStroke:
13125 this.eoFillStroke();
13126 break;
13127
13128 case _util.OPS.clip:
13129 this.clip("nonzero");
13130 break;
13131
13132 case _util.OPS.eoClip:
13133 this.clip("evenodd");
13134 break;
13135
13136 case _util.OPS.paintSolidColorImageMask:
13137 this.paintSolidColorImageMask();
13138 break;
13139
13140 case _util.OPS.paintImageXObject:
13141 this.paintImageXObject(args[0]);
13142 break;
13143
13144 case _util.OPS.paintInlineImageXObject:
13145 this.paintInlineImageXObject(args[0]);
13146 break;
13147
13148 case _util.OPS.paintImageMaskXObject:
13149 this.paintImageMaskXObject(args[0]);
13150 break;
13151
13152 case _util.OPS.paintFormXObjectBegin:
13153 this.paintFormXObjectBegin(args[0], args[1]);
13154 break;
13155
13156 case _util.OPS.paintFormXObjectEnd:
13157 this.paintFormXObjectEnd();
13158 break;
13159
13160 case _util.OPS.closePath:
13161 this.closePath();
13162 break;
13163
13164 case _util.OPS.closeStroke:
13165 this.closeStroke();
13166 break;
13167
13168 case _util.OPS.closeFillStroke:
13169 this.closeFillStroke();
13170 break;
13171
13172 case _util.OPS.closeEOFillStroke:
13173 this.closeEOFillStroke();
13174 break;
13175
13176 case _util.OPS.nextLine:
13177 this.nextLine();
13178 break;
13179
13180 case _util.OPS.transform:
13181 this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
13182 break;
13183
13184 case _util.OPS.constructPath:
13185 this.constructPath(args[0], args[1]);
13186 break;
13187
13188 case _util.OPS.endPath:
13189 this.endPath();
13190 break;
13191
13192 case 92:
13193 this.group(opTreeElement.items);
13194 break;
13195
13196 default:
13197 (0, _util.warn)(`Unimplemented operator ${fn}`);
13198 break;
13199 }
13200 }
13201 }
13202
13203 setWordSpacing(wordSpacing) {
13204 this.current.wordSpacing = wordSpacing;
13205 }
13206
13207 setCharSpacing(charSpacing) {
13208 this.current.charSpacing = charSpacing;
13209 }
13210
13211 nextLine() {
13212 this.moveText(0, this.current.leading);
13213 }
13214
13215 setTextMatrix(a, b, c, d, e, f) {
13216 const current = this.current;
13217 current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
13218 current.textMatrixScale = Math.hypot(a, b);
13219 current.x = current.lineX = 0;
13220 current.y = current.lineY = 0;
13221 current.xcoords = [];
13222 current.ycoords = [];
13223 current.tspan = this.svgFactory.createElement("svg:tspan");
13224 current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
13225 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
13226 current.tspan.setAttributeNS(null, "y", pf(-current.y));
13227 current.txtElement = this.svgFactory.createElement("svg:text");
13228 current.txtElement.appendChild(current.tspan);
13229 }
13230
13231 beginText() {
13232 const current = this.current;
13233 current.x = current.lineX = 0;
13234 current.y = current.lineY = 0;
13235 current.textMatrix = _util.IDENTITY_MATRIX;
13236 current.lineMatrix = _util.IDENTITY_MATRIX;
13237 current.textMatrixScale = 1;
13238 current.tspan = this.svgFactory.createElement("svg:tspan");
13239 current.txtElement = this.svgFactory.createElement("svg:text");
13240 current.txtgrp = this.svgFactory.createElement("svg:g");
13241 current.xcoords = [];
13242 current.ycoords = [];
13243 }
13244
13245 moveText(x, y) {
13246 const current = this.current;
13247 current.x = current.lineX += x;
13248 current.y = current.lineY += y;
13249 current.xcoords = [];
13250 current.ycoords = [];
13251 current.tspan = this.svgFactory.createElement("svg:tspan");
13252 current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
13253 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
13254 current.tspan.setAttributeNS(null, "y", pf(-current.y));
13255 }
13256
13257 showText(glyphs) {
13258 const current = this.current;
13259 const font = current.font;
13260 const fontSize = current.fontSize;
13261
13262 if (fontSize === 0) {
13263 return;
13264 }
13265
13266 const fontSizeScale = current.fontSizeScale;
13267 const charSpacing = current.charSpacing;
13268 const wordSpacing = current.wordSpacing;
13269 const fontDirection = current.fontDirection;
13270 const textHScale = current.textHScale * fontDirection;
13271 const vertical = font.vertical;
13272 const spacingDir = vertical ? 1 : -1;
13273 const defaultVMetrics = font.defaultVMetrics;
13274 const widthAdvanceScale = fontSize * current.fontMatrix[0];
13275 let x = 0;
13276
13277 for (const glyph of glyphs) {
13278 if (glyph === null) {
13279 x += fontDirection * wordSpacing;
13280 continue;
13281 } else if ((0, _util.isNum)(glyph)) {
13282 x += spacingDir * glyph * fontSize / 1000;
13283 continue;
13284 }
13285
13286 const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
13287 const character = glyph.fontChar;
13288 let scaledX, scaledY;
13289 let width = glyph.width;
13290
13291 if (vertical) {
13292 let vx;
13293 const vmetric = glyph.vmetric || defaultVMetrics;
13294 vx = glyph.vmetric ? vmetric[1] : width * 0.5;
13295 vx = -vx * widthAdvanceScale;
13296 const vy = vmetric[2] * widthAdvanceScale;
13297 width = vmetric ? -vmetric[0] : width;
13298 scaledX = vx / fontSizeScale;
13299 scaledY = (x + vy) / fontSizeScale;
13300 } else {
13301 scaledX = x / fontSizeScale;
13302 scaledY = 0;
13303 }
13304
13305 if (glyph.isInFont || font.missingFile) {
13306 current.xcoords.push(current.x + scaledX);
13307
13308 if (vertical) {
13309 current.ycoords.push(-current.y + scaledY);
13310 }
13311
13312 current.tspan.textContent += character;
13313 } else {}
13314
13315 let charWidth;
13316
13317 if (vertical) {
13318 charWidth = width * widthAdvanceScale - spacing * fontDirection;
13319 } else {
13320 charWidth = width * widthAdvanceScale + spacing * fontDirection;
13321 }
13322
13323 x += charWidth;
13324 }
13325
13326 current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
13327
13328 if (vertical) {
13329 current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
13330 } else {
13331 current.tspan.setAttributeNS(null, "y", pf(-current.y));
13332 }
13333
13334 if (vertical) {
13335 current.y -= x;
13336 } else {
13337 current.x += x * textHScale;
13338 }
13339
13340 current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
13341 current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
13342
13343 if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
13344 current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
13345 }
13346
13347 if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
13348 current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
13349 }
13350
13351 const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
13352
13353 if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
13354 if (current.fillColor !== SVG_DEFAULTS.fillColor) {
13355 current.tspan.setAttributeNS(null, "fill", current.fillColor);
13356 }
13357
13358 if (current.fillAlpha < 1) {
13359 current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
13360 }
13361 } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
13362 current.tspan.setAttributeNS(null, "fill", "transparent");
13363 } else {
13364 current.tspan.setAttributeNS(null, "fill", "none");
13365 }
13366
13367 if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
13368 const lineWidthScale = 1 / (current.textMatrixScale || 1);
13369
13370 this._setStrokeAttributes(current.tspan, lineWidthScale);
13371 }
13372
13373 let textMatrix = current.textMatrix;
13374
13375 if (current.textRise !== 0) {
13376 textMatrix = textMatrix.slice();
13377 textMatrix[5] += current.textRise;
13378 }
13379
13380 current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
13381 current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
13382 current.txtElement.appendChild(current.tspan);
13383 current.txtgrp.appendChild(current.txtElement);
13384
13385 this._ensureTransformGroup().appendChild(current.txtElement);
13386 }
13387
13388 setLeadingMoveText(x, y) {
13389 this.setLeading(-y);
13390 this.moveText(x, y);
13391 }
13392
13393 addFontStyle(fontObj) {
13394 if (!fontObj.data) {
13395 throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
13396 }
13397
13398 if (!this.cssStyle) {
13399 this.cssStyle = this.svgFactory.createElement("svg:style");
13400 this.cssStyle.setAttributeNS(null, "type", "text/css");
13401 this.defs.appendChild(this.cssStyle);
13402 }
13403
13404 const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
13405 this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
13406 }
13407
13408 setFont(details) {
13409 const current = this.current;
13410 const fontObj = this.commonObjs.get(details[0]);
13411 let size = details[1];
13412 current.font = fontObj;
13413
13414 if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
13415 this.addFontStyle(fontObj);
13416 this.embeddedFonts[fontObj.loadedName] = fontObj;
13417 }
13418
13419 current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
13420 let bold = "normal";
13421
13422 if (fontObj.black) {
13423 bold = "900";
13424 } else if (fontObj.bold) {
13425 bold = "bold";
13426 }
13427
13428 const italic = fontObj.italic ? "italic" : "normal";
13429
13430 if (size < 0) {
13431 size = -size;
13432 current.fontDirection = -1;
13433 } else {
13434 current.fontDirection = 1;
13435 }
13436
13437 current.fontSize = size;
13438 current.fontFamily = fontObj.loadedName;
13439 current.fontWeight = bold;
13440 current.fontStyle = italic;
13441 current.tspan = this.svgFactory.createElement("svg:tspan");
13442 current.tspan.setAttributeNS(null, "y", pf(-current.y));
13443 current.xcoords = [];
13444 current.ycoords = [];
13445 }
13446
13447 endText() {
13448 const current = this.current;
13449
13450 if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
13451 current.element = current.txtElement;
13452 this.clip("nonzero");
13453 this.endPath();
13454 }
13455 }
13456
13457 setLineWidth(width) {
13458 if (width > 0) {
13459 this.current.lineWidth = width;
13460 }
13461 }
13462
13463 setLineCap(style) {
13464 this.current.lineCap = LINE_CAP_STYLES[style];
13465 }
13466
13467 setLineJoin(style) {
13468 this.current.lineJoin = LINE_JOIN_STYLES[style];
13469 }
13470
13471 setMiterLimit(limit) {
13472 this.current.miterLimit = limit;
13473 }
13474
13475 setStrokeAlpha(strokeAlpha) {
13476 this.current.strokeAlpha = strokeAlpha;
13477 }
13478
13479 setStrokeRGBColor(r, g, b) {
13480 this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
13481 }
13482
13483 setFillAlpha(fillAlpha) {
13484 this.current.fillAlpha = fillAlpha;
13485 }
13486
13487 setFillRGBColor(r, g, b) {
13488 this.current.fillColor = _util.Util.makeHexColor(r, g, b);
13489 this.current.tspan = this.svgFactory.createElement("svg:tspan");
13490 this.current.xcoords = [];
13491 this.current.ycoords = [];
13492 }
13493
13494 setStrokeColorN(args) {
13495 this.current.strokeColor = this._makeColorN_Pattern(args);
13496 }
13497
13498 setFillColorN(args) {
13499 this.current.fillColor = this._makeColorN_Pattern(args);
13500 }
13501
13502 shadingFill(args) {
13503 const width = this.viewport.width;
13504 const height = this.viewport.height;
13505
13506 const inv = _util.Util.inverseTransform(this.transformMatrix);
13507
13508 const bl = _util.Util.applyTransform([0, 0], inv);
13509
13510 const br = _util.Util.applyTransform([0, height], inv);
13511
13512 const ul = _util.Util.applyTransform([width, 0], inv);
13513
13514 const ur = _util.Util.applyTransform([width, height], inv);
13515
13516 const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
13517 const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
13518 const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
13519 const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
13520 const rect = this.svgFactory.createElement("svg:rect");
13521 rect.setAttributeNS(null, "x", x0);
13522 rect.setAttributeNS(null, "y", y0);
13523 rect.setAttributeNS(null, "width", x1 - x0);
13524 rect.setAttributeNS(null, "height", y1 - y0);
13525 rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
13526
13527 if (this.current.fillAlpha < 1) {
13528 rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
13529 }
13530
13531 this._ensureTransformGroup().appendChild(rect);
13532 }
13533
13534 _makeColorN_Pattern(args) {
13535 if (args[0] === "TilingPattern") {
13536 return this._makeTilingPattern(args);
13537 }
13538
13539 return this._makeShadingPattern(args);
13540 }
13541
13542 _makeTilingPattern(args) {
13543 const color = args[1];
13544 const operatorList = args[2];
13545 const matrix = args[3] || _util.IDENTITY_MATRIX;
13546 const [x0, y0, x1, y1] = args[4];
13547 const xstep = args[5];
13548 const ystep = args[6];
13549 const paintType = args[7];
13550 const tilingId = `shading${shadingCount++}`;
13551
13552 const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
13553
13554 const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
13555
13556 const txstep = xstep * xscale;
13557 const tystep = ystep * yscale;
13558 const tiling = this.svgFactory.createElement("svg:pattern");
13559 tiling.setAttributeNS(null, "id", tilingId);
13560 tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
13561 tiling.setAttributeNS(null, "width", txstep);
13562 tiling.setAttributeNS(null, "height", tystep);
13563 tiling.setAttributeNS(null, "x", `${tx0}`);
13564 tiling.setAttributeNS(null, "y", `${ty0}`);
13565 const svg = this.svg;
13566 const transformMatrix = this.transformMatrix;
13567 const fillColor = this.current.fillColor;
13568 const strokeColor = this.current.strokeColor;
13569 const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
13570 this.svg = bbox;
13571 this.transformMatrix = matrix;
13572
13573 if (paintType === 2) {
13574 const cssColor = _util.Util.makeHexColor(...color);
13575
13576 this.current.fillColor = cssColor;
13577 this.current.strokeColor = cssColor;
13578 }
13579
13580 this.executeOpTree(this.convertOpList(operatorList));
13581 this.svg = svg;
13582 this.transformMatrix = transformMatrix;
13583 this.current.fillColor = fillColor;
13584 this.current.strokeColor = strokeColor;
13585 tiling.appendChild(bbox.childNodes[0]);
13586 this.defs.appendChild(tiling);
13587 return `url(#${tilingId})`;
13588 }
13589
13590 _makeShadingPattern(args) {
13591 if (typeof args === "string") {
13592 args = this.objs.get(args);
13593 }
13594
13595 switch (args[0]) {
13596 case "RadialAxial":
13597 const shadingId = `shading${shadingCount++}`;
13598 const colorStops = args[3];
13599 let gradient;
13600
13601 switch (args[1]) {
13602 case "axial":
13603 const point0 = args[4];
13604 const point1 = args[5];
13605 gradient = this.svgFactory.createElement("svg:linearGradient");
13606 gradient.setAttributeNS(null, "id", shadingId);
13607 gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
13608 gradient.setAttributeNS(null, "x1", point0[0]);
13609 gradient.setAttributeNS(null, "y1", point0[1]);
13610 gradient.setAttributeNS(null, "x2", point1[0]);
13611 gradient.setAttributeNS(null, "y2", point1[1]);
13612 break;
13613
13614 case "radial":
13615 const focalPoint = args[4];
13616 const circlePoint = args[5];
13617 const focalRadius = args[6];
13618 const circleRadius = args[7];
13619 gradient = this.svgFactory.createElement("svg:radialGradient");
13620 gradient.setAttributeNS(null, "id", shadingId);
13621 gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
13622 gradient.setAttributeNS(null, "cx", circlePoint[0]);
13623 gradient.setAttributeNS(null, "cy", circlePoint[1]);
13624 gradient.setAttributeNS(null, "r", circleRadius);
13625 gradient.setAttributeNS(null, "fx", focalPoint[0]);
13626 gradient.setAttributeNS(null, "fy", focalPoint[1]);
13627 gradient.setAttributeNS(null, "fr", focalRadius);
13628 break;
13629
13630 default:
13631 throw new Error(`Unknown RadialAxial type: ${args[1]}`);
13632 }
13633
13634 for (const colorStop of colorStops) {
13635 const stop = this.svgFactory.createElement("svg:stop");
13636 stop.setAttributeNS(null, "offset", colorStop[0]);
13637 stop.setAttributeNS(null, "stop-color", colorStop[1]);
13638 gradient.appendChild(stop);
13639 }
13640
13641 this.defs.appendChild(gradient);
13642 return `url(#${shadingId})`;
13643
13644 case "Mesh":
13645 (0, _util.warn)("Unimplemented pattern Mesh");
13646 return null;
13647
13648 case "Dummy":
13649 return "hotpink";
13650
13651 default:
13652 throw new Error(`Unknown IR type: ${args[0]}`);
13653 }
13654 }
13655
13656 setDash(dashArray, dashPhase) {
13657 this.current.dashArray = dashArray;
13658 this.current.dashPhase = dashPhase;
13659 }
13660
13661 constructPath(ops, args) {
13662 const current = this.current;
13663 let x = current.x,
13664 y = current.y;
13665 let d = [];
13666 let j = 0;
13667
13668 for (const op of ops) {
13669 switch (op | 0) {
13670 case _util.OPS.rectangle:
13671 x = args[j++];
13672 y = args[j++];
13673 const width = args[j++];
13674 const height = args[j++];
13675 const xw = x + width;
13676 const yh = y + height;
13677 d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
13678 break;
13679
13680 case _util.OPS.moveTo:
13681 x = args[j++];
13682 y = args[j++];
13683 d.push("M", pf(x), pf(y));
13684 break;
13685
13686 case _util.OPS.lineTo:
13687 x = args[j++];
13688 y = args[j++];
13689 d.push("L", pf(x), pf(y));
13690 break;
13691
13692 case _util.OPS.curveTo:
13693 x = args[j + 4];
13694 y = args[j + 5];
13695 d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
13696 j += 6;
13697 break;
13698
13699 case _util.OPS.curveTo2:
13700 d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
13701 x = args[j + 2];
13702 y = args[j + 3];
13703 j += 4;
13704 break;
13705
13706 case _util.OPS.curveTo3:
13707 x = args[j + 2];
13708 y = args[j + 3];
13709 d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
13710 j += 4;
13711 break;
13712
13713 case _util.OPS.closePath:
13714 d.push("Z");
13715 break;
13716 }
13717 }
13718
13719 d = d.join(" ");
13720
13721 if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
13722 d = current.path.getAttributeNS(null, "d") + d;
13723 } else {
13724 current.path = this.svgFactory.createElement("svg:path");
13725
13726 this._ensureTransformGroup().appendChild(current.path);
13727 }
13728
13729 current.path.setAttributeNS(null, "d", d);
13730 current.path.setAttributeNS(null, "fill", "none");
13731 current.element = current.path;
13732 current.setCurrentPoint(x, y);
13733 }
13734
13735 endPath() {
13736 const current = this.current;
13737 current.path = null;
13738
13739 if (!this.pendingClip) {
13740 return;
13741 }
13742
13743 if (!current.element) {
13744 this.pendingClip = null;
13745 return;
13746 }
13747
13748 const clipId = `clippath${clipCount++}`;
13749 const clipPath = this.svgFactory.createElement("svg:clipPath");
13750 clipPath.setAttributeNS(null, "id", clipId);
13751 clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
13752 const clipElement = current.element.cloneNode(true);
13753
13754 if (this.pendingClip === "evenodd") {
13755 clipElement.setAttributeNS(null, "clip-rule", "evenodd");
13756 } else {
13757 clipElement.setAttributeNS(null, "clip-rule", "nonzero");
13758 }
13759
13760 this.pendingClip = null;
13761 clipPath.appendChild(clipElement);
13762 this.defs.appendChild(clipPath);
13763
13764 if (current.activeClipUrl) {
13765 current.clipGroup = null;
13766
13767 for (const prev of this.extraStack) {
13768 prev.clipGroup = null;
13769 }
13770
13771 clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
13772 }
13773
13774 current.activeClipUrl = `url(#${clipId})`;
13775 this.tgrp = null;
13776 }
13777
13778 clip(type) {
13779 this.pendingClip = type;
13780 }
13781
13782 closePath() {
13783 const current = this.current;
13784
13785 if (current.path) {
13786 const d = `${current.path.getAttributeNS(null, "d")}Z`;
13787 current.path.setAttributeNS(null, "d", d);
13788 }
13789 }
13790
13791 setLeading(leading) {
13792 this.current.leading = -leading;
13793 }
13794
13795 setTextRise(textRise) {
13796 this.current.textRise = textRise;
13797 }
13798
13799 setTextRenderingMode(textRenderingMode) {
13800 this.current.textRenderingMode = textRenderingMode;
13801 }
13802
13803 setHScale(scale) {
13804 this.current.textHScale = scale / 100;
13805 }
13806
13807 setRenderingIntent(intent) {}
13808
13809 setFlatness(flatness) {}
13810
13811 setGState(states) {
13812 for (const [key, value] of states) {
13813 switch (key) {
13814 case "LW":
13815 this.setLineWidth(value);
13816 break;
13817
13818 case "LC":
13819 this.setLineCap(value);
13820 break;
13821
13822 case "LJ":
13823 this.setLineJoin(value);
13824 break;
13825
13826 case "ML":
13827 this.setMiterLimit(value);
13828 break;
13829
13830 case "D":
13831 this.setDash(value[0], value[1]);
13832 break;
13833
13834 case "RI":
13835 this.setRenderingIntent(value);
13836 break;
13837
13838 case "FL":
13839 this.setFlatness(value);
13840 break;
13841
13842 case "Font":
13843 this.setFont(value);
13844 break;
13845
13846 case "CA":
13847 this.setStrokeAlpha(value);
13848 break;
13849
13850 case "ca":
13851 this.setFillAlpha(value);
13852 break;
13853
13854 default:
13855 (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
13856 break;
13857 }
13858 }
13859 }
13860
13861 fill() {
13862 const current = this.current;
13863
13864 if (current.element) {
13865 current.element.setAttributeNS(null, "fill", current.fillColor);
13866 current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
13867 this.endPath();
13868 }
13869 }
13870
13871 stroke() {
13872 const current = this.current;
13873
13874 if (current.element) {
13875 this._setStrokeAttributes(current.element);
13876
13877 current.element.setAttributeNS(null, "fill", "none");
13878 this.endPath();
13879 }
13880 }
13881
13882 _setStrokeAttributes(element, lineWidthScale = 1) {
13883 const current = this.current;
13884 let dashArray = current.dashArray;
13885
13886 if (lineWidthScale !== 1 && dashArray.length > 0) {
13887 dashArray = dashArray.map(function (value) {
13888 return lineWidthScale * value;
13889 });
13890 }
13891
13892 element.setAttributeNS(null, "stroke", current.strokeColor);
13893 element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
13894 element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
13895 element.setAttributeNS(null, "stroke-linecap", current.lineCap);
13896 element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
13897 element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
13898 element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
13899 element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
13900 }
13901
13902 eoFill() {
13903 if (this.current.element) {
13904 this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
13905 }
13906
13907 this.fill();
13908 }
13909
13910 fillStroke() {
13911 this.stroke();
13912 this.fill();
13913 }
13914
13915 eoFillStroke() {
13916 if (this.current.element) {
13917 this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
13918 }
13919
13920 this.fillStroke();
13921 }
13922
13923 closeStroke() {
13924 this.closePath();
13925 this.stroke();
13926 }
13927
13928 closeFillStroke() {
13929 this.closePath();
13930 this.fillStroke();
13931 }
13932
13933 closeEOFillStroke() {
13934 this.closePath();
13935 this.eoFillStroke();
13936 }
13937
13938 paintSolidColorImageMask() {
13939 const rect = this.svgFactory.createElement("svg:rect");
13940 rect.setAttributeNS(null, "x", "0");
13941 rect.setAttributeNS(null, "y", "0");
13942 rect.setAttributeNS(null, "width", "1px");
13943 rect.setAttributeNS(null, "height", "1px");
13944 rect.setAttributeNS(null, "fill", this.current.fillColor);
13945
13946 this._ensureTransformGroup().appendChild(rect);
13947 }
13948
13949 paintImageXObject(objId) {
13950 const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
13951
13952 if (!imgData) {
13953 (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
13954 return;
13955 }
13956
13957 this.paintInlineImageXObject(imgData);
13958 }
13959
13960 paintInlineImageXObject(imgData, mask) {
13961 const width = imgData.width;
13962 const height = imgData.height;
13963 const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
13964 const cliprect = this.svgFactory.createElement("svg:rect");
13965 cliprect.setAttributeNS(null, "x", "0");
13966 cliprect.setAttributeNS(null, "y", "0");
13967 cliprect.setAttributeNS(null, "width", pf(width));
13968 cliprect.setAttributeNS(null, "height", pf(height));
13969 this.current.element = cliprect;
13970 this.clip("nonzero");
13971 const imgEl = this.svgFactory.createElement("svg:image");
13972 imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
13973 imgEl.setAttributeNS(null, "x", "0");
13974 imgEl.setAttributeNS(null, "y", pf(-height));
13975 imgEl.setAttributeNS(null, "width", pf(width) + "px");
13976 imgEl.setAttributeNS(null, "height", pf(height) + "px");
13977 imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
13978
13979 if (mask) {
13980 mask.appendChild(imgEl);
13981 } else {
13982 this._ensureTransformGroup().appendChild(imgEl);
13983 }
13984 }
13985
13986 paintImageMaskXObject(imgData) {
13987 const current = this.current;
13988 const width = imgData.width;
13989 const height = imgData.height;
13990 const fillColor = current.fillColor;
13991 current.maskId = `mask${maskCount++}`;
13992 const mask = this.svgFactory.createElement("svg:mask");
13993 mask.setAttributeNS(null, "id", current.maskId);
13994 const rect = this.svgFactory.createElement("svg:rect");
13995 rect.setAttributeNS(null, "x", "0");
13996 rect.setAttributeNS(null, "y", "0");
13997 rect.setAttributeNS(null, "width", pf(width));
13998 rect.setAttributeNS(null, "height", pf(height));
13999 rect.setAttributeNS(null, "fill", fillColor);
14000 rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
14001 this.defs.appendChild(mask);
14002
14003 this._ensureTransformGroup().appendChild(rect);
14004
14005 this.paintInlineImageXObject(imgData, mask);
14006 }
14007
14008 paintFormXObjectBegin(matrix, bbox) {
14009 if (Array.isArray(matrix) && matrix.length === 6) {
14010 this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
14011 }
14012
14013 if (bbox) {
14014 const width = bbox[2] - bbox[0];
14015 const height = bbox[3] - bbox[1];
14016 const cliprect = this.svgFactory.createElement("svg:rect");
14017 cliprect.setAttributeNS(null, "x", bbox[0]);
14018 cliprect.setAttributeNS(null, "y", bbox[1]);
14019 cliprect.setAttributeNS(null, "width", pf(width));
14020 cliprect.setAttributeNS(null, "height", pf(height));
14021 this.current.element = cliprect;
14022 this.clip("nonzero");
14023 this.endPath();
14024 }
14025 }
14026
14027 paintFormXObjectEnd() {}
14028
14029 _initialize(viewport) {
14030 const svg = this.svgFactory.create(viewport.width, viewport.height);
14031 const definitions = this.svgFactory.createElement("svg:defs");
14032 svg.appendChild(definitions);
14033 this.defs = definitions;
14034 const rootGroup = this.svgFactory.createElement("svg:g");
14035 rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
14036 svg.appendChild(rootGroup);
14037 this.svg = rootGroup;
14038 return svg;
14039 }
14040
14041 _ensureClipGroup() {
14042 if (!this.current.clipGroup) {
14043 const clipGroup = this.svgFactory.createElement("svg:g");
14044 clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
14045 this.svg.appendChild(clipGroup);
14046 this.current.clipGroup = clipGroup;
14047 }
14048
14049 return this.current.clipGroup;
14050 }
14051
14052 _ensureTransformGroup() {
14053 if (!this.tgrp) {
14054 this.tgrp = this.svgFactory.createElement("svg:g");
14055 this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
14056
14057 if (this.current.activeClipUrl) {
14058 this._ensureClipGroup().appendChild(this.tgrp);
14059 } else {
14060 this.svg.appendChild(this.tgrp);
14061 }
14062 }
14063
14064 return this.tgrp;
14065 }
14066
14067 };
14068}
14069
14070/***/ }),
14071/* 23 */
14072/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14073
14074
14075
14076Object.defineProperty(exports, "__esModule", ({
14077 value: true
14078}));
14079exports.PDFNodeStream = void 0;
14080
14081var _util = __w_pdfjs_require__(2);
14082
14083var _network_utils = __w_pdfjs_require__(24);
14084
14085;
14086
14087const fs = require("fs");
14088
14089const http = require("http");
14090
14091const https = require("https");
14092
14093const url = require("url");
14094
14095const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
14096
14097function parseUrl(sourceUrl) {
14098 const parsedUrl = url.parse(sourceUrl);
14099
14100 if (parsedUrl.protocol === "file:" || parsedUrl.host) {
14101 return parsedUrl;
14102 }
14103
14104 if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
14105 return url.parse(`file:///${sourceUrl}`);
14106 }
14107
14108 if (!parsedUrl.host) {
14109 parsedUrl.protocol = "file:";
14110 }
14111
14112 return parsedUrl;
14113}
14114
14115class PDFNodeStream {
14116 constructor(source) {
14117 this.source = source;
14118 this.url = parseUrl(source.url);
14119 this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
14120 this.isFsUrl = this.url.protocol === "file:";
14121 this.httpHeaders = this.isHttp && source.httpHeaders || {};
14122 this._fullRequestReader = null;
14123 this._rangeRequestReaders = [];
14124 }
14125
14126 get _progressiveDataLength() {
14127 return this._fullRequestReader?._loaded ?? 0;
14128 }
14129
14130 getFullReader() {
14131 (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
14132 this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
14133 return this._fullRequestReader;
14134 }
14135
14136 getRangeReader(start, end) {
14137 if (end <= this._progressiveDataLength) {
14138 return null;
14139 }
14140
14141 const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
14142
14143 this._rangeRequestReaders.push(rangeReader);
14144
14145 return rangeReader;
14146 }
14147
14148 cancelAllRequests(reason) {
14149 if (this._fullRequestReader) {
14150 this._fullRequestReader.cancel(reason);
14151 }
14152
14153 for (const reader of this._rangeRequestReaders.slice(0)) {
14154 reader.cancel(reason);
14155 }
14156 }
14157
14158}
14159
14160exports.PDFNodeStream = PDFNodeStream;
14161
14162class BaseFullReader {
14163 constructor(stream) {
14164 this._url = stream.url;
14165 this._done = false;
14166 this._storedError = null;
14167 this.onProgress = null;
14168 const source = stream.source;
14169 this._contentLength = source.length;
14170 this._loaded = 0;
14171 this._filename = null;
14172 this._disableRange = source.disableRange || false;
14173 this._rangeChunkSize = source.rangeChunkSize;
14174
14175 if (!this._rangeChunkSize && !this._disableRange) {
14176 this._disableRange = true;
14177 }
14178
14179 this._isStreamingSupported = !source.disableStream;
14180 this._isRangeSupported = !source.disableRange;
14181 this._readableStream = null;
14182 this._readCapability = (0, _util.createPromiseCapability)();
14183 this._headersCapability = (0, _util.createPromiseCapability)();
14184 }
14185
14186 get headersReady() {
14187 return this._headersCapability.promise;
14188 }
14189
14190 get filename() {
14191 return this._filename;
14192 }
14193
14194 get contentLength() {
14195 return this._contentLength;
14196 }
14197
14198 get isRangeSupported() {
14199 return this._isRangeSupported;
14200 }
14201
14202 get isStreamingSupported() {
14203 return this._isStreamingSupported;
14204 }
14205
14206 async read() {
14207 await this._readCapability.promise;
14208
14209 if (this._done) {
14210 return {
14211 value: undefined,
14212 done: true
14213 };
14214 }
14215
14216 if (this._storedError) {
14217 throw this._storedError;
14218 }
14219
14220 const chunk = this._readableStream.read();
14221
14222 if (chunk === null) {
14223 this._readCapability = (0, _util.createPromiseCapability)();
14224 return this.read();
14225 }
14226
14227 this._loaded += chunk.length;
14228
14229 if (this.onProgress) {
14230 this.onProgress({
14231 loaded: this._loaded,
14232 total: this._contentLength
14233 });
14234 }
14235
14236 const buffer = new Uint8Array(chunk).buffer;
14237 return {
14238 value: buffer,
14239 done: false
14240 };
14241 }
14242
14243 cancel(reason) {
14244 if (!this._readableStream) {
14245 this._error(reason);
14246
14247 return;
14248 }
14249
14250 this._readableStream.destroy(reason);
14251 }
14252
14253 _error(reason) {
14254 this._storedError = reason;
14255
14256 this._readCapability.resolve();
14257 }
14258
14259 _setReadableStream(readableStream) {
14260 this._readableStream = readableStream;
14261 readableStream.on("readable", () => {
14262 this._readCapability.resolve();
14263 });
14264 readableStream.on("end", () => {
14265 readableStream.destroy();
14266 this._done = true;
14267
14268 this._readCapability.resolve();
14269 });
14270 readableStream.on("error", reason => {
14271 this._error(reason);
14272 });
14273
14274 if (!this._isStreamingSupported && this._isRangeSupported) {
14275 this._error(new _util.AbortException("streaming is disabled"));
14276 }
14277
14278 if (this._storedError) {
14279 this._readableStream.destroy(this._storedError);
14280 }
14281 }
14282
14283}
14284
14285class BaseRangeReader {
14286 constructor(stream) {
14287 this._url = stream.url;
14288 this._done = false;
14289 this._storedError = null;
14290 this.onProgress = null;
14291 this._loaded = 0;
14292 this._readableStream = null;
14293 this._readCapability = (0, _util.createPromiseCapability)();
14294 const source = stream.source;
14295 this._isStreamingSupported = !source.disableStream;
14296 }
14297
14298 get isStreamingSupported() {
14299 return this._isStreamingSupported;
14300 }
14301
14302 async read() {
14303 await this._readCapability.promise;
14304
14305 if (this._done) {
14306 return {
14307 value: undefined,
14308 done: true
14309 };
14310 }
14311
14312 if (this._storedError) {
14313 throw this._storedError;
14314 }
14315
14316 const chunk = this._readableStream.read();
14317
14318 if (chunk === null) {
14319 this._readCapability = (0, _util.createPromiseCapability)();
14320 return this.read();
14321 }
14322
14323 this._loaded += chunk.length;
14324
14325 if (this.onProgress) {
14326 this.onProgress({
14327 loaded: this._loaded
14328 });
14329 }
14330
14331 const buffer = new Uint8Array(chunk).buffer;
14332 return {
14333 value: buffer,
14334 done: false
14335 };
14336 }
14337
14338 cancel(reason) {
14339 if (!this._readableStream) {
14340 this._error(reason);
14341
14342 return;
14343 }
14344
14345 this._readableStream.destroy(reason);
14346 }
14347
14348 _error(reason) {
14349 this._storedError = reason;
14350
14351 this._readCapability.resolve();
14352 }
14353
14354 _setReadableStream(readableStream) {
14355 this._readableStream = readableStream;
14356 readableStream.on("readable", () => {
14357 this._readCapability.resolve();
14358 });
14359 readableStream.on("end", () => {
14360 readableStream.destroy();
14361 this._done = true;
14362
14363 this._readCapability.resolve();
14364 });
14365 readableStream.on("error", reason => {
14366 this._error(reason);
14367 });
14368
14369 if (this._storedError) {
14370 this._readableStream.destroy(this._storedError);
14371 }
14372 }
14373
14374}
14375
14376function createRequestOptions(parsedUrl, headers) {
14377 return {
14378 protocol: parsedUrl.protocol,
14379 auth: parsedUrl.auth,
14380 host: parsedUrl.hostname,
14381 port: parsedUrl.port,
14382 path: parsedUrl.path,
14383 method: "GET",
14384 headers
14385 };
14386}
14387
14388class PDFNodeStreamFullReader extends BaseFullReader {
14389 constructor(stream) {
14390 super(stream);
14391
14392 const handleResponse = response => {
14393 if (response.statusCode === 404) {
14394 const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
14395 this._storedError = error;
14396
14397 this._headersCapability.reject(error);
14398
14399 return;
14400 }
14401
14402 this._headersCapability.resolve();
14403
14404 this._setReadableStream(response);
14405
14406 const getResponseHeader = name => {
14407 return this._readableStream.headers[name.toLowerCase()];
14408 };
14409
14410 const {
14411 allowRangeRequests,
14412 suggestedLength
14413 } = (0, _network_utils.validateRangeRequestCapabilities)({
14414 getResponseHeader,
14415 isHttp: stream.isHttp,
14416 rangeChunkSize: this._rangeChunkSize,
14417 disableRange: this._disableRange
14418 });
14419 this._isRangeSupported = allowRangeRequests;
14420 this._contentLength = suggestedLength || this._contentLength;
14421 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
14422 };
14423
14424 this._request = null;
14425
14426 if (this._url.protocol === "http:") {
14427 this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
14428 } else {
14429 this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
14430 }
14431
14432 this._request.on("error", reason => {
14433 this._storedError = reason;
14434
14435 this._headersCapability.reject(reason);
14436 });
14437
14438 this._request.end();
14439 }
14440
14441}
14442
14443class PDFNodeStreamRangeReader extends BaseRangeReader {
14444 constructor(stream, start, end) {
14445 super(stream);
14446 this._httpHeaders = {};
14447
14448 for (const property in stream.httpHeaders) {
14449 const value = stream.httpHeaders[property];
14450
14451 if (typeof value === "undefined") {
14452 continue;
14453 }
14454
14455 this._httpHeaders[property] = value;
14456 }
14457
14458 this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
14459
14460 const handleResponse = response => {
14461 if (response.statusCode === 404) {
14462 const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
14463 this._storedError = error;
14464 return;
14465 }
14466
14467 this._setReadableStream(response);
14468 };
14469
14470 this._request = null;
14471
14472 if (this._url.protocol === "http:") {
14473 this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
14474 } else {
14475 this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
14476 }
14477
14478 this._request.on("error", reason => {
14479 this._storedError = reason;
14480 });
14481
14482 this._request.end();
14483 }
14484
14485}
14486
14487class PDFNodeStreamFsFullReader extends BaseFullReader {
14488 constructor(stream) {
14489 super(stream);
14490 let path = decodeURIComponent(this._url.path);
14491
14492 if (fileUriRegex.test(this._url.href)) {
14493 path = path.replace(/^\//, "");
14494 }
14495
14496 fs.lstat(path, (error, stat) => {
14497 if (error) {
14498 if (error.code === "ENOENT") {
14499 error = new _util.MissingPDFException(`Missing PDF "${path}".`);
14500 }
14501
14502 this._storedError = error;
14503
14504 this._headersCapability.reject(error);
14505
14506 return;
14507 }
14508
14509 this._contentLength = stat.size;
14510
14511 this._setReadableStream(fs.createReadStream(path));
14512
14513 this._headersCapability.resolve();
14514 });
14515 }
14516
14517}
14518
14519class PDFNodeStreamFsRangeReader extends BaseRangeReader {
14520 constructor(stream, start, end) {
14521 super(stream);
14522 let path = decodeURIComponent(this._url.path);
14523
14524 if (fileUriRegex.test(this._url.href)) {
14525 path = path.replace(/^\//, "");
14526 }
14527
14528 this._setReadableStream(fs.createReadStream(path, {
14529 start,
14530 end: end - 1
14531 }));
14532 }
14533
14534}
14535
14536/***/ }),
14537/* 24 */
14538/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14539
14540
14541
14542Object.defineProperty(exports, "__esModule", ({
14543 value: true
14544}));
14545exports.createResponseStatusError = createResponseStatusError;
14546exports.extractFilenameFromHeader = extractFilenameFromHeader;
14547exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
14548exports.validateResponseStatus = validateResponseStatus;
14549
14550var _util = __w_pdfjs_require__(2);
14551
14552var _content_disposition = __w_pdfjs_require__(25);
14553
14554var _display_utils = __w_pdfjs_require__(1);
14555
14556function validateRangeRequestCapabilities({
14557 getResponseHeader,
14558 isHttp,
14559 rangeChunkSize,
14560 disableRange
14561}) {
14562 (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
14563 const returnValues = {
14564 allowRangeRequests: false,
14565 suggestedLength: undefined
14566 };
14567 const length = parseInt(getResponseHeader("Content-Length"), 10);
14568
14569 if (!Number.isInteger(length)) {
14570 return returnValues;
14571 }
14572
14573 returnValues.suggestedLength = length;
14574
14575 if (length <= 2 * rangeChunkSize) {
14576 return returnValues;
14577 }
14578
14579 if (disableRange || !isHttp) {
14580 return returnValues;
14581 }
14582
14583 if (getResponseHeader("Accept-Ranges") !== "bytes") {
14584 return returnValues;
14585 }
14586
14587 const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
14588
14589 if (contentEncoding !== "identity") {
14590 return returnValues;
14591 }
14592
14593 returnValues.allowRangeRequests = true;
14594 return returnValues;
14595}
14596
14597function extractFilenameFromHeader(getResponseHeader) {
14598 const contentDisposition = getResponseHeader("Content-Disposition");
14599
14600 if (contentDisposition) {
14601 let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
14602
14603 if (filename.includes("%")) {
14604 try {
14605 filename = decodeURIComponent(filename);
14606 } catch (ex) {}
14607 }
14608
14609 if ((0, _display_utils.isPdfFile)(filename)) {
14610 return filename;
14611 }
14612 }
14613
14614 return null;
14615}
14616
14617function createResponseStatusError(status, url) {
14618 if (status === 404 || status === 0 && url.startsWith("file:")) {
14619 return new _util.MissingPDFException('Missing PDF "' + url + '".');
14620 }
14621
14622 return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
14623}
14624
14625function validateResponseStatus(status) {
14626 return status === 200 || status === 206;
14627}
14628
14629/***/ }),
14630/* 25 */
14631/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14632
14633
14634
14635Object.defineProperty(exports, "__esModule", ({
14636 value: true
14637}));
14638exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
14639
14640var _util = __w_pdfjs_require__(2);
14641
14642function getFilenameFromContentDispositionHeader(contentDisposition) {
14643 let needsEncodingFixup = true;
14644 let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
14645
14646 if (tmp) {
14647 tmp = tmp[1];
14648 let filename = rfc2616unquote(tmp);
14649 filename = unescape(filename);
14650 filename = rfc5987decode(filename);
14651 filename = rfc2047decode(filename);
14652 return fixupEncoding(filename);
14653 }
14654
14655 tmp = rfc2231getparam(contentDisposition);
14656
14657 if (tmp) {
14658 const filename = rfc2047decode(tmp);
14659 return fixupEncoding(filename);
14660 }
14661
14662 tmp = toParamRegExp("filename", "i").exec(contentDisposition);
14663
14664 if (tmp) {
14665 tmp = tmp[1];
14666 let filename = rfc2616unquote(tmp);
14667 filename = rfc2047decode(filename);
14668 return fixupEncoding(filename);
14669 }
14670
14671 function toParamRegExp(attributePattern, flags) {
14672 return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
14673 }
14674
14675 function textdecode(encoding, value) {
14676 if (encoding) {
14677 if (!/^[\x00-\xFF]+$/.test(value)) {
14678 return value;
14679 }
14680
14681 try {
14682 const decoder = new TextDecoder(encoding, {
14683 fatal: true
14684 });
14685 const buffer = (0, _util.stringToBytes)(value);
14686 value = decoder.decode(buffer);
14687 needsEncodingFixup = false;
14688 } catch (e) {
14689 if (/^utf-?8$/i.test(encoding)) {
14690 try {
14691 value = decodeURIComponent(escape(value));
14692 needsEncodingFixup = false;
14693 } catch (err) {}
14694 }
14695 }
14696 }
14697
14698 return value;
14699 }
14700
14701 function fixupEncoding(value) {
14702 if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
14703 value = textdecode("utf-8", value);
14704
14705 if (needsEncodingFixup) {
14706 value = textdecode("iso-8859-1", value);
14707 }
14708 }
14709
14710 return value;
14711 }
14712
14713 function rfc2231getparam(contentDispositionStr) {
14714 const matches = [];
14715 let match;
14716 const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
14717
14718 while ((match = iter.exec(contentDispositionStr)) !== null) {
14719 let [, n, quot, part] = match;
14720 n = parseInt(n, 10);
14721
14722 if (n in matches) {
14723 if (n === 0) {
14724 break;
14725 }
14726
14727 continue;
14728 }
14729
14730 matches[n] = [quot, part];
14731 }
14732
14733 const parts = [];
14734
14735 for (let n = 0; n < matches.length; ++n) {
14736 if (!(n in matches)) {
14737 break;
14738 }
14739
14740 let [quot, part] = matches[n];
14741 part = rfc2616unquote(part);
14742
14743 if (quot) {
14744 part = unescape(part);
14745
14746 if (n === 0) {
14747 part = rfc5987decode(part);
14748 }
14749 }
14750
14751 parts.push(part);
14752 }
14753
14754 return parts.join("");
14755 }
14756
14757 function rfc2616unquote(value) {
14758 if (value.startsWith('"')) {
14759 const parts = value.slice(1).split('\\"');
14760
14761 for (let i = 0; i < parts.length; ++i) {
14762 const quotindex = parts[i].indexOf('"');
14763
14764 if (quotindex !== -1) {
14765 parts[i] = parts[i].slice(0, quotindex);
14766 parts.length = i + 1;
14767 }
14768
14769 parts[i] = parts[i].replace(/\\(.)/g, "$1");
14770 }
14771
14772 value = parts.join('"');
14773 }
14774
14775 return value;
14776 }
14777
14778 function rfc5987decode(extvalue) {
14779 const encodingend = extvalue.indexOf("'");
14780
14781 if (encodingend === -1) {
14782 return extvalue;
14783 }
14784
14785 const encoding = extvalue.slice(0, encodingend);
14786 const langvalue = extvalue.slice(encodingend + 1);
14787 const value = langvalue.replace(/^[^']*'/, "");
14788 return textdecode(encoding, value);
14789 }
14790
14791 function rfc2047decode(value) {
14792 if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
14793 return value;
14794 }
14795
14796 return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
14797 if (encoding === "q" || encoding === "Q") {
14798 text = text.replace(/_/g, " ");
14799 text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
14800 return String.fromCharCode(parseInt(hex, 16));
14801 });
14802 return textdecode(charset, text);
14803 }
14804
14805 try {
14806 text = atob(text);
14807 } catch (e) {}
14808
14809 return textdecode(charset, text);
14810 });
14811 }
14812
14813 return "";
14814}
14815
14816/***/ }),
14817/* 26 */
14818/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14819
14820
14821
14822Object.defineProperty(exports, "__esModule", ({
14823 value: true
14824}));
14825exports.PDFNetworkStream = void 0;
14826
14827var _util = __w_pdfjs_require__(2);
14828
14829var _network_utils = __w_pdfjs_require__(24);
14830
14831;
14832const OK_RESPONSE = 200;
14833const PARTIAL_CONTENT_RESPONSE = 206;
14834
14835function getArrayBuffer(xhr) {
14836 const data = xhr.response;
14837
14838 if (typeof data !== "string") {
14839 return data;
14840 }
14841
14842 const array = (0, _util.stringToBytes)(data);
14843 return array.buffer;
14844}
14845
14846class NetworkManager {
14847 constructor(url, args = {}) {
14848 this.url = url;
14849 this.isHttp = /^https?:/i.test(url);
14850 this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
14851 this.withCredentials = args.withCredentials || false;
14852
14853 this.getXhr = args.getXhr || function NetworkManager_getXhr() {
14854 return new XMLHttpRequest();
14855 };
14856
14857 this.currXhrId = 0;
14858 this.pendingRequests = Object.create(null);
14859 }
14860
14861 requestRange(begin, end, listeners) {
14862 const args = {
14863 begin,
14864 end
14865 };
14866
14867 for (const prop in listeners) {
14868 args[prop] = listeners[prop];
14869 }
14870
14871 return this.request(args);
14872 }
14873
14874 requestFull(listeners) {
14875 return this.request(listeners);
14876 }
14877
14878 request(args) {
14879 const xhr = this.getXhr();
14880 const xhrId = this.currXhrId++;
14881 const pendingRequest = this.pendingRequests[xhrId] = {
14882 xhr
14883 };
14884 xhr.open("GET", this.url);
14885 xhr.withCredentials = this.withCredentials;
14886
14887 for (const property in this.httpHeaders) {
14888 const value = this.httpHeaders[property];
14889
14890 if (typeof value === "undefined") {
14891 continue;
14892 }
14893
14894 xhr.setRequestHeader(property, value);
14895 }
14896
14897 if (this.isHttp && "begin" in args && "end" in args) {
14898 xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
14899 pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
14900 } else {
14901 pendingRequest.expectedStatus = OK_RESPONSE;
14902 }
14903
14904 xhr.responseType = "arraybuffer";
14905
14906 if (args.onError) {
14907 xhr.onerror = function (evt) {
14908 args.onError(xhr.status);
14909 };
14910 }
14911
14912 xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
14913 xhr.onprogress = this.onProgress.bind(this, xhrId);
14914 pendingRequest.onHeadersReceived = args.onHeadersReceived;
14915 pendingRequest.onDone = args.onDone;
14916 pendingRequest.onError = args.onError;
14917 pendingRequest.onProgress = args.onProgress;
14918 xhr.send(null);
14919 return xhrId;
14920 }
14921
14922 onProgress(xhrId, evt) {
14923 const pendingRequest = this.pendingRequests[xhrId];
14924
14925 if (!pendingRequest) {
14926 return;
14927 }
14928
14929 pendingRequest.onProgress?.(evt);
14930 }
14931
14932 onStateChange(xhrId, evt) {
14933 const pendingRequest = this.pendingRequests[xhrId];
14934
14935 if (!pendingRequest) {
14936 return;
14937 }
14938
14939 const xhr = pendingRequest.xhr;
14940
14941 if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
14942 pendingRequest.onHeadersReceived();
14943 delete pendingRequest.onHeadersReceived;
14944 }
14945
14946 if (xhr.readyState !== 4) {
14947 return;
14948 }
14949
14950 if (!(xhrId in this.pendingRequests)) {
14951 return;
14952 }
14953
14954 delete this.pendingRequests[xhrId];
14955
14956 if (xhr.status === 0 && this.isHttp) {
14957 pendingRequest.onError?.(xhr.status);
14958 return;
14959 }
14960
14961 const xhrStatus = xhr.status || OK_RESPONSE;
14962 const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
14963
14964 if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
14965 pendingRequest.onError?.(xhr.status);
14966 return;
14967 }
14968
14969 const chunk = getArrayBuffer(xhr);
14970
14971 if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
14972 const rangeHeader = xhr.getResponseHeader("Content-Range");
14973 const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
14974 pendingRequest.onDone({
14975 begin: parseInt(matches[1], 10),
14976 chunk
14977 });
14978 } else if (chunk) {
14979 pendingRequest.onDone({
14980 begin: 0,
14981 chunk
14982 });
14983 } else {
14984 pendingRequest.onError?.(xhr.status);
14985 }
14986 }
14987
14988 getRequestXhr(xhrId) {
14989 return this.pendingRequests[xhrId].xhr;
14990 }
14991
14992 isPendingRequest(xhrId) {
14993 return xhrId in this.pendingRequests;
14994 }
14995
14996 abortRequest(xhrId) {
14997 const xhr = this.pendingRequests[xhrId].xhr;
14998 delete this.pendingRequests[xhrId];
14999 xhr.abort();
15000 }
15001
15002}
15003
15004class PDFNetworkStream {
15005 constructor(source) {
15006 this._source = source;
15007 this._manager = new NetworkManager(source.url, {
15008 httpHeaders: source.httpHeaders,
15009 withCredentials: source.withCredentials
15010 });
15011 this._rangeChunkSize = source.rangeChunkSize;
15012 this._fullRequestReader = null;
15013 this._rangeRequestReaders = [];
15014 }
15015
15016 _onRangeRequestReaderClosed(reader) {
15017 const i = this._rangeRequestReaders.indexOf(reader);
15018
15019 if (i >= 0) {
15020 this._rangeRequestReaders.splice(i, 1);
15021 }
15022 }
15023
15024 getFullReader() {
15025 (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
15026 this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
15027 return this._fullRequestReader;
15028 }
15029
15030 getRangeReader(begin, end) {
15031 const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
15032 reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
15033
15034 this._rangeRequestReaders.push(reader);
15035
15036 return reader;
15037 }
15038
15039 cancelAllRequests(reason) {
15040 this._fullRequestReader?.cancel(reason);
15041
15042 for (const reader of this._rangeRequestReaders.slice(0)) {
15043 reader.cancel(reason);
15044 }
15045 }
15046
15047}
15048
15049exports.PDFNetworkStream = PDFNetworkStream;
15050
15051class PDFNetworkStreamFullRequestReader {
15052 constructor(manager, source) {
15053 this._manager = manager;
15054 const args = {
15055 onHeadersReceived: this._onHeadersReceived.bind(this),
15056 onDone: this._onDone.bind(this),
15057 onError: this._onError.bind(this),
15058 onProgress: this._onProgress.bind(this)
15059 };
15060 this._url = source.url;
15061 this._fullRequestId = manager.requestFull(args);
15062 this._headersReceivedCapability = (0, _util.createPromiseCapability)();
15063 this._disableRange = source.disableRange || false;
15064 this._contentLength = source.length;
15065 this._rangeChunkSize = source.rangeChunkSize;
15066
15067 if (!this._rangeChunkSize && !this._disableRange) {
15068 this._disableRange = true;
15069 }
15070
15071 this._isStreamingSupported = false;
15072 this._isRangeSupported = false;
15073 this._cachedChunks = [];
15074 this._requests = [];
15075 this._done = false;
15076 this._storedError = undefined;
15077 this._filename = null;
15078 this.onProgress = null;
15079 }
15080
15081 _onHeadersReceived() {
15082 const fullRequestXhrId = this._fullRequestId;
15083
15084 const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
15085
15086 const getResponseHeader = name => {
15087 return fullRequestXhr.getResponseHeader(name);
15088 };
15089
15090 const {
15091 allowRangeRequests,
15092 suggestedLength
15093 } = (0, _network_utils.validateRangeRequestCapabilities)({
15094 getResponseHeader,
15095 isHttp: this._manager.isHttp,
15096 rangeChunkSize: this._rangeChunkSize,
15097 disableRange: this._disableRange
15098 });
15099
15100 if (allowRangeRequests) {
15101 this._isRangeSupported = true;
15102 }
15103
15104 this._contentLength = suggestedLength || this._contentLength;
15105 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
15106
15107 if (this._isRangeSupported) {
15108 this._manager.abortRequest(fullRequestXhrId);
15109 }
15110
15111 this._headersReceivedCapability.resolve();
15112 }
15113
15114 _onDone(data) {
15115 if (data) {
15116 if (this._requests.length > 0) {
15117 const requestCapability = this._requests.shift();
15118
15119 requestCapability.resolve({
15120 value: data.chunk,
15121 done: false
15122 });
15123 } else {
15124 this._cachedChunks.push(data.chunk);
15125 }
15126 }
15127
15128 this._done = true;
15129
15130 if (this._cachedChunks.length > 0) {
15131 return;
15132 }
15133
15134 for (const requestCapability of this._requests) {
15135 requestCapability.resolve({
15136 value: undefined,
15137 done: true
15138 });
15139 }
15140
15141 this._requests.length = 0;
15142 }
15143
15144 _onError(status) {
15145 this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
15146
15147 this._headersReceivedCapability.reject(this._storedError);
15148
15149 for (const requestCapability of this._requests) {
15150 requestCapability.reject(this._storedError);
15151 }
15152
15153 this._requests.length = 0;
15154 this._cachedChunks.length = 0;
15155 }
15156
15157 _onProgress(evt) {
15158 this.onProgress?.({
15159 loaded: evt.loaded,
15160 total: evt.lengthComputable ? evt.total : this._contentLength
15161 });
15162 }
15163
15164 get filename() {
15165 return this._filename;
15166 }
15167
15168 get isRangeSupported() {
15169 return this._isRangeSupported;
15170 }
15171
15172 get isStreamingSupported() {
15173 return this._isStreamingSupported;
15174 }
15175
15176 get contentLength() {
15177 return this._contentLength;
15178 }
15179
15180 get headersReady() {
15181 return this._headersReceivedCapability.promise;
15182 }
15183
15184 async read() {
15185 if (this._storedError) {
15186 throw this._storedError;
15187 }
15188
15189 if (this._cachedChunks.length > 0) {
15190 const chunk = this._cachedChunks.shift();
15191
15192 return {
15193 value: chunk,
15194 done: false
15195 };
15196 }
15197
15198 if (this._done) {
15199 return {
15200 value: undefined,
15201 done: true
15202 };
15203 }
15204
15205 const requestCapability = (0, _util.createPromiseCapability)();
15206
15207 this._requests.push(requestCapability);
15208
15209 return requestCapability.promise;
15210 }
15211
15212 cancel(reason) {
15213 this._done = true;
15214
15215 this._headersReceivedCapability.reject(reason);
15216
15217 for (const requestCapability of this._requests) {
15218 requestCapability.resolve({
15219 value: undefined,
15220 done: true
15221 });
15222 }
15223
15224 this._requests.length = 0;
15225
15226 if (this._manager.isPendingRequest(this._fullRequestId)) {
15227 this._manager.abortRequest(this._fullRequestId);
15228 }
15229
15230 this._fullRequestReader = null;
15231 }
15232
15233}
15234
15235class PDFNetworkStreamRangeRequestReader {
15236 constructor(manager, begin, end) {
15237 this._manager = manager;
15238 const args = {
15239 onDone: this._onDone.bind(this),
15240 onError: this._onError.bind(this),
15241 onProgress: this._onProgress.bind(this)
15242 };
15243 this._url = manager.url;
15244 this._requestId = manager.requestRange(begin, end, args);
15245 this._requests = [];
15246 this._queuedChunk = null;
15247 this._done = false;
15248 this._storedError = undefined;
15249 this.onProgress = null;
15250 this.onClosed = null;
15251 }
15252
15253 _close() {
15254 this.onClosed?.(this);
15255 }
15256
15257 _onDone(data) {
15258 const chunk = data.chunk;
15259
15260 if (this._requests.length > 0) {
15261 const requestCapability = this._requests.shift();
15262
15263 requestCapability.resolve({
15264 value: chunk,
15265 done: false
15266 });
15267 } else {
15268 this._queuedChunk = chunk;
15269 }
15270
15271 this._done = true;
15272
15273 for (const requestCapability of this._requests) {
15274 requestCapability.resolve({
15275 value: undefined,
15276 done: true
15277 });
15278 }
15279
15280 this._requests.length = 0;
15281
15282 this._close();
15283 }
15284
15285 _onError(status) {
15286 this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
15287
15288 for (const requestCapability of this._requests) {
15289 requestCapability.reject(this._storedError);
15290 }
15291
15292 this._requests.length = 0;
15293 this._queuedChunk = null;
15294 }
15295
15296 _onProgress(evt) {
15297 if (!this.isStreamingSupported) {
15298 this.onProgress?.({
15299 loaded: evt.loaded
15300 });
15301 }
15302 }
15303
15304 get isStreamingSupported() {
15305 return false;
15306 }
15307
15308 async read() {
15309 if (this._storedError) {
15310 throw this._storedError;
15311 }
15312
15313 if (this._queuedChunk !== null) {
15314 const chunk = this._queuedChunk;
15315 this._queuedChunk = null;
15316 return {
15317 value: chunk,
15318 done: false
15319 };
15320 }
15321
15322 if (this._done) {
15323 return {
15324 value: undefined,
15325 done: true
15326 };
15327 }
15328
15329 const requestCapability = (0, _util.createPromiseCapability)();
15330
15331 this._requests.push(requestCapability);
15332
15333 return requestCapability.promise;
15334 }
15335
15336 cancel(reason) {
15337 this._done = true;
15338
15339 for (const requestCapability of this._requests) {
15340 requestCapability.resolve({
15341 value: undefined,
15342 done: true
15343 });
15344 }
15345
15346 this._requests.length = 0;
15347
15348 if (this._manager.isPendingRequest(this._requestId)) {
15349 this._manager.abortRequest(this._requestId);
15350 }
15351
15352 this._close();
15353 }
15354
15355}
15356
15357/***/ }),
15358/* 27 */
15359/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
15360
15361
15362
15363Object.defineProperty(exports, "__esModule", ({
15364 value: true
15365}));
15366exports.PDFFetchStream = void 0;
15367
15368var _util = __w_pdfjs_require__(2);
15369
15370var _network_utils = __w_pdfjs_require__(24);
15371
15372;
15373
15374function createFetchOptions(headers, withCredentials, abortController) {
15375 return {
15376 method: "GET",
15377 headers,
15378 signal: abortController?.signal,
15379 mode: "cors",
15380 credentials: withCredentials ? "include" : "same-origin",
15381 redirect: "follow"
15382 };
15383}
15384
15385function createHeaders(httpHeaders) {
15386 const headers = new Headers();
15387
15388 for (const property in httpHeaders) {
15389 const value = httpHeaders[property];
15390
15391 if (typeof value === "undefined") {
15392 continue;
15393 }
15394
15395 headers.append(property, value);
15396 }
15397
15398 return headers;
15399}
15400
15401class PDFFetchStream {
15402 constructor(source) {
15403 this.source = source;
15404 this.isHttp = /^https?:/i.test(source.url);
15405 this.httpHeaders = this.isHttp && source.httpHeaders || {};
15406 this._fullRequestReader = null;
15407 this._rangeRequestReaders = [];
15408 }
15409
15410 get _progressiveDataLength() {
15411 return this._fullRequestReader?._loaded ?? 0;
15412 }
15413
15414 getFullReader() {
15415 (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
15416 this._fullRequestReader = new PDFFetchStreamReader(this);
15417 return this._fullRequestReader;
15418 }
15419
15420 getRangeReader(begin, end) {
15421 if (end <= this._progressiveDataLength) {
15422 return null;
15423 }
15424
15425 const reader = new PDFFetchStreamRangeReader(this, begin, end);
15426
15427 this._rangeRequestReaders.push(reader);
15428
15429 return reader;
15430 }
15431
15432 cancelAllRequests(reason) {
15433 if (this._fullRequestReader) {
15434 this._fullRequestReader.cancel(reason);
15435 }
15436
15437 for (const reader of this._rangeRequestReaders.slice(0)) {
15438 reader.cancel(reason);
15439 }
15440 }
15441
15442}
15443
15444exports.PDFFetchStream = PDFFetchStream;
15445
15446class PDFFetchStreamReader {
15447 constructor(stream) {
15448 this._stream = stream;
15449 this._reader = null;
15450 this._loaded = 0;
15451 this._filename = null;
15452 const source = stream.source;
15453 this._withCredentials = source.withCredentials || false;
15454 this._contentLength = source.length;
15455 this._headersCapability = (0, _util.createPromiseCapability)();
15456 this._disableRange = source.disableRange || false;
15457 this._rangeChunkSize = source.rangeChunkSize;
15458
15459 if (!this._rangeChunkSize && !this._disableRange) {
15460 this._disableRange = true;
15461 }
15462
15463 if (typeof AbortController !== "undefined") {
15464 this._abortController = new AbortController();
15465 }
15466
15467 this._isStreamingSupported = !source.disableStream;
15468 this._isRangeSupported = !source.disableRange;
15469 this._headers = createHeaders(this._stream.httpHeaders);
15470 const url = source.url;
15471 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
15472 if (!(0, _network_utils.validateResponseStatus)(response.status)) {
15473 throw (0, _network_utils.createResponseStatusError)(response.status, url);
15474 }
15475
15476 this._reader = response.body.getReader();
15477
15478 this._headersCapability.resolve();
15479
15480 const getResponseHeader = name => {
15481 return response.headers.get(name);
15482 };
15483
15484 const {
15485 allowRangeRequests,
15486 suggestedLength
15487 } = (0, _network_utils.validateRangeRequestCapabilities)({
15488 getResponseHeader,
15489 isHttp: this._stream.isHttp,
15490 rangeChunkSize: this._rangeChunkSize,
15491 disableRange: this._disableRange
15492 });
15493 this._isRangeSupported = allowRangeRequests;
15494 this._contentLength = suggestedLength || this._contentLength;
15495 this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
15496
15497 if (!this._isStreamingSupported && this._isRangeSupported) {
15498 this.cancel(new _util.AbortException("Streaming is disabled."));
15499 }
15500 }).catch(this._headersCapability.reject);
15501 this.onProgress = null;
15502 }
15503
15504 get headersReady() {
15505 return this._headersCapability.promise;
15506 }
15507
15508 get filename() {
15509 return this._filename;
15510 }
15511
15512 get contentLength() {
15513 return this._contentLength;
15514 }
15515
15516 get isRangeSupported() {
15517 return this._isRangeSupported;
15518 }
15519
15520 get isStreamingSupported() {
15521 return this._isStreamingSupported;
15522 }
15523
15524 async read() {
15525 await this._headersCapability.promise;
15526 const {
15527 value,
15528 done
15529 } = await this._reader.read();
15530
15531 if (done) {
15532 return {
15533 value,
15534 done
15535 };
15536 }
15537
15538 this._loaded += value.byteLength;
15539
15540 if (this.onProgress) {
15541 this.onProgress({
15542 loaded: this._loaded,
15543 total: this._contentLength
15544 });
15545 }
15546
15547 const buffer = new Uint8Array(value).buffer;
15548 return {
15549 value: buffer,
15550 done: false
15551 };
15552 }
15553
15554 cancel(reason) {
15555 if (this._reader) {
15556 this._reader.cancel(reason);
15557 }
15558
15559 if (this._abortController) {
15560 this._abortController.abort();
15561 }
15562 }
15563
15564}
15565
15566class PDFFetchStreamRangeReader {
15567 constructor(stream, begin, end) {
15568 this._stream = stream;
15569 this._reader = null;
15570 this._loaded = 0;
15571 const source = stream.source;
15572 this._withCredentials = source.withCredentials || false;
15573 this._readCapability = (0, _util.createPromiseCapability)();
15574 this._isStreamingSupported = !source.disableStream;
15575
15576 if (typeof AbortController !== "undefined") {
15577 this._abortController = new AbortController();
15578 }
15579
15580 this._headers = createHeaders(this._stream.httpHeaders);
15581
15582 this._headers.append("Range", `bytes=${begin}-${end - 1}`);
15583
15584 const url = source.url;
15585 fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
15586 if (!(0, _network_utils.validateResponseStatus)(response.status)) {
15587 throw (0, _network_utils.createResponseStatusError)(response.status, url);
15588 }
15589
15590 this._readCapability.resolve();
15591
15592 this._reader = response.body.getReader();
15593 }).catch(this._readCapability.reject);
15594 this.onProgress = null;
15595 }
15596
15597 get isStreamingSupported() {
15598 return this._isStreamingSupported;
15599 }
15600
15601 async read() {
15602 await this._readCapability.promise;
15603 const {
15604 value,
15605 done
15606 } = await this._reader.read();
15607
15608 if (done) {
15609 return {
15610 value,
15611 done
15612 };
15613 }
15614
15615 this._loaded += value.byteLength;
15616
15617 if (this.onProgress) {
15618 this.onProgress({
15619 loaded: this._loaded
15620 });
15621 }
15622
15623 const buffer = new Uint8Array(value).buffer;
15624 return {
15625 value: buffer,
15626 done: false
15627 };
15628 }
15629
15630 cancel(reason) {
15631 if (this._reader) {
15632 this._reader.cancel(reason);
15633 }
15634
15635 if (this._abortController) {
15636 this._abortController.abort();
15637 }
15638 }
15639
15640}
15641
15642/***/ })
15643/******/ ]);
15644/************************************************************************/
15645/******/ // The module cache
15646/******/ var __webpack_module_cache__ = {};
15647/******/
15648/******/ // The require function
15649/******/ function __w_pdfjs_require__(moduleId) {
15650/******/ // Check if module is in cache
15651/******/ var cachedModule = __webpack_module_cache__[moduleId];
15652/******/ if (cachedModule !== undefined) {
15653/******/ return cachedModule.exports;
15654/******/ }
15655/******/ // Create a new module (and put it into the cache)
15656/******/ var module = __webpack_module_cache__[moduleId] = {
15657/******/ // no module.id needed
15658/******/ // no module.loaded needed
15659/******/ exports: {}
15660/******/ };
15661/******/
15662/******/ // Execute the module function
15663/******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
15664/******/
15665/******/ // Return the exports of the module
15666/******/ return module.exports;
15667/******/ }
15668/******/
15669/************************************************************************/
15670var __webpack_exports__ = {};
15671// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
15672(() => {
15673var exports = __webpack_exports__;
15674
15675
15676Object.defineProperty(exports, "__esModule", ({
15677 value: true
15678}));
15679Object.defineProperty(exports, "AnnotationLayer", ({
15680 enumerable: true,
15681 get: function () {
15682 return _annotation_layer.AnnotationLayer;
15683 }
15684}));
15685Object.defineProperty(exports, "AnnotationMode", ({
15686 enumerable: true,
15687 get: function () {
15688 return _util.AnnotationMode;
15689 }
15690}));
15691Object.defineProperty(exports, "CMapCompressionType", ({
15692 enumerable: true,
15693 get: function () {
15694 return _util.CMapCompressionType;
15695 }
15696}));
15697Object.defineProperty(exports, "GlobalWorkerOptions", ({
15698 enumerable: true,
15699 get: function () {
15700 return _worker_options.GlobalWorkerOptions;
15701 }
15702}));
15703Object.defineProperty(exports, "InvalidPDFException", ({
15704 enumerable: true,
15705 get: function () {
15706 return _util.InvalidPDFException;
15707 }
15708}));
15709Object.defineProperty(exports, "LinkTarget", ({
15710 enumerable: true,
15711 get: function () {
15712 return _display_utils.LinkTarget;
15713 }
15714}));
15715Object.defineProperty(exports, "LoopbackPort", ({
15716 enumerable: true,
15717 get: function () {
15718 return _api.LoopbackPort;
15719 }
15720}));
15721Object.defineProperty(exports, "MissingPDFException", ({
15722 enumerable: true,
15723 get: function () {
15724 return _util.MissingPDFException;
15725 }
15726}));
15727Object.defineProperty(exports, "OPS", ({
15728 enumerable: true,
15729 get: function () {
15730 return _util.OPS;
15731 }
15732}));
15733Object.defineProperty(exports, "PDFDataRangeTransport", ({
15734 enumerable: true,
15735 get: function () {
15736 return _api.PDFDataRangeTransport;
15737 }
15738}));
15739Object.defineProperty(exports, "PDFDateString", ({
15740 enumerable: true,
15741 get: function () {
15742 return _display_utils.PDFDateString;
15743 }
15744}));
15745Object.defineProperty(exports, "PDFWorker", ({
15746 enumerable: true,
15747 get: function () {
15748 return _api.PDFWorker;
15749 }
15750}));
15751Object.defineProperty(exports, "PasswordResponses", ({
15752 enumerable: true,
15753 get: function () {
15754 return _util.PasswordResponses;
15755 }
15756}));
15757Object.defineProperty(exports, "PermissionFlag", ({
15758 enumerable: true,
15759 get: function () {
15760 return _util.PermissionFlag;
15761 }
15762}));
15763Object.defineProperty(exports, "PixelsPerInch", ({
15764 enumerable: true,
15765 get: function () {
15766 return _display_utils.PixelsPerInch;
15767 }
15768}));
15769Object.defineProperty(exports, "RenderingCancelledException", ({
15770 enumerable: true,
15771 get: function () {
15772 return _display_utils.RenderingCancelledException;
15773 }
15774}));
15775Object.defineProperty(exports, "SVGGraphics", ({
15776 enumerable: true,
15777 get: function () {
15778 return _svg.SVGGraphics;
15779 }
15780}));
15781Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
15782 enumerable: true,
15783 get: function () {
15784 return _util.UNSUPPORTED_FEATURES;
15785 }
15786}));
15787Object.defineProperty(exports, "UnexpectedResponseException", ({
15788 enumerable: true,
15789 get: function () {
15790 return _util.UnexpectedResponseException;
15791 }
15792}));
15793Object.defineProperty(exports, "Util", ({
15794 enumerable: true,
15795 get: function () {
15796 return _util.Util;
15797 }
15798}));
15799Object.defineProperty(exports, "VerbosityLevel", ({
15800 enumerable: true,
15801 get: function () {
15802 return _util.VerbosityLevel;
15803 }
15804}));
15805Object.defineProperty(exports, "XfaLayer", ({
15806 enumerable: true,
15807 get: function () {
15808 return _xfa_layer.XfaLayer;
15809 }
15810}));
15811Object.defineProperty(exports, "addLinkAttributes", ({
15812 enumerable: true,
15813 get: function () {
15814 return _display_utils.addLinkAttributes;
15815 }
15816}));
15817Object.defineProperty(exports, "build", ({
15818 enumerable: true,
15819 get: function () {
15820 return _api.build;
15821 }
15822}));
15823Object.defineProperty(exports, "createObjectURL", ({
15824 enumerable: true,
15825 get: function () {
15826 return _util.createObjectURL;
15827 }
15828}));
15829Object.defineProperty(exports, "createPromiseCapability", ({
15830 enumerable: true,
15831 get: function () {
15832 return _util.createPromiseCapability;
15833 }
15834}));
15835Object.defineProperty(exports, "createValidAbsoluteUrl", ({
15836 enumerable: true,
15837 get: function () {
15838 return _util.createValidAbsoluteUrl;
15839 }
15840}));
15841Object.defineProperty(exports, "getDocument", ({
15842 enumerable: true,
15843 get: function () {
15844 return _api.getDocument;
15845 }
15846}));
15847Object.defineProperty(exports, "getFilenameFromUrl", ({
15848 enumerable: true,
15849 get: function () {
15850 return _display_utils.getFilenameFromUrl;
15851 }
15852}));
15853Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
15854 enumerable: true,
15855 get: function () {
15856 return _display_utils.getPdfFilenameFromUrl;
15857 }
15858}));
15859Object.defineProperty(exports, "getXfaPageViewport", ({
15860 enumerable: true,
15861 get: function () {
15862 return _display_utils.getXfaPageViewport;
15863 }
15864}));
15865Object.defineProperty(exports, "isPdfFile", ({
15866 enumerable: true,
15867 get: function () {
15868 return _display_utils.isPdfFile;
15869 }
15870}));
15871Object.defineProperty(exports, "loadScript", ({
15872 enumerable: true,
15873 get: function () {
15874 return _display_utils.loadScript;
15875 }
15876}));
15877Object.defineProperty(exports, "removeNullCharacters", ({
15878 enumerable: true,
15879 get: function () {
15880 return _util.removeNullCharacters;
15881 }
15882}));
15883Object.defineProperty(exports, "renderTextLayer", ({
15884 enumerable: true,
15885 get: function () {
15886 return _text_layer.renderTextLayer;
15887 }
15888}));
15889Object.defineProperty(exports, "shadow", ({
15890 enumerable: true,
15891 get: function () {
15892 return _util.shadow;
15893 }
15894}));
15895Object.defineProperty(exports, "version", ({
15896 enumerable: true,
15897 get: function () {
15898 return _api.version;
15899 }
15900}));
15901
15902var _display_utils = __w_pdfjs_require__(1);
15903
15904var _util = __w_pdfjs_require__(2);
15905
15906var _api = __w_pdfjs_require__(6);
15907
15908var _annotation_layer = __w_pdfjs_require__(18);
15909
15910var _worker_options = __w_pdfjs_require__(12);
15911
15912var _is_node = __w_pdfjs_require__(4);
15913
15914var _text_layer = __w_pdfjs_require__(21);
15915
15916var _svg = __w_pdfjs_require__(22);
15917
15918var _xfa_layer = __w_pdfjs_require__(20);
15919
15920const pdfjsVersion = '2.12.313';
15921const pdfjsBuild = 'a2ae56f39';
15922{
15923 if (_is_node.isNodeJS) {
15924 const {
15925 PDFNodeStream
15926 } = __w_pdfjs_require__(23);
15927
15928 (0, _api.setPDFNetworkStreamFactory)(params => {
15929 return new PDFNodeStream(params);
15930 });
15931 } else {
15932 const {
15933 PDFNetworkStream
15934 } = __w_pdfjs_require__(26);
15935
15936 const {
15937 PDFFetchStream
15938 } = __w_pdfjs_require__(27);
15939
15940 (0, _api.setPDFNetworkStreamFactory)(params => {
15941 if ((0, _display_utils.isValidFetchUrl)(params.url)) {
15942 return new PDFFetchStream(params);
15943 }
15944
15945 return new PDFNetworkStream(params);
15946 });
15947 }
15948}
15949})();
15950
15951/******/ return __webpack_exports__;
15952/******/ })()
15953;
15954});
15955//# sourceMappingURL=pdf.js.map
\No newline at end of file