@chialab/pdfjs-lib 1.0.0-alpha.20 → 1.0.0-alpha.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1142 +0,0 @@
1
- import {
2
- BaseException,
3
- FeatureTest,
4
- Util,
5
- shadow,
6
- unreachable,
7
- updateUrlHash,
8
- warn
9
- } from "./chunk-NJUB3B5A.js";
10
- import {
11
- __privateAdd,
12
- __privateGet,
13
- __privateMethod,
14
- __privateSet,
15
- __privateWrapper,
16
- __publicField
17
- } from "./chunk-O4UKW7AD.js";
18
-
19
- // src/pdf.js/src/display/display_utils.js
20
- var SVG_NS = "http://www.w3.org/2000/svg";
21
- var _PixelsPerInch = class _PixelsPerInch {
22
- };
23
- __publicField(_PixelsPerInch, "CSS", 96);
24
- __publicField(_PixelsPerInch, "PDF", 72);
25
- __publicField(_PixelsPerInch, "PDF_TO_CSS_UNITS", _PixelsPerInch.CSS / _PixelsPerInch.PDF);
26
- var PixelsPerInch = _PixelsPerInch;
27
- async function fetchData(url, type = "text") {
28
- if (isValidFetchUrl(url, document.baseURI)) {
29
- const response = await fetch(url);
30
- if (!response.ok) {
31
- throw new Error(response.statusText);
32
- }
33
- switch (type) {
34
- case "arraybuffer":
35
- return response.arrayBuffer();
36
- case "blob":
37
- return response.blob();
38
- case "json":
39
- return response.json();
40
- }
41
- return response.text();
42
- }
43
- return new Promise((resolve, reject) => {
44
- const request = new XMLHttpRequest();
45
- request.open(
46
- "GET",
47
- url,
48
- /* async = */
49
- true
50
- );
51
- request.responseType = type;
52
- request.onreadystatechange = () => {
53
- if (request.readyState !== XMLHttpRequest.DONE) {
54
- return;
55
- }
56
- if (request.status === 200 || request.status === 0) {
57
- switch (type) {
58
- case "arraybuffer":
59
- case "blob":
60
- case "json":
61
- resolve(request.response);
62
- return;
63
- }
64
- resolve(request.responseText);
65
- return;
66
- }
67
- reject(new Error(request.statusText));
68
- };
69
- request.send(null);
70
- });
71
- }
72
- var PageViewport = class _PageViewport {
73
- /**
74
- * @param {PageViewportParameters}
75
- */
76
- constructor({
77
- viewBox,
78
- userUnit,
79
- scale,
80
- rotation,
81
- offsetX = 0,
82
- offsetY = 0,
83
- dontFlip = false
84
- }) {
85
- this.viewBox = viewBox;
86
- this.userUnit = userUnit;
87
- this.scale = scale;
88
- this.rotation = rotation;
89
- this.offsetX = offsetX;
90
- this.offsetY = offsetY;
91
- scale *= userUnit;
92
- const centerX = (viewBox[2] + viewBox[0]) / 2;
93
- const centerY = (viewBox[3] + viewBox[1]) / 2;
94
- let rotateA, rotateB, rotateC, rotateD;
95
- rotation %= 360;
96
- if (rotation < 0) {
97
- rotation += 360;
98
- }
99
- switch (rotation) {
100
- case 180:
101
- rotateA = -1;
102
- rotateB = 0;
103
- rotateC = 0;
104
- rotateD = 1;
105
- break;
106
- case 90:
107
- rotateA = 0;
108
- rotateB = 1;
109
- rotateC = 1;
110
- rotateD = 0;
111
- break;
112
- case 270:
113
- rotateA = 0;
114
- rotateB = -1;
115
- rotateC = -1;
116
- rotateD = 0;
117
- break;
118
- case 0:
119
- rotateA = 1;
120
- rotateB = 0;
121
- rotateC = 0;
122
- rotateD = -1;
123
- break;
124
- default:
125
- throw new Error(
126
- "PageViewport: Invalid rotation, must be a multiple of 90 degrees."
127
- );
128
- }
129
- if (dontFlip) {
130
- rotateC = -rotateC;
131
- rotateD = -rotateD;
132
- }
133
- let offsetCanvasX, offsetCanvasY;
134
- let width, height;
135
- if (rotateA === 0) {
136
- offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
137
- offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
138
- width = (viewBox[3] - viewBox[1]) * scale;
139
- height = (viewBox[2] - viewBox[0]) * scale;
140
- } else {
141
- offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
142
- offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
143
- width = (viewBox[2] - viewBox[0]) * scale;
144
- height = (viewBox[3] - viewBox[1]) * scale;
145
- }
146
- this.transform = [
147
- rotateA * scale,
148
- rotateB * scale,
149
- rotateC * scale,
150
- rotateD * scale,
151
- offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
152
- offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
153
- ];
154
- this.width = width;
155
- this.height = height;
156
- }
157
- /**
158
- * The original, un-scaled, viewport dimensions.
159
- * @type {Object}
160
- */
161
- get rawDims() {
162
- const dims = this.viewBox;
163
- return shadow(this, "rawDims", {
164
- pageWidth: dims[2] - dims[0],
165
- pageHeight: dims[3] - dims[1],
166
- pageX: dims[0],
167
- pageY: dims[1]
168
- });
169
- }
170
- /**
171
- * Clones viewport, with optional additional properties.
172
- * @param {PageViewportCloneParameters} [params]
173
- * @returns {PageViewport} Cloned viewport.
174
- */
175
- clone({
176
- scale = this.scale,
177
- rotation = this.rotation,
178
- offsetX = this.offsetX,
179
- offsetY = this.offsetY,
180
- dontFlip = false
181
- } = {}) {
182
- return new _PageViewport({
183
- viewBox: this.viewBox.slice(),
184
- userUnit: this.userUnit,
185
- scale,
186
- rotation,
187
- offsetX,
188
- offsetY,
189
- dontFlip
190
- });
191
- }
192
- /**
193
- * Converts PDF point to the viewport coordinates. For examples, useful for
194
- * converting PDF location into canvas pixel coordinates.
195
- * @param {number} x - The x-coordinate.
196
- * @param {number} y - The y-coordinate.
197
- * @returns {Array} Array containing `x`- and `y`-coordinates of the
198
- * point in the viewport coordinate space.
199
- * @see {@link convertToPdfPoint}
200
- * @see {@link convertToViewportRectangle}
201
- */
202
- convertToViewportPoint(x, y) {
203
- const p = [x, y];
204
- Util.applyTransform(p, this.transform);
205
- return p;
206
- }
207
- /**
208
- * Converts PDF rectangle to the viewport coordinates.
209
- * @param {Array} rect - The xMin, yMin, xMax and yMax coordinates.
210
- * @returns {Array} Array containing corresponding coordinates of the
211
- * rectangle in the viewport coordinate space.
212
- * @see {@link convertToViewportPoint}
213
- */
214
- convertToViewportRectangle(rect) {
215
- const topLeft = [rect[0], rect[1]];
216
- Util.applyTransform(topLeft, this.transform);
217
- const bottomRight = [rect[2], rect[3]];
218
- Util.applyTransform(bottomRight, this.transform);
219
- return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
220
- }
221
- /**
222
- * Converts viewport coordinates to the PDF location. For examples, useful
223
- * for converting canvas pixel location into PDF one.
224
- * @param {number} x - The x-coordinate.
225
- * @param {number} y - The y-coordinate.
226
- * @returns {Array} Array containing `x`- and `y`-coordinates of the
227
- * point in the PDF coordinate space.
228
- * @see {@link convertToViewportPoint}
229
- */
230
- convertToPdfPoint(x, y) {
231
- const p = [x, y];
232
- Util.applyInverseTransform(p, this.transform);
233
- return p;
234
- }
235
- };
236
- var RenderingCancelledException = class extends BaseException {
237
- constructor(msg, extraDelay = 0) {
238
- super(msg, "RenderingCancelledException");
239
- this.extraDelay = extraDelay;
240
- }
241
- };
242
- function isDataScheme(url) {
243
- const ii = url.length;
244
- let i = 0;
245
- while (i < ii && url[i].trim() === "") {
246
- i++;
247
- }
248
- return url.substring(i, i + 5).toLowerCase() === "data:";
249
- }
250
- function isPdfFile(filename) {
251
- return typeof filename === "string" && /\.pdf$/i.test(filename);
252
- }
253
- function getFilenameFromUrl(url) {
254
- [url] = url.split(/[#?]/, 1);
255
- return url.substring(url.lastIndexOf("/") + 1);
256
- }
257
- function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
258
- if (typeof url !== "string") {
259
- return defaultFilename;
260
- }
261
- if (isDataScheme(url)) {
262
- warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
263
- return defaultFilename;
264
- }
265
- const getURL = (urlString) => {
266
- try {
267
- return new URL(urlString);
268
- } catch {
269
- try {
270
- return new URL(decodeURIComponent(urlString));
271
- } catch {
272
- try {
273
- return new URL(urlString, "https://foo.bar");
274
- } catch {
275
- try {
276
- return new URL(decodeURIComponent(urlString), "https://foo.bar");
277
- } catch {
278
- return null;
279
- }
280
- }
281
- }
282
- }
283
- };
284
- const newURL = getURL(url);
285
- if (!newURL) {
286
- return defaultFilename;
287
- }
288
- const decode = (name) => {
289
- try {
290
- let decoded = decodeURIComponent(name);
291
- if (decoded.includes("/")) {
292
- decoded = decoded.split("/").at(-1);
293
- if (decoded.test(/^\.pdf$/i)) {
294
- return decoded;
295
- }
296
- return name;
297
- }
298
- return decoded;
299
- } catch {
300
- return name;
301
- }
302
- };
303
- const pdfRegex = /\.pdf$/i;
304
- const filename = newURL.pathname.split("/").at(-1);
305
- if (pdfRegex.test(filename)) {
306
- return decode(filename);
307
- }
308
- if (newURL.searchParams.size > 0) {
309
- const values = Array.from(newURL.searchParams.values()).reverse();
310
- for (const value of values) {
311
- if (pdfRegex.test(value)) {
312
- return decode(value);
313
- }
314
- }
315
- const keys = Array.from(newURL.searchParams.keys()).reverse();
316
- for (const key of keys) {
317
- if (pdfRegex.test(key)) {
318
- return decode(key);
319
- }
320
- }
321
- }
322
- if (newURL.hash) {
323
- const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
324
- const hashFilename = reFilename.exec(newURL.hash);
325
- if (hashFilename) {
326
- return decode(hashFilename[0]);
327
- }
328
- }
329
- return defaultFilename;
330
- }
331
- var StatTimer = class {
332
- constructor() {
333
- __publicField(this, "started", /* @__PURE__ */ Object.create(null));
334
- __publicField(this, "times", []);
335
- }
336
- time(name) {
337
- if (name in this.started) {
338
- warn(`Timer is already running for ${name}`);
339
- }
340
- this.started[name] = Date.now();
341
- }
342
- timeEnd(name) {
343
- if (!(name in this.started)) {
344
- warn(`Timer has not been started for ${name}`);
345
- }
346
- this.times.push({
347
- name,
348
- start: this.started[name],
349
- end: Date.now()
350
- });
351
- delete this.started[name];
352
- }
353
- toString() {
354
- const outBuf = [];
355
- let longest = 0;
356
- for (const { name } of this.times) {
357
- longest = Math.max(name.length, longest);
358
- }
359
- for (const { name, start, end } of this.times) {
360
- outBuf.push(`${name.padEnd(longest)} ${end - start}ms
361
- `);
362
- }
363
- return outBuf.join("");
364
- }
365
- };
366
- function isValidFetchUrl(url, baseUrl) {
367
- if (false) {
368
- throw new Error("Not implemented: isValidFetchUrl");
369
- }
370
- const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
371
- return res?.protocol === "http:" || res?.protocol === "https:";
372
- }
373
- function noContextMenu(e) {
374
- e.preventDefault();
375
- }
376
- function stopEvent(e) {
377
- e.preventDefault();
378
- e.stopPropagation();
379
- }
380
- function deprecated(details) {
381
- console.log("Deprecated API usage: " + details);
382
- }
383
- var _regex;
384
- var PDFDateString = class {
385
- /**
386
- * Convert a PDF date string to a JavaScript `Date` object.
387
- *
388
- * The PDF date string format is described in section 7.9.4 of the official
389
- * PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth
390
- * edition) Adobe describes the same format including a trailing apostrophe.
391
- * This syntax in incorrect, but Adobe Acrobat creates PDF files that contain
392
- * them. We ignore all apostrophes as they are not necessary for date parsing.
393
- *
394
- * Moreover, Adobe Acrobat doesn't handle changing the date to universal time
395
- * and doesn't use the user's time zone (effectively ignoring the HH' and mm'
396
- * parts of the date string).
397
- *
398
- * @param {string} input
399
- * @returns {Date|null}
400
- */
401
- static toDateObject(input) {
402
- if (!input || typeof input !== "string") {
403
- return null;
404
- }
405
- __privateGet(this, _regex) || __privateSet(this, _regex, new RegExp(
406
- "^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"
407
- // Trailing apostrophe (optional)
408
- ));
409
- const matches = __privateGet(this, _regex).exec(input);
410
- if (!matches) {
411
- return null;
412
- }
413
- const year = parseInt(matches[1], 10);
414
- let month = parseInt(matches[2], 10);
415
- month = month >= 1 && month <= 12 ? month - 1 : 0;
416
- let day = parseInt(matches[3], 10);
417
- day = day >= 1 && day <= 31 ? day : 1;
418
- let hour = parseInt(matches[4], 10);
419
- hour = hour >= 0 && hour <= 23 ? hour : 0;
420
- let minute = parseInt(matches[5], 10);
421
- minute = minute >= 0 && minute <= 59 ? minute : 0;
422
- let second = parseInt(matches[6], 10);
423
- second = second >= 0 && second <= 59 ? second : 0;
424
- const universalTimeRelation = matches[7] || "Z";
425
- let offsetHour = parseInt(matches[8], 10);
426
- offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
427
- let offsetMinute = parseInt(matches[9], 10) || 0;
428
- offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
429
- if (universalTimeRelation === "-") {
430
- hour += offsetHour;
431
- minute += offsetMinute;
432
- } else if (universalTimeRelation === "+") {
433
- hour -= offsetHour;
434
- minute -= offsetMinute;
435
- }
436
- return new Date(Date.UTC(year, month, day, hour, minute, second));
437
- }
438
- };
439
- _regex = new WeakMap();
440
- __privateAdd(PDFDateString, _regex);
441
- function getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) {
442
- const { width, height } = xfaPage.attributes.style;
443
- const viewBox = [0, 0, parseInt(width), parseInt(height)];
444
- return new PageViewport({
445
- viewBox,
446
- userUnit: 1,
447
- scale,
448
- rotation
449
- });
450
- }
451
- function getRGB(color) {
452
- if (color.startsWith("#")) {
453
- const colorRGB = parseInt(color.slice(1), 16);
454
- return [
455
- (colorRGB & 16711680) >> 16,
456
- (colorRGB & 65280) >> 8,
457
- colorRGB & 255
458
- ];
459
- }
460
- if (color.startsWith("rgb(")) {
461
- return color.slice(
462
- /* "rgb(".length */
463
- 4,
464
- -1
465
- ).split(",").map((x) => parseInt(x));
466
- }
467
- if (color.startsWith("rgba(")) {
468
- return color.slice(
469
- /* "rgba(".length */
470
- 5,
471
- -1
472
- ).split(",").map((x) => parseInt(x)).slice(0, 3);
473
- }
474
- warn(`Not a valid color format: "${color}"`);
475
- return [0, 0, 0];
476
- }
477
- function getColorValues(colors) {
478
- const span = document.createElement("span");
479
- span.style.visibility = "hidden";
480
- span.style.colorScheme = "only light";
481
- document.body.append(span);
482
- for (const name of colors.keys()) {
483
- span.style.color = name;
484
- const computedColor = window.getComputedStyle(span).color;
485
- colors.set(name, getRGB(computedColor));
486
- }
487
- span.remove();
488
- }
489
- function getCurrentTransform(ctx) {
490
- const { a, b, c, d, e, f } = ctx.getTransform();
491
- return [a, b, c, d, e, f];
492
- }
493
- function getCurrentTransformInverse(ctx) {
494
- const { a, b, c, d, e, f } = ctx.getTransform().invertSelf();
495
- return [a, b, c, d, e, f];
496
- }
497
- function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
498
- if (viewport instanceof PageViewport) {
499
- const { pageWidth, pageHeight } = viewport.rawDims;
500
- const { style } = div;
501
- const useRound = FeatureTest.isCSSRoundSupported;
502
- const w = `var(--total-scale-factor) * ${pageWidth}px`, h = `var(--total-scale-factor) * ${pageHeight}px`;
503
- const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`, heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`;
504
- if (!mustFlip || viewport.rotation % 180 === 0) {
505
- style.width = widthStr;
506
- style.height = heightStr;
507
- } else {
508
- style.width = heightStr;
509
- style.height = widthStr;
510
- }
511
- }
512
- if (mustRotate) {
513
- div.setAttribute("data-main-rotation", viewport.rotation);
514
- }
515
- }
516
- var OutputScale = class _OutputScale {
517
- constructor() {
518
- const { pixelRatio } = _OutputScale;
519
- this.sx = pixelRatio;
520
- this.sy = pixelRatio;
521
- }
522
- /**
523
- * @type {boolean} Returns `true` when scaling is required, `false` otherwise.
524
- */
525
- get scaled() {
526
- return this.sx !== 1 || this.sy !== 1;
527
- }
528
- /**
529
- * @type {boolean} Returns `true` when scaling is symmetric,
530
- * `false` otherwise.
531
- */
532
- get symmetric() {
533
- return this.sx === this.sy;
534
- }
535
- /**
536
- * @returns {boolean} Returns `true` if scaling was limited,
537
- * `false` otherwise.
538
- */
539
- limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {
540
- let maxAreaScale = Infinity, maxWidthScale = Infinity, maxHeightScale = Infinity;
541
- maxPixels = _OutputScale.capPixels(maxPixels, capAreaFactor);
542
- if (maxPixels > 0) {
543
- maxAreaScale = Math.sqrt(maxPixels / (width * height));
544
- }
545
- if (maxDim !== -1) {
546
- maxWidthScale = maxDim / width;
547
- maxHeightScale = maxDim / height;
548
- }
549
- const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);
550
- if (this.sx > maxScale || this.sy > maxScale) {
551
- this.sx = maxScale;
552
- this.sy = maxScale;
553
- return true;
554
- }
555
- return false;
556
- }
557
- static get pixelRatio() {
558
- return globalThis.devicePixelRatio || 1;
559
- }
560
- static capPixels(maxPixels, capAreaFactor) {
561
- if (capAreaFactor >= 0) {
562
- const winPixels = Math.ceil(
563
- (false ? window.innerWidth * window.innerHeight : window.screen.availWidth * window.screen.availHeight) * this.pixelRatio ** 2 * (1 + capAreaFactor / 100)
564
- );
565
- return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;
566
- }
567
- return maxPixels;
568
- }
569
- };
570
- var SupportedImageMimeTypes = [
571
- "image/apng",
572
- "image/avif",
573
- "image/bmp",
574
- "image/gif",
575
- "image/jpeg",
576
- "image/png",
577
- "image/svg+xml",
578
- "image/webp",
579
- "image/x-icon"
580
- ];
581
-
582
- // src/pdf.js/src/display/canvas_factory.js
583
- var _enableHWA;
584
- var BaseCanvasFactory = class {
585
- constructor({ enableHWA = false }) {
586
- __privateAdd(this, _enableHWA, false);
587
- if (false) {
588
- unreachable("Cannot initialize BaseCanvasFactory.");
589
- }
590
- __privateSet(this, _enableHWA, enableHWA);
591
- }
592
- create(width, height) {
593
- if (width <= 0 || height <= 0) {
594
- throw new Error("Invalid canvas size");
595
- }
596
- const canvas = this._createCanvas(width, height);
597
- return {
598
- canvas,
599
- context: canvas.getContext("2d", {
600
- willReadFrequently: !__privateGet(this, _enableHWA)
601
- })
602
- };
603
- }
604
- reset(canvasAndContext, width, height) {
605
- if (!canvasAndContext.canvas) {
606
- throw new Error("Canvas is not specified");
607
- }
608
- if (width <= 0 || height <= 0) {
609
- throw new Error("Invalid canvas size");
610
- }
611
- canvasAndContext.canvas.width = width;
612
- canvasAndContext.canvas.height = height;
613
- }
614
- destroy(canvasAndContext) {
615
- if (!canvasAndContext.canvas) {
616
- throw new Error("Canvas is not specified");
617
- }
618
- canvasAndContext.canvas.width = 0;
619
- canvasAndContext.canvas.height = 0;
620
- canvasAndContext.canvas = null;
621
- canvasAndContext.context = null;
622
- }
623
- /**
624
- * @ignore
625
- */
626
- _createCanvas(width, height) {
627
- unreachable("Abstract method `_createCanvas` called.");
628
- }
629
- };
630
- _enableHWA = new WeakMap();
631
- var DOMCanvasFactory = class extends BaseCanvasFactory {
632
- constructor({ ownerDocument = globalThis.document, enableHWA = false }) {
633
- super({ enableHWA });
634
- this._document = ownerDocument;
635
- }
636
- /**
637
- * @ignore
638
- */
639
- _createCanvas(width, height) {
640
- const canvas = this._document.createElement("canvas");
641
- canvas.width = width;
642
- canvas.height = height;
643
- return canvas;
644
- }
645
- };
646
-
647
- // src/lib/utils.ts
648
- async function canvasToData(canvas) {
649
- if ("toBlob" in canvas) {
650
- const blob = await new Promise(
651
- (resolve) => canvas.toBlob((data) => resolve(data))
652
- );
653
- if (!blob) {
654
- throw new Error("Failed to generate graphics");
655
- }
656
- return new Uint8Array(await blob.arrayBuffer());
657
- }
658
- const buffer = await canvas.toBuffer("png");
659
- return new Uint8Array(buffer);
660
- }
661
- async function toDataUrl(data, type = "image/png") {
662
- if (typeof FileReader !== "undefined") {
663
- return new Promise((resolve) => {
664
- const reader = new FileReader();
665
- reader.onload = () => {
666
- resolve(reader.result);
667
- };
668
- reader.readAsDataURL(new Blob([data], { type }));
669
- });
670
- }
671
- return `data:${type};base64,${Buffer.from(data).toString("base64")}`;
672
- }
673
- function makeSerializable(object) {
674
- if (typeof object !== "object" || object === null) {
675
- return object;
676
- }
677
- if (object instanceof Int8Array || object instanceof Uint8Array || object instanceof Uint8ClampedArray || object instanceof Int16Array || object instanceof Uint16Array || object instanceof Int32Array || object instanceof Uint32Array || object instanceof Float32Array || object instanceof Float64Array) {
678
- return makeSerializable(Array.from(object));
679
- }
680
- if (object instanceof BigInt64Array || object instanceof BigUint64Array) {
681
- return makeSerializable(Array.from(object));
682
- }
683
- if (Array.isArray(object)) {
684
- return object.map(makeSerializable);
685
- }
686
- return Object.fromEntries(
687
- Object.entries(object).map(([key, value]) => [
688
- key,
689
- makeSerializable(value)
690
- ])
691
- );
692
- }
693
- function colorToRgb(color) {
694
- if (color.startsWith("#")) {
695
- const hex = color.slice(1);
696
- if (hex.length === 3) {
697
- return [
698
- Number.parseInt(hex[0] + hex[0], 16),
699
- Number.parseInt(hex[1] + hex[1], 16),
700
- Number.parseInt(hex[2] + hex[2], 16)
701
- ];
702
- }
703
- if (hex.length === 6) {
704
- return [
705
- Number.parseInt(hex.slice(0, 2), 16),
706
- Number.parseInt(hex.slice(2, 4), 16),
707
- Number.parseInt(hex.slice(4, 6), 16)
708
- ];
709
- }
710
- }
711
- throw new Error(`Invalid color format: ${color}`);
712
- }
713
- function rgbToHex(r, g, b) {
714
- const toHex = (value) => value.toString(16).padStart(2, "0");
715
- if (Array.isArray(r)) {
716
- return `#${toHex(r[0])}${toHex(r[1])}${toHex(r[2])}`;
717
- }
718
- return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
719
- }
720
- function parseRgbaColor(color) {
721
- const match = color.match(
722
- /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/
723
- );
724
- if (!match) {
725
- return { r: 0, g: 0, b: 0, a: 1 };
726
- }
727
- return {
728
- r: Number.parseInt(match[1], 10),
729
- g: Number.parseInt(match[2], 10),
730
- b: Number.parseInt(match[3], 10),
731
- a: match[4] ? Number.parseFloat(match[4]) : 1
732
- };
733
- }
734
-
735
- // src/pdf.js/src/display/filter_factory.js
736
- var BaseFilterFactory = class {
737
- constructor() {
738
- if (false) {
739
- unreachable("Cannot initialize BaseFilterFactory.");
740
- }
741
- }
742
- addFilter(maps) {
743
- return "none";
744
- }
745
- addHCMFilter(fgColor, bgColor) {
746
- return "none";
747
- }
748
- addAlphaFilter(map) {
749
- return "none";
750
- }
751
- addLuminosityFilter(map) {
752
- return "none";
753
- }
754
- addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
755
- return "none";
756
- }
757
- destroy(keepHCM = false) {
758
- }
759
- };
760
- var _baseUrl, __cache, __defs, _docId, _document, __hcmCache, _id, _DOMFilterFactory_instances, cache_get, hcmCache_get, defs_get, createTables_fn, createUrl_fn, addLuminosityConversion_fn, addGrayConversion_fn, createFilter_fn, appendFeFunc_fn, addTransferMapConversion_fn, addTransferMapAlphaConversion_fn, getRGB_fn;
761
- var DOMFilterFactory = class extends BaseFilterFactory {
762
- constructor({ docId, ownerDocument = globalThis.document }) {
763
- super();
764
- __privateAdd(this, _DOMFilterFactory_instances);
765
- __privateAdd(this, _baseUrl);
766
- __privateAdd(this, __cache);
767
- __privateAdd(this, __defs);
768
- __privateAdd(this, _docId);
769
- __privateAdd(this, _document);
770
- __privateAdd(this, __hcmCache);
771
- __privateAdd(this, _id, 0);
772
- __privateSet(this, _docId, docId);
773
- __privateSet(this, _document, ownerDocument);
774
- }
775
- addFilter(maps) {
776
- if (!maps) {
777
- return "none";
778
- }
779
- let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(maps);
780
- if (value) {
781
- return value;
782
- }
783
- const [tableR, tableG, tableB] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, maps);
784
- const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
785
- value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
786
- if (value) {
787
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(maps, value);
788
- return value;
789
- }
790
- const id = `g_${__privateGet(this, _docId)}_transfer_map_${__privateWrapper(this, _id)._++}`;
791
- const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
792
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(maps, url);
793
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
794
- const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
795
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, tableR, tableG, tableB, filter);
796
- return url;
797
- }
798
- addHCMFilter(fgColor, bgColor) {
799
- const key = `${fgColor}-${bgColor}`;
800
- const filterName = "base";
801
- let info = __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).get(filterName);
802
- if (info?.key === key) {
803
- return info.url;
804
- }
805
- if (info) {
806
- info.filter?.remove();
807
- info.key = key;
808
- info.url = "none";
809
- info.filter = null;
810
- } else {
811
- info = {
812
- key,
813
- url: "none",
814
- filter: null
815
- };
816
- __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).set(filterName, info);
817
- }
818
- if (!fgColor || !bgColor) {
819
- return info.url;
820
- }
821
- const fgRGB = __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).call(this, fgColor);
822
- fgColor = Util.makeHexColor(...fgRGB);
823
- const bgRGB = __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).call(this, bgColor);
824
- bgColor = Util.makeHexColor(...bgRGB);
825
- __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = "";
826
- if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
827
- return info.url;
828
- }
829
- const map = new Array(256);
830
- for (let i = 0; i <= 255; i++) {
831
- const x = i / 255;
832
- map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
833
- }
834
- const table = map.join(",");
835
- const id = `g_${__privateGet(this, _docId)}_hcm_filter`;
836
- const filter = info.filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
837
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, table, table, table, filter);
838
- __privateMethod(this, _DOMFilterFactory_instances, addGrayConversion_fn).call(this, filter);
839
- const getSteps = (c, n) => {
840
- const start = fgRGB[c] / 255;
841
- const end = bgRGB[c] / 255;
842
- const arr = new Array(n + 1);
843
- for (let i = 0; i <= n; i++) {
844
- arr[i] = start + i / n * (end - start);
845
- }
846
- return arr.join(",");
847
- };
848
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
849
- info.url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
850
- return info.url;
851
- }
852
- addAlphaFilter(map) {
853
- let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(map);
854
- if (value) {
855
- return value;
856
- }
857
- const [tableA] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, [map]);
858
- const key = `alpha_${tableA}`;
859
- value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
860
- if (value) {
861
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, value);
862
- return value;
863
- }
864
- const id = `g_${__privateGet(this, _docId)}_alpha_map_${__privateWrapper(this, _id)._++}`;
865
- const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
866
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, url);
867
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
868
- const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
869
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapAlphaConversion_fn).call(this, tableA, filter);
870
- return url;
871
- }
872
- addLuminosityFilter(map) {
873
- let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(map || "luminosity");
874
- if (value) {
875
- return value;
876
- }
877
- let tableA, key;
878
- if (map) {
879
- [tableA] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, [map]);
880
- key = `luminosity_${tableA}`;
881
- } else {
882
- key = "luminosity";
883
- }
884
- value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
885
- if (value) {
886
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, value);
887
- return value;
888
- }
889
- const id = `g_${__privateGet(this, _docId)}_luminosity_map_${__privateWrapper(this, _id)._++}`;
890
- const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
891
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, url);
892
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
893
- const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
894
- __privateMethod(this, _DOMFilterFactory_instances, addLuminosityConversion_fn).call(this, filter);
895
- if (map) {
896
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapAlphaConversion_fn).call(this, tableA, filter);
897
- }
898
- return url;
899
- }
900
- addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
901
- const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
902
- let info = __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).get(filterName);
903
- if (info?.key === key) {
904
- return info.url;
905
- }
906
- if (info) {
907
- info.filter?.remove();
908
- info.key = key;
909
- info.url = "none";
910
- info.filter = null;
911
- } else {
912
- info = {
913
- key,
914
- url: "none",
915
- filter: null
916
- };
917
- __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).set(filterName, info);
918
- }
919
- if (!fgColor || !bgColor) {
920
- return info.url;
921
- }
922
- const [fgRGB, bgRGB] = [fgColor, bgColor].map(__privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).bind(this));
923
- let fgGray = Math.round(
924
- 0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]
925
- );
926
- let bgGray = Math.round(
927
- 0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]
928
- );
929
- let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(
930
- __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).bind(this)
931
- );
932
- if (bgGray < fgGray) {
933
- [fgGray, bgGray, newFgRGB, newBgRGB] = [
934
- bgGray,
935
- fgGray,
936
- newBgRGB,
937
- newFgRGB
938
- ];
939
- }
940
- __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = "";
941
- const getSteps = (fg, bg, n) => {
942
- const arr = new Array(256);
943
- const step = (bgGray - fgGray) / n;
944
- const newStart = fg / 255;
945
- const newStep = (bg - fg) / (255 * n);
946
- let prev = 0;
947
- for (let i = 0; i <= n; i++) {
948
- const k = Math.round(fgGray + i * step);
949
- const value = newStart + i * newStep;
950
- for (let j = prev; j <= k; j++) {
951
- arr[j] = value;
952
- }
953
- prev = k + 1;
954
- }
955
- for (let i = prev; i < 256; i++) {
956
- arr[i] = arr[prev - 1];
957
- }
958
- return arr.join(",");
959
- };
960
- const id = `g_${__privateGet(this, _docId)}_hcm_${filterName}_filter`;
961
- const filter = info.filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
962
- __privateMethod(this, _DOMFilterFactory_instances, addGrayConversion_fn).call(this, filter);
963
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
964
- info.url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
965
- return info.url;
966
- }
967
- destroy(keepHCM = false) {
968
- if (keepHCM && __privateGet(this, __hcmCache)?.size) {
969
- return;
970
- }
971
- __privateGet(this, __defs)?.parentNode.parentNode.remove();
972
- __privateSet(this, __defs, null);
973
- __privateGet(this, __cache)?.clear();
974
- __privateSet(this, __cache, null);
975
- __privateGet(this, __hcmCache)?.clear();
976
- __privateSet(this, __hcmCache, null);
977
- __privateSet(this, _id, 0);
978
- }
979
- };
980
- _baseUrl = new WeakMap();
981
- __cache = new WeakMap();
982
- __defs = new WeakMap();
983
- _docId = new WeakMap();
984
- _document = new WeakMap();
985
- __hcmCache = new WeakMap();
986
- _id = new WeakMap();
987
- _DOMFilterFactory_instances = new WeakSet();
988
- cache_get = function() {
989
- return __privateGet(this, __cache) || __privateSet(this, __cache, /* @__PURE__ */ new Map());
990
- };
991
- hcmCache_get = function() {
992
- return __privateGet(this, __hcmCache) || __privateSet(this, __hcmCache, /* @__PURE__ */ new Map());
993
- };
994
- defs_get = function() {
995
- if (!__privateGet(this, __defs)) {
996
- const div = __privateGet(this, _document).createElement("div");
997
- const { style } = div;
998
- style.visibility = "hidden";
999
- style.contain = "strict";
1000
- style.width = style.height = 0;
1001
- style.position = "absolute";
1002
- style.top = style.left = 0;
1003
- style.zIndex = -1;
1004
- const svg = __privateGet(this, _document).createElementNS(SVG_NS, "svg");
1005
- svg.setAttribute("width", 0);
1006
- svg.setAttribute("height", 0);
1007
- __privateSet(this, __defs, __privateGet(this, _document).createElementNS(SVG_NS, "defs"));
1008
- div.append(svg);
1009
- svg.append(__privateGet(this, __defs));
1010
- __privateGet(this, _document).body.append(div);
1011
- }
1012
- return __privateGet(this, __defs);
1013
- };
1014
- createTables_fn = function(maps) {
1015
- if (maps.length === 1) {
1016
- const mapR2 = maps[0];
1017
- const buffer = new Array(256);
1018
- for (let i = 0; i < 256; i++) {
1019
- buffer[i] = mapR2[i] / 255;
1020
- }
1021
- const table = buffer.join(",");
1022
- return [table, table, table];
1023
- }
1024
- const [mapR, mapG, mapB] = maps;
1025
- const bufferR = new Array(256);
1026
- const bufferG = new Array(256);
1027
- const bufferB = new Array(256);
1028
- for (let i = 0; i < 256; i++) {
1029
- bufferR[i] = mapR[i] / 255;
1030
- bufferG[i] = mapG[i] / 255;
1031
- bufferB[i] = mapB[i] / 255;
1032
- }
1033
- return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
1034
- };
1035
- createUrl_fn = function(id) {
1036
- if (__privateGet(this, _baseUrl) === void 0) {
1037
- __privateSet(this, _baseUrl, "");
1038
- const url = __privateGet(this, _document).URL;
1039
- if (url !== __privateGet(this, _document).baseURI) {
1040
- if (isDataScheme(url)) {
1041
- warn('#createUrl: ignore "data:"-URL for performance reasons.');
1042
- } else {
1043
- __privateSet(this, _baseUrl, updateUrlHash(url, ""));
1044
- }
1045
- }
1046
- }
1047
- return `url(${__privateGet(this, _baseUrl)}#${id})`;
1048
- };
1049
- addLuminosityConversion_fn = function(filter) {
1050
- const feColorMatrix = __privateGet(this, _document).createElementNS(
1051
- SVG_NS,
1052
- "feColorMatrix"
1053
- );
1054
- feColorMatrix.setAttribute("type", "matrix");
1055
- feColorMatrix.setAttribute(
1056
- "values",
1057
- "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"
1058
- );
1059
- filter.append(feColorMatrix);
1060
- };
1061
- addGrayConversion_fn = function(filter) {
1062
- const feColorMatrix = __privateGet(this, _document).createElementNS(
1063
- SVG_NS,
1064
- "feColorMatrix"
1065
- );
1066
- feColorMatrix.setAttribute("type", "matrix");
1067
- feColorMatrix.setAttribute(
1068
- "values",
1069
- "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"
1070
- );
1071
- filter.append(feColorMatrix);
1072
- };
1073
- createFilter_fn = function(id) {
1074
- const filter = __privateGet(this, _document).createElementNS(SVG_NS, "filter");
1075
- filter.setAttribute("color-interpolation-filters", "sRGB");
1076
- filter.setAttribute("id", id);
1077
- __privateGet(this, _DOMFilterFactory_instances, defs_get).append(filter);
1078
- return filter;
1079
- };
1080
- appendFeFunc_fn = function(feComponentTransfer, func, table) {
1081
- const feFunc = __privateGet(this, _document).createElementNS(SVG_NS, func);
1082
- feFunc.setAttribute("type", "discrete");
1083
- feFunc.setAttribute("tableValues", table);
1084
- feComponentTransfer.append(feFunc);
1085
- };
1086
- addTransferMapConversion_fn = function(rTable, gTable, bTable, filter) {
1087
- const feComponentTransfer = __privateGet(this, _document).createElementNS(
1088
- SVG_NS,
1089
- "feComponentTransfer"
1090
- );
1091
- filter.append(feComponentTransfer);
1092
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncR", rTable);
1093
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncG", gTable);
1094
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncB", bTable);
1095
- };
1096
- addTransferMapAlphaConversion_fn = function(aTable, filter) {
1097
- const feComponentTransfer = __privateGet(this, _document).createElementNS(
1098
- SVG_NS,
1099
- "feComponentTransfer"
1100
- );
1101
- filter.append(feComponentTransfer);
1102
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncA", aTable);
1103
- };
1104
- getRGB_fn = function(color) {
1105
- __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = color;
1106
- return getRGB(getComputedStyle(__privateGet(this, _DOMFilterFactory_instances, defs_get)).getPropertyValue("color"));
1107
- };
1108
-
1109
- export {
1110
- SVG_NS,
1111
- PixelsPerInch,
1112
- fetchData,
1113
- PageViewport,
1114
- RenderingCancelledException,
1115
- isDataScheme,
1116
- isPdfFile,
1117
- getFilenameFromUrl,
1118
- getPdfFilenameFromUrl,
1119
- StatTimer,
1120
- isValidFetchUrl,
1121
- noContextMenu,
1122
- stopEvent,
1123
- deprecated,
1124
- PDFDateString,
1125
- getXfaPageViewport,
1126
- getRGB,
1127
- getColorValues,
1128
- getCurrentTransform,
1129
- getCurrentTransformInverse,
1130
- setLayerDimensions,
1131
- OutputScale,
1132
- SupportedImageMimeTypes,
1133
- BaseCanvasFactory,
1134
- DOMCanvasFactory,
1135
- DOMFilterFactory,
1136
- canvasToData,
1137
- toDataUrl,
1138
- makeSerializable,
1139
- colorToRgb,
1140
- rgbToHex,
1141
- parseRgbaColor
1142
- };