modern-pdf-lib 0.15.1 → 0.22.9

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.
Files changed (95) hide show
  1. package/README.md +119 -9
  2. package/dist/batchOptimize-Ba_pWw71.cjs +427 -0
  3. package/dist/batchOptimize-CxyY4fZe.mjs +392 -0
  4. package/dist/{bridge-DpzMOnHd.mjs → bridge-DTH5LMAK.mjs} +3 -3
  5. package/dist/{bridge-DN7BOHRW.cjs → bridge-DYCQzxF7.cjs} +2 -2
  6. package/dist/browser.cjs +621 -0
  7. package/dist/browser.d.cts +190 -0
  8. package/dist/browser.d.cts.map +1 -0
  9. package/dist/browser.d.mts +190 -0
  10. package/dist/browser.d.mts.map +1 -0
  11. package/dist/browser.mjs +212 -0
  12. package/dist/cli/index.cjs +40 -18
  13. package/dist/cli/index.mjs +40 -18
  14. package/dist/compressionAnalysis-B84FPXaQ.cjs +1525 -0
  15. package/dist/compressionAnalysis-BBv4BkQP.d.mts +261 -0
  16. package/dist/compressionAnalysis-BBv4BkQP.d.mts.map +1 -0
  17. package/dist/compressionAnalysis-ChkscEa1.mjs +1490 -0
  18. package/dist/compressionAnalysis-CtJ2X9l2.d.cts +261 -0
  19. package/dist/compressionAnalysis-CtJ2X9l2.d.cts.map +1 -0
  20. package/dist/create.cjs +35 -0
  21. package/dist/create.d.cts +3 -0
  22. package/dist/create.d.mts +3 -0
  23. package/dist/create.mjs +5 -0
  24. package/dist/{deduplicateImages-BfpjHY9b.mjs → deduplicateImages-CmTeo6Tx.mjs} +3 -3
  25. package/dist/{deduplicateImages-BtJ5tlrr.cjs → deduplicateImages-cKsnD6Ep.cjs} +2 -2
  26. package/dist/{fflateAdapter-D2mv_ttM.mjs → fflateAdapter-CBQpGTlx.mjs} +2 -2
  27. package/dist/{fflateAdapter-cT4YeY_h.cjs → fflateAdapter-LTAeAhaD.cjs} +1 -1
  28. package/dist/fieldAppearance-C8PoLFSc.d.mts +136 -0
  29. package/dist/fieldAppearance-C8PoLFSc.d.mts.map +1 -0
  30. package/dist/fieldAppearance-CdiGFG5e.d.cts +136 -0
  31. package/dist/fieldAppearance-CdiGFG5e.d.cts.map +1 -0
  32. package/dist/fontEmbed-Dsu9fo4U.d.mts +636 -0
  33. package/dist/fontEmbed-Dsu9fo4U.d.mts.map +1 -0
  34. package/dist/fontEmbed-LID6yG6g.d.cts +636 -0
  35. package/dist/fontEmbed-LID6yG6g.d.cts.map +1 -0
  36. package/dist/{fontSubset-BxsF9Tu5.cjs → fontSubset-5SLWMmEw.cjs} +1 -1
  37. package/dist/{fontSubset-ClyTXlhY.mjs → fontSubset-DWpduoY2.mjs} +2 -2
  38. package/dist/forms.cjs +13 -0
  39. package/dist/forms.d.cts +3 -0
  40. package/dist/forms.d.mts +3 -0
  41. package/dist/forms.mjs +3 -0
  42. package/dist/grayscaleDetect-C2m-eEXR.cjs +96 -0
  43. package/dist/grayscaleDetect-C6kFF3dk.mjs +84 -0
  44. package/dist/imageExtract-Dnk_Ssv7.mjs +155 -0
  45. package/dist/imageExtract-zEb1gnkb.cjs +166 -0
  46. package/dist/index-BtYOx5wh.d.mts +4904 -0
  47. package/dist/index-BtYOx5wh.d.mts.map +1 -0
  48. package/dist/index-bpktKzCA.d.cts +4904 -0
  49. package/dist/index-bpktKzCA.d.cts.map +1 -0
  50. package/dist/index.cjs +274 -20704
  51. package/dist/index.d.cts +7 -9151
  52. package/dist/index.d.mts +7 -9151
  53. package/dist/index.mjs +17 -20532
  54. package/dist/layout-CuAVk_Or.cjs +563 -0
  55. package/dist/layout-DgX_0jfK.mjs +438 -0
  56. package/dist/{libdeflateWasm-Cg7cWHOq.cjs → libdeflateWasm-BdiDEJOj.cjs} +2 -2
  57. package/dist/{libdeflateWasm-Cmxa-yiS.mjs → libdeflateWasm-rLppXytE.mjs} +3 -3
  58. package/dist/loader-3u6Tw5T-.mjs +328 -0
  59. package/dist/loader-I4zdkoWc.cjs +393 -0
  60. package/dist/parse.cjs +24 -0
  61. package/dist/parse.d.cts +4 -0
  62. package/dist/parse.d.mts +4 -0
  63. package/dist/parse.mjs +7 -0
  64. package/dist/{pdfCatalog-BcOL6QF-.cjs → pdfCatalog-CYy4NXEY.cjs} +2 -2
  65. package/dist/{pdfCatalog-CnJRovvm.mjs → pdfCatalog-IImGcMbR.mjs} +3 -3
  66. package/dist/pdfDocument-BFxHD_2u.mjs +13755 -0
  67. package/dist/pdfDocument-BSiQdNZq.d.cts +4640 -0
  68. package/dist/pdfDocument-BSiQdNZq.d.cts.map +1 -0
  69. package/dist/pdfDocument-i6U5fQ91.d.mts +4640 -0
  70. package/dist/pdfDocument-i6U5fQ91.d.mts.map +1 -0
  71. package/dist/pdfDocument-pmRXryVI.cjs +14180 -0
  72. package/dist/pdfForm-9gd40uz9.cjs +1796 -0
  73. package/dist/pdfForm-BiyNtYem.d.mts +905 -0
  74. package/dist/pdfForm-BiyNtYem.d.mts.map +1 -0
  75. package/dist/pdfForm-Cn-cVicP.mjs +1695 -0
  76. package/dist/pdfForm-SOXJ72LW.d.cts +905 -0
  77. package/dist/pdfForm-SOXJ72LW.d.cts.map +1 -0
  78. package/dist/{pdfObjects-BrU4Xd0V.cjs → pdfObjects-1veop1_d.cjs} +2 -2
  79. package/dist/{pdfObjects-DZZ2GPRW.mjs → pdfObjects-uEsWlfzU.mjs} +2 -2
  80. package/dist/{pdfPage-Dm5XC_g_.mjs → pdfPage-Cd8e7flb.mjs} +3024 -5
  81. package/dist/{pdfPage-Dz_SVKUS.cjs → pdfPage-Cd8jOJp6.cjs} +3046 -3
  82. package/dist/{pngEmbed-I1hU3Y6m.mjs → pngEmbed-BLj2zi-5.mjs} +3 -3
  83. package/dist/{pngEmbed-C6M1eX6b.cjs → pngEmbed-D4X4ZN-3.cjs} +2 -2
  84. package/dist/src-6L07EQsi.cjs +11852 -0
  85. package/dist/src-Dm4aaZ8q.mjs +11103 -0
  86. package/dist/{imageExtract-vjyQyFcT.mjs → streamDecode-Bj568Nc9.mjs} +1646 -188
  87. package/dist/{imageExtract-BC7TMY98.cjs → streamDecode-CvgErkFu.cjs} +1645 -199
  88. package/package.json +33 -1
  89. package/dist/batchOptimize-ClXizv19.mjs +0 -306
  90. package/dist/batchOptimize-DYQOX1-7.cjs +0 -329
  91. package/dist/index.d.cts.map +0 -1
  92. package/dist/index.d.mts.map +0 -1
  93. package/dist/loader-B6VIrZOJ.mjs +0 -164
  94. package/dist/loader-DdB5Xo5D.cjs +0 -166
  95. package/dist/rolldown-runtime-95iHPtFO.mjs +0 -18
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "modern-pdf-lib",
3
- "version": "0.15.1",
3
+ "version": "0.22.9",
4
4
  "description": "A modern, WASM-accelerated PDF creation engine for every JavaScript runtime",
5
5
  "type": "module",
6
6
  "exports": {
@@ -12,6 +12,34 @@
12
12
  "default": "./dist/index.cjs"
13
13
  }
14
14
  },
15
+ "./browser": {
16
+ "types": "./dist/browser.d.mts",
17
+ "import": "./dist/browser.mjs"
18
+ },
19
+ "./create": {
20
+ "types": "./dist/create.d.mts",
21
+ "import": "./dist/create.mjs",
22
+ "require": {
23
+ "types": "./dist/create.d.cts",
24
+ "default": "./dist/create.cjs"
25
+ }
26
+ },
27
+ "./parse": {
28
+ "types": "./dist/parse.d.mts",
29
+ "import": "./dist/parse.mjs",
30
+ "require": {
31
+ "types": "./dist/parse.d.cts",
32
+ "default": "./dist/parse.cjs"
33
+ }
34
+ },
35
+ "./forms": {
36
+ "types": "./dist/forms.d.mts",
37
+ "import": "./dist/forms.mjs",
38
+ "require": {
39
+ "types": "./dist/forms.d.cts",
40
+ "default": "./dist/forms.cjs"
41
+ }
42
+ },
15
43
  "./wasm/*": "./dist/wasm/*"
16
44
  },
17
45
  "bin": {
@@ -19,6 +47,8 @@
19
47
  },
20
48
  "main": "./dist/index.cjs",
21
49
  "module": "./dist/index.mjs",
50
+ "unpkg": "./dist/browser.mjs",
51
+ "jsdelivr": "./dist/browser.mjs",
22
52
  "types": "./dist/index.d.mts",
23
53
  "files": [
24
54
  "dist/**/*.mjs",
@@ -27,6 +57,7 @@
27
57
  "dist/**/*.d.cts",
28
58
  "dist/**/*.d.mts.map",
29
59
  "dist/**/*.d.cts.map",
60
+ "dist/modern-pdf-lib.iife.js",
30
61
  "LICENSE",
31
62
  "README.md"
32
63
  ],
@@ -36,6 +67,7 @@
36
67
  "sideEffects": false,
37
68
  "scripts": {
38
69
  "build": "tsdown",
70
+ "build:iife": "tsx scripts/build-iife.ts",
39
71
  "build:wasm": "bash scripts/build-wasm.sh",
40
72
  "build:all": "npm run build:wasm && npm run build",
41
73
  "dev": "vite",
@@ -1,306 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-95iHPtFO.mjs";
2
- import { i as PdfName } from "./pdfObjects-DZZ2GPRW.mjs";
3
- import { n as extractImages, t as decodeImageStream } from "./imageExtract-vjyQyFcT.mjs";
4
-
5
- //#region src/assets/image/grayscaleDetect.ts
6
- /**
7
- * @module assets/image/grayscaleDetect
8
- *
9
- * Grayscale detection and conversion for image optimization.
10
- *
11
- * Detects RGB images where all pixels are effectively grayscale
12
- * (R ≈ G ≈ B) and converts them to single-channel grayscale,
13
- * reducing data size by ~66%.
14
- *
15
- * No Buffer — uses Uint8Array exclusively.
16
- */
17
- /**
18
- * Check whether an RGB/RGBA image is effectively grayscale.
19
- *
20
- * Scans all pixels and checks if R, G, and B channels are within
21
- * `tolerance` of each other. If ≥99% of pixels pass, the image
22
- * is considered grayscale.
23
- *
24
- * @param pixels - Raw pixel data (row-major, channel-interleaved).
25
- * @param width - Image width in pixels.
26
- * @param height - Image height in pixels.
27
- * @param channels - Number of channels: 3 (RGB) or 4 (RGBA).
28
- * @param tolerance - Maximum allowed difference between R, G, and B
29
- * values for a pixel to be considered gray.
30
- * Default: `2`.
31
- * @returns `true` if the image is effectively grayscale.
32
- *
33
- * @example
34
- * ```ts
35
- * import { isGrayscaleImage, convertToGrayscale } from 'modern-pdf-lib';
36
- *
37
- * if (isGrayscaleImage(pixels, width, height, 3)) {
38
- * const grayPixels = convertToGrayscale(pixels, width, height, 3);
39
- * // grayPixels has 1 byte per pixel instead of 3
40
- * }
41
- * ```
42
- */
43
- function isGrayscaleImage(pixels, width, height, channels, tolerance = 2) {
44
- const pixelCount = width * height;
45
- const maxNonGray = Math.floor(pixelCount * .01);
46
- let nonGrayCount = 0;
47
- for (let i = 0; i < pixelCount; i++) {
48
- const r = pixels[i * channels];
49
- const g = pixels[i * channels + 1];
50
- const b = pixels[i * channels + 2];
51
- if (Math.max(r, g, b) - Math.min(r, g, b) > tolerance) {
52
- nonGrayCount++;
53
- if (nonGrayCount > maxNonGray) return false;
54
- }
55
- }
56
- return true;
57
- }
58
- /**
59
- * Convert an RGB/RGBA image to single-channel grayscale.
60
- *
61
- * Uses the ITU-R BT.601 luma formula:
62
- * ```
63
- * gray = 0.299 × R + 0.587 × G + 0.114 × B
64
- * ```
65
- *
66
- * The alpha channel (if present) is discarded.
67
- *
68
- * @param pixels - Raw pixel data (row-major, channel-interleaved).
69
- * @param width - Image width in pixels.
70
- * @param height - Image height in pixels.
71
- * @param channels - Number of channels: 3 (RGB) or 4 (RGBA).
72
- * @returns Grayscale pixel data (1 byte per pixel).
73
- */
74
- function convertToGrayscale(pixels, width, height, channels) {
75
- const pixelCount = width * height;
76
- const gray = new Uint8Array(pixelCount);
77
- for (let i = 0; i < pixelCount; i++) {
78
- const r = pixels[i * channels];
79
- const g = pixels[i * channels + 1];
80
- const b = pixels[i * channels + 2];
81
- gray[i] = Math.round(.299 * r + .587 * g + .114 * b);
82
- }
83
- return gray;
84
- }
85
-
86
- //#endregion
87
- //#region src/assets/image/batchOptimize.ts
88
- var batchOptimize_exports = /* @__PURE__ */ __exportAll({ optimizeAllImages: () => optimizeAllImages });
89
- /** Minimum image size to bother optimizing (10 KB). */
90
- const SMALL_IMAGE_THRESHOLD = 10240;
91
- /**
92
- * Optimize all images in a PDF document by recompressing them as JPEG.
93
- *
94
- * Walks every image XObject in the document, decodes its pixel data,
95
- * recompresses it as JPEG using the WASM encoder (if available), and
96
- * replaces the stream data in-place when the result is smaller.
97
- *
98
- * **Requires the JPEG WASM module to be initialized** via
99
- * `initJpegWasm()` or `initWasm({ jpeg: true })`. Without it,
100
- * no images will be optimized (all will be skipped).
101
- *
102
- * @param doc - A parsed `PdfDocument` (from `loadPdf()`).
103
- * @param options - Optimization settings.
104
- * @returns A report summarizing the optimization results.
105
- *
106
- * @example
107
- * ```ts
108
- * import { loadPdf, initWasm, optimizeAllImages } from 'modern-pdf-lib';
109
- *
110
- * await initWasm({ jpeg: true });
111
- *
112
- * const doc = await loadPdf(pdfBytes);
113
- * const report = await optimizeAllImages(doc);
114
- *
115
- * console.log(`Optimized ${report.optimizedImages} of ${report.totalImages} images`);
116
- * console.log(`Savings: ${report.savings.toFixed(1)}%`);
117
- *
118
- * const optimizedBytes = await doc.save();
119
- * ```
120
- */
121
- async function optimizeAllImages(doc, options = {}) {
122
- const quality = options.quality ?? 80;
123
- const minSavingsPercent = options.minSavingsPercent ?? 10;
124
- const skipSmall = options.skipSmallImages ?? false;
125
- const progressive = options.progressive ?? false;
126
- const chromaSubsampling = options.chromaSubsampling ?? "4:2:0";
127
- const { encodeJpegWasm, isJpegWasmReady } = await import("./bridge-DpzMOnHd.mjs").then((n) => n.t);
128
- const { decodeJpegWasm } = await import("./bridge-DpzMOnHd.mjs").then((n) => n.t);
129
- const images = extractImages(doc);
130
- const perImage = [];
131
- let totalOriginal = 0;
132
- let totalNew = 0;
133
- let optimizedCount = 0;
134
- for (const img of images) {
135
- totalOriginal += img.compressedSize;
136
- if (!isJpegWasmReady()) {
137
- perImage.push({
138
- name: img.name,
139
- pageIndex: img.pageIndex,
140
- originalSize: img.compressedSize,
141
- newSize: img.compressedSize,
142
- skipped: true,
143
- reason: "JPEG WASM encoder not initialized"
144
- });
145
- totalNew += img.compressedSize;
146
- continue;
147
- }
148
- if (skipSmall && img.compressedSize < SMALL_IMAGE_THRESHOLD) {
149
- perImage.push({
150
- name: img.name,
151
- pageIndex: img.pageIndex,
152
- originalSize: img.compressedSize,
153
- newSize: img.compressedSize,
154
- skipped: true,
155
- reason: `Below size threshold (${SMALL_IMAGE_THRESHOLD} bytes)`
156
- });
157
- totalNew += img.compressedSize;
158
- continue;
159
- }
160
- if (img.bitsPerComponent !== 8) {
161
- perImage.push({
162
- name: img.name,
163
- pageIndex: img.pageIndex,
164
- originalSize: img.compressedSize,
165
- newSize: img.compressedSize,
166
- skipped: true,
167
- reason: `Unsupported bits per component: ${img.bitsPerComponent}`
168
- });
169
- totalNew += img.compressedSize;
170
- continue;
171
- }
172
- if (img.colorSpace === "Indexed") {
173
- perImage.push({
174
- name: img.name,
175
- pageIndex: img.pageIndex,
176
- originalSize: img.compressedSize,
177
- newSize: img.compressedSize,
178
- skipped: true,
179
- reason: "Indexed color space not suitable for JPEG"
180
- });
181
- totalNew += img.compressedSize;
182
- continue;
183
- }
184
- let pixels;
185
- let channels = img.channels;
186
- try {
187
- if (img.filters[0] === "DCTDecode") {
188
- const decoded = decodeJpegWasm(img.stream.data);
189
- if (!decoded) {
190
- perImage.push({
191
- name: img.name,
192
- pageIndex: img.pageIndex,
193
- originalSize: img.compressedSize,
194
- newSize: img.compressedSize,
195
- skipped: true,
196
- reason: "Failed to decode existing JPEG"
197
- });
198
- totalNew += img.compressedSize;
199
- continue;
200
- }
201
- pixels = decoded.pixels;
202
- channels = decoded.channels;
203
- } else pixels = decodeImageStream(img);
204
- } catch {
205
- perImage.push({
206
- name: img.name,
207
- pageIndex: img.pageIndex,
208
- originalSize: img.compressedSize,
209
- newSize: img.compressedSize,
210
- skipped: true,
211
- reason: "Failed to decode image stream"
212
- });
213
- totalNew += img.compressedSize;
214
- continue;
215
- }
216
- const expectedLen = img.width * img.height * channels;
217
- if (pixels.length !== expectedLen) {
218
- perImage.push({
219
- name: img.name,
220
- pageIndex: img.pageIndex,
221
- originalSize: img.compressedSize,
222
- newSize: img.compressedSize,
223
- skipped: true,
224
- reason: `Pixel data length mismatch: got ${pixels.length}, expected ${expectedLen}`
225
- });
226
- totalNew += img.compressedSize;
227
- continue;
228
- }
229
- if (channels === 4 && img.colorSpace === "DeviceCMYK") {
230
- const rgb = new Uint8Array(img.width * img.height * 3);
231
- for (let i = 0; i < img.width * img.height; i++) {
232
- const c = pixels[i * 4] / 255;
233
- const m = pixels[i * 4 + 1] / 255;
234
- const y = pixels[i * 4 + 2] / 255;
235
- const k = pixels[i * 4 + 3] / 255;
236
- rgb[i * 3] = Math.round(255 * (1 - c) * (1 - k));
237
- rgb[i * 3 + 1] = Math.round(255 * (1 - m) * (1 - k));
238
- rgb[i * 3 + 2] = Math.round(255 * (1 - y) * (1 - k));
239
- }
240
- pixels = rgb;
241
- channels = 3;
242
- }
243
- if (options.autoGrayscale && (channels === 3 || channels === 4)) {
244
- if (isGrayscaleImage(pixels, img.width, img.height, channels)) {
245
- pixels = convertToGrayscale(pixels, img.width, img.height, channels);
246
- channels = 1;
247
- }
248
- }
249
- const jpegBytes = encodeJpegWasm(pixels, img.width, img.height, channels, quality, progressive, chromaSubsampling);
250
- if (!jpegBytes) {
251
- perImage.push({
252
- name: img.name,
253
- pageIndex: img.pageIndex,
254
- originalSize: img.compressedSize,
255
- newSize: img.compressedSize,
256
- skipped: true,
257
- reason: "JPEG encoding failed"
258
- });
259
- totalNew += img.compressedSize;
260
- continue;
261
- }
262
- const savingsPercent = (img.compressedSize - jpegBytes.length) / img.compressedSize * 100;
263
- if (savingsPercent < minSavingsPercent) {
264
- perImage.push({
265
- name: img.name,
266
- pageIndex: img.pageIndex,
267
- originalSize: img.compressedSize,
268
- newSize: img.compressedSize,
269
- skipped: true,
270
- reason: `Savings ${savingsPercent.toFixed(1)}% below threshold ${minSavingsPercent}%`
271
- });
272
- totalNew += img.compressedSize;
273
- continue;
274
- }
275
- img.stream.data = jpegBytes;
276
- img.stream.syncLength();
277
- const dict = img.stream.dict;
278
- dict.set("/Filter", PdfName.of("/DCTDecode"));
279
- if (img.colorSpace === "DeviceCMYK" && channels === 3) dict.set("/ColorSpace", PdfName.of("/DeviceRGB"));
280
- if (channels === 1) dict.set("/ColorSpace", PdfName.of("/DeviceGray"));
281
- dict.delete("/DecodeParms");
282
- if (img.colorSpace === "DeviceCMYK") dict.delete("/Decode");
283
- optimizedCount++;
284
- perImage.push({
285
- name: img.name,
286
- pageIndex: img.pageIndex,
287
- originalSize: img.compressedSize,
288
- newSize: jpegBytes.length,
289
- skipped: false
290
- });
291
- totalNew += jpegBytes.length;
292
- }
293
- const overallSavings = totalOriginal > 0 ? (totalOriginal - totalNew) / totalOriginal * 100 : 0;
294
- return {
295
- totalImages: images.length,
296
- optimizedImages: optimizedCount,
297
- originalTotalBytes: totalOriginal,
298
- optimizedTotalBytes: totalNew,
299
- savings: overallSavings,
300
- perImage
301
- };
302
- }
303
-
304
- //#endregion
305
- export { isGrayscaleImage as i, optimizeAllImages as n, convertToGrayscale as r, batchOptimize_exports as t };
306
- //# sourceMappingURL=batchOptimize-ClXizv19.mjs.map
@@ -1,329 +0,0 @@
1
- const require_rolldown_runtime = require('./rolldown-runtime-CKhH4XqG.cjs');
2
- const require_pdfObjects = require('./pdfObjects-BrU4Xd0V.cjs');
3
- const require_imageExtract = require('./imageExtract-BC7TMY98.cjs');
4
-
5
- //#region src/assets/image/grayscaleDetect.ts
6
- /**
7
- * @module assets/image/grayscaleDetect
8
- *
9
- * Grayscale detection and conversion for image optimization.
10
- *
11
- * Detects RGB images where all pixels are effectively grayscale
12
- * (R ≈ G ≈ B) and converts them to single-channel grayscale,
13
- * reducing data size by ~66%.
14
- *
15
- * No Buffer — uses Uint8Array exclusively.
16
- */
17
- /**
18
- * Check whether an RGB/RGBA image is effectively grayscale.
19
- *
20
- * Scans all pixels and checks if R, G, and B channels are within
21
- * `tolerance` of each other. If ≥99% of pixels pass, the image
22
- * is considered grayscale.
23
- *
24
- * @param pixels - Raw pixel data (row-major, channel-interleaved).
25
- * @param width - Image width in pixels.
26
- * @param height - Image height in pixels.
27
- * @param channels - Number of channels: 3 (RGB) or 4 (RGBA).
28
- * @param tolerance - Maximum allowed difference between R, G, and B
29
- * values for a pixel to be considered gray.
30
- * Default: `2`.
31
- * @returns `true` if the image is effectively grayscale.
32
- *
33
- * @example
34
- * ```ts
35
- * import { isGrayscaleImage, convertToGrayscale } from 'modern-pdf-lib';
36
- *
37
- * if (isGrayscaleImage(pixels, width, height, 3)) {
38
- * const grayPixels = convertToGrayscale(pixels, width, height, 3);
39
- * // grayPixels has 1 byte per pixel instead of 3
40
- * }
41
- * ```
42
- */
43
- function isGrayscaleImage(pixels, width, height, channels, tolerance = 2) {
44
- const pixelCount = width * height;
45
- const maxNonGray = Math.floor(pixelCount * .01);
46
- let nonGrayCount = 0;
47
- for (let i = 0; i < pixelCount; i++) {
48
- const r = pixels[i * channels];
49
- const g = pixels[i * channels + 1];
50
- const b = pixels[i * channels + 2];
51
- if (Math.max(r, g, b) - Math.min(r, g, b) > tolerance) {
52
- nonGrayCount++;
53
- if (nonGrayCount > maxNonGray) return false;
54
- }
55
- }
56
- return true;
57
- }
58
- /**
59
- * Convert an RGB/RGBA image to single-channel grayscale.
60
- *
61
- * Uses the ITU-R BT.601 luma formula:
62
- * ```
63
- * gray = 0.299 × R + 0.587 × G + 0.114 × B
64
- * ```
65
- *
66
- * The alpha channel (if present) is discarded.
67
- *
68
- * @param pixels - Raw pixel data (row-major, channel-interleaved).
69
- * @param width - Image width in pixels.
70
- * @param height - Image height in pixels.
71
- * @param channels - Number of channels: 3 (RGB) or 4 (RGBA).
72
- * @returns Grayscale pixel data (1 byte per pixel).
73
- */
74
- function convertToGrayscale(pixels, width, height, channels) {
75
- const pixelCount = width * height;
76
- const gray = new Uint8Array(pixelCount);
77
- for (let i = 0; i < pixelCount; i++) {
78
- const r = pixels[i * channels];
79
- const g = pixels[i * channels + 1];
80
- const b = pixels[i * channels + 2];
81
- gray[i] = Math.round(.299 * r + .587 * g + .114 * b);
82
- }
83
- return gray;
84
- }
85
-
86
- //#endregion
87
- //#region src/assets/image/batchOptimize.ts
88
- var batchOptimize_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ optimizeAllImages: () => optimizeAllImages });
89
- /** Minimum image size to bother optimizing (10 KB). */
90
- const SMALL_IMAGE_THRESHOLD = 10240;
91
- /**
92
- * Optimize all images in a PDF document by recompressing them as JPEG.
93
- *
94
- * Walks every image XObject in the document, decodes its pixel data,
95
- * recompresses it as JPEG using the WASM encoder (if available), and
96
- * replaces the stream data in-place when the result is smaller.
97
- *
98
- * **Requires the JPEG WASM module to be initialized** via
99
- * `initJpegWasm()` or `initWasm({ jpeg: true })`. Without it,
100
- * no images will be optimized (all will be skipped).
101
- *
102
- * @param doc - A parsed `PdfDocument` (from `loadPdf()`).
103
- * @param options - Optimization settings.
104
- * @returns A report summarizing the optimization results.
105
- *
106
- * @example
107
- * ```ts
108
- * import { loadPdf, initWasm, optimizeAllImages } from 'modern-pdf-lib';
109
- *
110
- * await initWasm({ jpeg: true });
111
- *
112
- * const doc = await loadPdf(pdfBytes);
113
- * const report = await optimizeAllImages(doc);
114
- *
115
- * console.log(`Optimized ${report.optimizedImages} of ${report.totalImages} images`);
116
- * console.log(`Savings: ${report.savings.toFixed(1)}%`);
117
- *
118
- * const optimizedBytes = await doc.save();
119
- * ```
120
- */
121
- async function optimizeAllImages(doc, options = {}) {
122
- const quality = options.quality ?? 80;
123
- const minSavingsPercent = options.minSavingsPercent ?? 10;
124
- const skipSmall = options.skipSmallImages ?? false;
125
- const progressive = options.progressive ?? false;
126
- const chromaSubsampling = options.chromaSubsampling ?? "4:2:0";
127
- const { encodeJpegWasm, isJpegWasmReady } = await Promise.resolve().then(() => require("./bridge-DN7BOHRW.cjs")).then((n) => n.bridge_exports);
128
- const { decodeJpegWasm } = await Promise.resolve().then(() => require("./bridge-DN7BOHRW.cjs")).then((n) => n.bridge_exports);
129
- const images = require_imageExtract.extractImages(doc);
130
- const perImage = [];
131
- let totalOriginal = 0;
132
- let totalNew = 0;
133
- let optimizedCount = 0;
134
- for (const img of images) {
135
- totalOriginal += img.compressedSize;
136
- if (!isJpegWasmReady()) {
137
- perImage.push({
138
- name: img.name,
139
- pageIndex: img.pageIndex,
140
- originalSize: img.compressedSize,
141
- newSize: img.compressedSize,
142
- skipped: true,
143
- reason: "JPEG WASM encoder not initialized"
144
- });
145
- totalNew += img.compressedSize;
146
- continue;
147
- }
148
- if (skipSmall && img.compressedSize < SMALL_IMAGE_THRESHOLD) {
149
- perImage.push({
150
- name: img.name,
151
- pageIndex: img.pageIndex,
152
- originalSize: img.compressedSize,
153
- newSize: img.compressedSize,
154
- skipped: true,
155
- reason: `Below size threshold (${SMALL_IMAGE_THRESHOLD} bytes)`
156
- });
157
- totalNew += img.compressedSize;
158
- continue;
159
- }
160
- if (img.bitsPerComponent !== 8) {
161
- perImage.push({
162
- name: img.name,
163
- pageIndex: img.pageIndex,
164
- originalSize: img.compressedSize,
165
- newSize: img.compressedSize,
166
- skipped: true,
167
- reason: `Unsupported bits per component: ${img.bitsPerComponent}`
168
- });
169
- totalNew += img.compressedSize;
170
- continue;
171
- }
172
- if (img.colorSpace === "Indexed") {
173
- perImage.push({
174
- name: img.name,
175
- pageIndex: img.pageIndex,
176
- originalSize: img.compressedSize,
177
- newSize: img.compressedSize,
178
- skipped: true,
179
- reason: "Indexed color space not suitable for JPEG"
180
- });
181
- totalNew += img.compressedSize;
182
- continue;
183
- }
184
- let pixels;
185
- let channels = img.channels;
186
- try {
187
- if (img.filters[0] === "DCTDecode") {
188
- const decoded = decodeJpegWasm(img.stream.data);
189
- if (!decoded) {
190
- perImage.push({
191
- name: img.name,
192
- pageIndex: img.pageIndex,
193
- originalSize: img.compressedSize,
194
- newSize: img.compressedSize,
195
- skipped: true,
196
- reason: "Failed to decode existing JPEG"
197
- });
198
- totalNew += img.compressedSize;
199
- continue;
200
- }
201
- pixels = decoded.pixels;
202
- channels = decoded.channels;
203
- } else pixels = require_imageExtract.decodeImageStream(img);
204
- } catch {
205
- perImage.push({
206
- name: img.name,
207
- pageIndex: img.pageIndex,
208
- originalSize: img.compressedSize,
209
- newSize: img.compressedSize,
210
- skipped: true,
211
- reason: "Failed to decode image stream"
212
- });
213
- totalNew += img.compressedSize;
214
- continue;
215
- }
216
- const expectedLen = img.width * img.height * channels;
217
- if (pixels.length !== expectedLen) {
218
- perImage.push({
219
- name: img.name,
220
- pageIndex: img.pageIndex,
221
- originalSize: img.compressedSize,
222
- newSize: img.compressedSize,
223
- skipped: true,
224
- reason: `Pixel data length mismatch: got ${pixels.length}, expected ${expectedLen}`
225
- });
226
- totalNew += img.compressedSize;
227
- continue;
228
- }
229
- if (channels === 4 && img.colorSpace === "DeviceCMYK") {
230
- const rgb = new Uint8Array(img.width * img.height * 3);
231
- for (let i = 0; i < img.width * img.height; i++) {
232
- const c = pixels[i * 4] / 255;
233
- const m = pixels[i * 4 + 1] / 255;
234
- const y = pixels[i * 4 + 2] / 255;
235
- const k = pixels[i * 4 + 3] / 255;
236
- rgb[i * 3] = Math.round(255 * (1 - c) * (1 - k));
237
- rgb[i * 3 + 1] = Math.round(255 * (1 - m) * (1 - k));
238
- rgb[i * 3 + 2] = Math.round(255 * (1 - y) * (1 - k));
239
- }
240
- pixels = rgb;
241
- channels = 3;
242
- }
243
- if (options.autoGrayscale && (channels === 3 || channels === 4)) {
244
- if (isGrayscaleImage(pixels, img.width, img.height, channels)) {
245
- pixels = convertToGrayscale(pixels, img.width, img.height, channels);
246
- channels = 1;
247
- }
248
- }
249
- const jpegBytes = encodeJpegWasm(pixels, img.width, img.height, channels, quality, progressive, chromaSubsampling);
250
- if (!jpegBytes) {
251
- perImage.push({
252
- name: img.name,
253
- pageIndex: img.pageIndex,
254
- originalSize: img.compressedSize,
255
- newSize: img.compressedSize,
256
- skipped: true,
257
- reason: "JPEG encoding failed"
258
- });
259
- totalNew += img.compressedSize;
260
- continue;
261
- }
262
- const savingsPercent = (img.compressedSize - jpegBytes.length) / img.compressedSize * 100;
263
- if (savingsPercent < minSavingsPercent) {
264
- perImage.push({
265
- name: img.name,
266
- pageIndex: img.pageIndex,
267
- originalSize: img.compressedSize,
268
- newSize: img.compressedSize,
269
- skipped: true,
270
- reason: `Savings ${savingsPercent.toFixed(1)}% below threshold ${minSavingsPercent}%`
271
- });
272
- totalNew += img.compressedSize;
273
- continue;
274
- }
275
- img.stream.data = jpegBytes;
276
- img.stream.syncLength();
277
- const dict = img.stream.dict;
278
- dict.set("/Filter", require_pdfObjects.PdfName.of("/DCTDecode"));
279
- if (img.colorSpace === "DeviceCMYK" && channels === 3) dict.set("/ColorSpace", require_pdfObjects.PdfName.of("/DeviceRGB"));
280
- if (channels === 1) dict.set("/ColorSpace", require_pdfObjects.PdfName.of("/DeviceGray"));
281
- dict.delete("/DecodeParms");
282
- if (img.colorSpace === "DeviceCMYK") dict.delete("/Decode");
283
- optimizedCount++;
284
- perImage.push({
285
- name: img.name,
286
- pageIndex: img.pageIndex,
287
- originalSize: img.compressedSize,
288
- newSize: jpegBytes.length,
289
- skipped: false
290
- });
291
- totalNew += jpegBytes.length;
292
- }
293
- const overallSavings = totalOriginal > 0 ? (totalOriginal - totalNew) / totalOriginal * 100 : 0;
294
- return {
295
- totalImages: images.length,
296
- optimizedImages: optimizedCount,
297
- originalTotalBytes: totalOriginal,
298
- optimizedTotalBytes: totalNew,
299
- savings: overallSavings,
300
- perImage
301
- };
302
- }
303
-
304
- //#endregion
305
- Object.defineProperty(exports, 'batchOptimize_exports', {
306
- enumerable: true,
307
- get: function () {
308
- return batchOptimize_exports;
309
- }
310
- });
311
- Object.defineProperty(exports, 'convertToGrayscale', {
312
- enumerable: true,
313
- get: function () {
314
- return convertToGrayscale;
315
- }
316
- });
317
- Object.defineProperty(exports, 'isGrayscaleImage', {
318
- enumerable: true,
319
- get: function () {
320
- return isGrayscaleImage;
321
- }
322
- });
323
- Object.defineProperty(exports, 'optimizeAllImages', {
324
- enumerable: true,
325
- get: function () {
326
- return optimizeAllImages;
327
- }
328
- });
329
- //# sourceMappingURL=batchOptimize-DYQOX1-7.cjs.map