Repository navigation
Expand file tree
/
Copy pathCompressController.java
More file actions
1428 lines (1238 loc) · 58.9 KB
/
Copy pathCompressController.java
File metadata and controls
1428 lines (1238 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package stirling.software.SPDF.controller.api.misc;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.model.api.misc.OptimizePdfRequest;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.MiscApi;
import stirling.software.common.enumeration.ResourceWeight;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.LineArtConversionService;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@MiscApi
@Slf4j
@RequiredArgsConstructor
public class CompressController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final EndpointConfiguration endpointConfiguration;
private final TempFileManager tempFileManager;
@Autowired(required = false)
private LineArtConversionService lineArtConversionService;
private boolean isQpdfEnabled() {
return endpointConfiguration.isGroupEnabled("qpdf");
}
private boolean isGhostscriptEnabled() {
return endpointConfiguration.isGroupEnabled("Ghostscript");
}
private boolean isImageMagickEnabled() {
return endpointConfiguration.isGroupEnabled("ImageMagick");
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class ImageReference {
int pageNum; // Page number where the image appears
COSName name; // The name used to reference this image
}
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
private static class NestedImageReference extends ImageReference {
COSName formName; // Name of the form XObject containing the image
COSName imageName; // Name of the image within the form
}
// Tracks compression stats for reporting
private static class CompressionStats {
int totalImages = 0;
int nestedImages = 0;
int uniqueImagesCount = 0;
int compressedImages = 0;
int skippedImages = 0;
long totalOriginalBytes = 0;
long totalCompressedBytes = 0;
}
private static void replaceImages(
PDDocument doc,
Map<ImageIdentity, List<ImageReference>> uniqueImages,
Map<ImageIdentity, PDImageXObject> compressedVersions)
throws IOException {
for (Entry<ImageIdentity, List<ImageReference>> entry : uniqueImages.entrySet()) {
ImageIdentity imageIdentity = entry.getKey();
List<ImageReference> references = entry.getValue();
PDImageXObject compressedImage = compressedVersions.get(imageIdentity);
if (compressedImage == null) continue;
for (ImageReference ref : references) {
replaceImageReference(doc, ref, compressedImage);
}
}
}
// Find all images in the document, both direct and nested within forms
private static Map<ImageIdentity, List<ImageReference>> findImages(PDDocument doc)
throws IOException {
Map<ImageIdentity, List<ImageReference>> uniqueImages = new HashMap<>();
// Scan through all pages in the document
for (int pageNum = 0; pageNum < doc.getNumberOfPages(); pageNum++) {
PDPage page = doc.getPage(pageNum);
PDResources res = page.getResources();
if (res == null || res.getXObjectNames() == null) continue;
// Process all XObjects on the page
for (COSName name : res.getXObjectNames()) {
PDXObject xobj = res.getXObject(name);
// Direct image
if (isImage(xobj)) {
addDirectImage(pageNum, name, (PDImageXObject) xobj, uniqueImages);
log.info(
"Found direct image '{}' on page {} - {}x{}",
name.getName(),
pageNum + 1,
((PDImage) xobj).getWidth(),
((PDImage) xobj).getHeight());
}
// Form XObject that may contain nested images
else if (isForm(xobj)) {
checkFormForImages(pageNum, name, (PDFormXObject) xobj, uniqueImages);
}
}
}
return uniqueImages;
}
private static ImageReference addDirectImage(
int pageNum,
COSName name,
PDImageXObject image,
Map<ImageIdentity, List<ImageReference>> uniqueImages)
throws IOException {
ImageReference ref = new ImageReference();
ref.pageNum = pageNum;
ref.name = name;
ImageIdentity identity = new ImageIdentity(image);
uniqueImages.computeIfAbsent(identity, k -> new ArrayList<>()).add(ref);
return ref;
}
// Look for images inside form XObjects
private static void checkFormForImages(
int pageNum,
COSName formName,
PDFormXObject formXObj,
Map<ImageIdentity, List<ImageReference>> uniqueImages)
throws IOException {
PDResources formResources = formXObj.getResources();
if (formResources == null || formResources.getXObjectNames() == null) {
return;
}
log.info(
"Checking form XObject '{}' on page {} for nested images",
formName.getName(),
pageNum + 1);
// Process all XObjects within the form
for (COSName nestedName : formResources.getXObjectNames()) {
PDXObject nestedXobj = formResources.getXObject(nestedName);
if (isImage(nestedXobj)) {
PDImageXObject nestedImage = (PDImageXObject) nestedXobj;
log.info(
"Found nested image '{}' in form '{}' on page {} - {}x{}",
nestedName.getName(),
formName.getName(),
pageNum + 1,
nestedImage.getWidth(),
nestedImage.getHeight());
// Create specialized reference for the nested image
NestedImageReference nestedRef = new NestedImageReference();
nestedRef.pageNum = pageNum;
nestedRef.formName = formName;
nestedRef.imageName = nestedName;
ImageIdentity identity = new ImageIdentity(nestedImage);
uniqueImages.computeIfAbsent(identity, k -> new ArrayList<>()).add(nestedRef);
}
}
}
// Count total images and nested images
private static void calculateImageStats(
Map<ImageIdentity, List<ImageReference>> uniqueImages, CompressionStats stats) {
for (List<ImageReference> references : uniqueImages.values()) {
for (ImageReference ref : references) {
stats.totalImages++;
if (ref instanceof NestedImageReference) {
stats.nestedImages++;
}
}
}
}
private static boolean isImage(PDXObject xobj) {
return xobj instanceof PDImageXObject;
}
private static boolean isForm(PDXObject xobj) {
return xobj instanceof PDFormXObject;
}
// Create compressed versions of all unique images
private static Map<ImageIdentity, PDImageXObject> createCompressedImages(
PDDocument doc,
Map<ImageIdentity, List<ImageReference>> uniqueImages,
double scaleFactor,
float jpegQuality,
boolean convertToGrayscale,
CompressionStats stats)
throws IOException {
Map<ImageIdentity, PDImageXObject> compressedVersions = new HashMap<>();
// Process each unique image exactly once
for (Entry<ImageIdentity, List<ImageReference>> entry : uniqueImages.entrySet()) {
ImageIdentity imageIdentity = entry.getKey();
List<ImageReference> references = entry.getValue();
if (references.isEmpty()) continue;
// Get the first instance of this image
PDImageXObject originalImage = getOriginalImage(doc, references.getFirst());
// Track original size
int originalSize = (int) originalImage.getCOSObject().getLength();
stats.totalOriginalBytes += originalSize;
// Process this unique image
PDImageXObject compressedImage =
compressImage(
doc,
originalImage,
originalSize,
scaleFactor,
jpegQuality,
convertToGrayscale);
if (compressedImage != null) {
// Store the compressed version in our map
compressedVersions.put(imageIdentity, compressedImage);
stats.compressedImages++;
// Update compression stats
int compressedSize = (int) compressedImage.getCOSObject().getLength();
stats.totalCompressedBytes += (long) compressedSize * references.size();
double reductionPercentage = 100.0 - ((compressedSize * 100.0) / originalSize);
log.info(
"Image identity {}: Compressed from {} to {} (reduced by {}%)",
imageIdentity,
GeneralUtils.formatBytes(originalSize),
GeneralUtils.formatBytes(compressedSize),
String.format(Locale.ROOT, "%.1f", reductionPercentage));
} else {
log.info(
"Image identity {}: Not suitable for compression, skipping", imageIdentity);
stats.totalCompressedBytes += (long) originalSize * references.size();
stats.skippedImages++;
}
}
return compressedVersions;
}
private static String generateImageHash(PDImageXObject image) {
try {
try (InputStream stream = image.getCOSObject().createRawInputStream()) {
byte[] buffer = new byte[16384];
int bytesRead = stream.read(buffer);
if (bytesRead > 0) {
byte[] dataToHash =
bytesRead == buffer.length ? buffer : Arrays.copyOf(buffer, bytesRead);
String enhancedData =
new String(dataToHash, StandardCharsets.UTF_8)
+ "_"
+ image.getWidth()
+ "_"
+ image.getHeight()
+ "_"
+ image.getColorSpace().getName()
+ "_"
+ image.getBitsPerComponent();
return bytesToHexString(
generateMD5(enhancedData.getBytes(StandardCharsets.UTF_8)));
}
return "empty-stream";
}
} catch (Exception e) {
ExceptionUtils.logException("image hash generation", e);
return "fallback-" + System.identityHashCode(image);
}
}
public TempFile compressImagesInPDF(
Path pdfFile, double scaleFactor, float jpegQuality, boolean convertToGrayscale)
throws Exception {
TempFile newCompressedPDF = tempFileManager.createManagedTempFile(".pdf");
long originalFileSize = Files.size(pdfFile);
log.info(
"Starting image compression with scale factor: {}, JPEG quality: {}, grayscale: {}"
+ " on file size: {}",
scaleFactor,
jpegQuality,
convertToGrayscale,
GeneralUtils.formatBytes(originalFileSize));
try (PDDocument doc = pdfDocumentFactory.load(pdfFile)) {
// Find all unique images in the document
Map<ImageIdentity, List<ImageReference>> uniqueImages = findImages(doc);
// Get statistics
CompressionStats stats = new CompressionStats();
stats.uniqueImagesCount = uniqueImages.size();
calculateImageStats(uniqueImages, stats);
// Create compressed versions of unique images
Map<ImageIdentity, PDImageXObject> compressedVersions =
createCompressedImages(
doc, uniqueImages, scaleFactor, jpegQuality, convertToGrayscale, stats);
// Replace all instances with compressed versions
replaceImages(doc, uniqueImages, compressedVersions);
// Log compression statistics
logCompressionStats(stats, originalFileSize);
// Free memory before saving
compressedVersions.clear();
uniqueImages.clear();
log.info("Saving compressed PDF to {}", newCompressedPDF.getPath());
doc.save(newCompressedPDF.getAbsolutePath());
// Log overall file size reduction
long compressedFileSize = Files.size(newCompressedPDF.getPath());
double overallReduction = 100.0 - ((compressedFileSize * 100.0) / originalFileSize);
log.info(
"Overall PDF compression: {} → {} (reduced by {}%)",
GeneralUtils.formatBytes(originalFileSize),
GeneralUtils.formatBytes(compressedFileSize),
String.format(Locale.ROOT, "%.1f", overallReduction));
return newCompressedPDF;
} catch (Exception e) {
newCompressedPDF.close();
throw e;
}
}
private static String generateMaskHash(PDImageXObject image) {
try {
PDImageXObject mask = image.getMask();
if (mask == null) {
mask = image.getSoftMask();
}
if (mask != null) {
try (InputStream stream = mask.getCOSObject().createRawInputStream()) {
byte[] buffer = new byte[4096];
int bytesRead = stream.read(buffer);
if (bytesRead > 0) {
byte[] dataToHash =
bytesRead == buffer.length
? buffer
: Arrays.copyOf(buffer, bytesRead);
return bytesToHexString(generateMD5(dataToHash));
}
return "empty-mask";
}
}
return "no-mask";
} catch (Exception e) {
ExceptionUtils.logException("mask hash generation", e);
return "fallback-mask-" + System.identityHashCode(image);
}
}
// Get original image from a reference
private static PDImageXObject getOriginalImage(PDDocument doc, ImageReference ref)
throws IOException {
if (ref instanceof NestedImageReference nestedRef) {
PDPage page = doc.getPage(nestedRef.pageNum);
PDResources pageResources = page.getResources();
// Get the form XObject
PDFormXObject formXObj = (PDFormXObject) pageResources.getXObject(nestedRef.formName);
// Get the nested image from the form's resources
PDResources formResources = formXObj.getResources();
return (PDImageXObject) formResources.getXObject(nestedRef.imageName);
} else {
// Get direct image from page resources
PDPage page = doc.getPage(ref.pageNum);
PDResources resources = page.getResources();
return (PDImageXObject) resources.getXObject(ref.name);
}
}
// Try to compress an image if it makes sense
private static PDImageXObject compressImage(
PDDocument doc,
PDImageXObject originalImage,
int originalSize,
double scaleFactor,
float jpegQuality,
boolean convertToGrayscale)
throws IOException {
// Process and compress the image
BufferedImage processedImage =
processAndCompressImage(
originalImage, scaleFactor, jpegQuality, convertToGrayscale);
if (processedImage == null) {
return null;
}
// Convert to bytes for storage
byte[] compressedData = convertToBytes(processedImage, jpegQuality);
// Check if compression is beneficial
if (compressedData.length < originalSize || convertToGrayscale) {
// Create a compressed version
return PDImageXObject.createFromByteArray(
doc, compressedData, originalImage.getCOSObject().toString());
}
return null;
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format(Locale.ROOT, "%02x", b));
}
return sb.toString();
}
// Replace a specific image reference with a compressed version
private static void replaceImageReference(
PDDocument doc, ImageReference ref, PDImageXObject compressedImage) throws IOException {
if (ref instanceof NestedImageReference nestedRef) {
// Replace nested image within form XObject
PDPage page = doc.getPage(nestedRef.pageNum);
PDResources pageResources = page.getResources();
// Get the form XObject
PDFormXObject formXObj = (PDFormXObject) pageResources.getXObject(nestedRef.formName);
// Replace the nested image in the form's resources
PDResources formResources = formXObj.getResources();
formResources.put(nestedRef.imageName, compressedImage);
log.info(
"Replaced nested image '{}' in form '{}' on page {} with compressed version",
nestedRef.imageName.getName(),
nestedRef.formName.getName(),
nestedRef.pageNum + 1);
} else {
// Replace direct image in page resources
PDPage page = doc.getPage(ref.pageNum);
PDResources resources = page.getResources();
resources.put(ref.name, compressedImage);
log.info("Replaced direct image on page {} with compressed version", ref.pageNum + 1);
}
}
// Log final stats about the compression
private static void logCompressionStats(CompressionStats stats, long originalFileSize) {
// Calculate image reduction percentage
double overallImageReduction =
stats.totalOriginalBytes > 0
? 100.0 - ((stats.totalCompressedBytes * 100.0) / stats.totalOriginalBytes)
: 0;
int duplicatedImages = stats.totalImages - stats.uniqueImagesCount;
log.info(
"Image compression summary - Total unique: {}, Compressed: {}, Skipped: {},"
+ " Duplicates: {}, Nested: {}",
stats.uniqueImagesCount,
stats.compressedImages,
stats.skippedImages,
duplicatedImages,
stats.nestedImages);
log.info(
"Total original image size: {}, compressed: {} (reduced by {}%)",
GeneralUtils.formatBytes(stats.totalOriginalBytes),
GeneralUtils.formatBytes(stats.totalCompressedBytes),
String.format(Locale.ROOT, "%.1f", overallImageReduction));
}
private static BufferedImage convertToGrayscale(BufferedImage image) {
BufferedImage grayImage =
new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = grayImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return grayImage;
}
// Resize and optionally convert to grayscale
private static BufferedImage processAndCompressImage(
PDImageXObject image, double scaleFactor, float jpegQuality, boolean convertToGrayscale)
throws IOException {
BufferedImage bufferedImage = image.getImage();
int originalWidth = bufferedImage.getWidth();
int originalHeight = bufferedImage.getHeight();
// Minimum dimensions to preserve reasonable quality
int MIN_WIDTH = 400;
int MIN_HEIGHT = 400;
log.info("Original dimensions: {}x{}", originalWidth, originalHeight);
// Skip if already small enough
if ((originalWidth <= MIN_WIDTH || originalHeight <= MIN_HEIGHT) && !convertToGrayscale) {
log.info("Skipping - below minimum dimensions threshold");
return null;
}
// Convert to grayscale first if requested (before resizing for better quality)
if (convertToGrayscale) {
bufferedImage = convertToGrayscale(bufferedImage);
log.info("Converted image to grayscale");
}
// Adjust scale factor for very large or very small images
double adjustedScaleFactor = scaleFactor;
if (originalWidth > 3000 || originalHeight > 3000) {
// More aggressive for very large images
adjustedScaleFactor = Math.min(scaleFactor, 0.75);
log.info("Very large image, using more aggressive scale: {}", adjustedScaleFactor);
} else if (originalWidth < 1000 || originalHeight < 1000) {
// More conservative for smaller images
adjustedScaleFactor = Math.max(scaleFactor, 0.9);
log.info("Smaller image, using conservative scale: {}", adjustedScaleFactor);
}
int newWidth = (int) (originalWidth * adjustedScaleFactor);
int newHeight = (int) (originalHeight * adjustedScaleFactor);
// Ensure minimum dimensions
newWidth = Math.max(newWidth, MIN_WIDTH);
newHeight = Math.max(newHeight, MIN_HEIGHT);
// Skip if change is negligible
if ((double) newWidth / originalWidth > 0.95
&& (double) newHeight / originalHeight > 0.95
&& !convertToGrayscale) {
log.info("Change too small, skipping compression");
return null;
}
log.info(
"Resizing to {}x{} ({}% of original)",
newWidth, newHeight, Math.round((newWidth * 100.0) / originalWidth));
BufferedImage scaledImage;
if (convertToGrayscale) {
// If already grayscale, maintain the grayscale format
scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_BYTE_GRAY);
} else {
// Otherwise use original color model
scaledImage =
new BufferedImage(
newWidth,
newHeight,
bufferedImage.getColorModel().hasAlpha()
? BufferedImage.TYPE_INT_ARGB
: BufferedImage.TYPE_INT_RGB);
}
Graphics2D g2d = scaledImage.createGraphics();
g2d.setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(bufferedImage, 0, 0, newWidth, newHeight, null);
g2d.dispose();
return scaledImage;
}
// Convert image to byte array with quality settings
private static byte[] convertToBytes(BufferedImage scaledImage, float jpegQuality)
throws IOException {
String format = scaledImage.getColorModel().hasAlpha() ? "png" : "jpeg";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if ("jpeg".equals(format)) {
// Get the best available JPEG writer
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = writers.next();
JPEGImageWriteParam param = (JPEGImageWriteParam) writer.getDefaultWriteParam();
// Set compression parameters
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(jpegQuality);
param.setOptimizeHuffmanTables(true); // Better compression
param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); // Progressive scanning
// Write compressed image
try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream)) {
writer.setOutput(ios);
writer.write(null, new IIOImage(scaledImage, null, null), param);
}
writer.dispose();
} else {
ImageIO.write(scaledImage, format, outputStream);
}
return outputStream.toByteArray();
}
// Get image filter/compression type
private static String getImageFilter(PDImageXObject image) {
try {
return image.getCOSObject().getDictionaryObject(COSName.FILTER).toString();
} catch (Exception e) {
return "unknown";
}
}
// Get color profile information
private static String getColorProfileInfo(PDImageXObject image) {
try {
// Try to get ICC profile information
if (image.getColorSpace() != null) {
return image.getColorSpace().getName()
+ "_"
+ image.getColorSpace().getNumberOfComponents();
}
return "no-profile";
} catch (Exception e) {
return "error-profile";
}
}
// Determine image type from stream data
private static String getImageType(PDImageXObject image) {
try {
String filter = getImageFilter(image);
if (filter.contains("DCTDecode") || filter.contains("JPXDecode")) {
return "JPEG";
} else if (filter.contains("FlateDecode")) {
return "PNG";
} else if (filter.contains("CCITTFaxDecode")) {
return "TIFF";
} else if (filter.contains("JBIG2Decode")) {
return "JBIG2";
} else {
return "RAW";
}
} catch (Exception e) {
return "unknown";
}
}
// Generate hash of decode parameters
private static String generateDecodeParamsHash(PDImageXObject image) {
try {
// Get decode parameters that affect how the image is processed
StringBuilder params = new StringBuilder();
// Add filter information
params.append(getImageFilter(image));
// Add color space components
params.append("_").append(image.getColorSpace().getNumberOfComponents());
// Add bits per component
params.append("_").append(image.getBitsPerComponent());
// Add any decode array parameters
if (image.getDecode() != null) {
params.append("_").append(image.getDecode().toString());
}
return bytesToHexString(
generateMD5(params.toString().getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
return "fallback-decode-" + System.identityHashCode(image);
}
}
private static byte[] generateMD5(byte[] data) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
return md.digest(data); // Get the MD5 hash of the image bytes
} catch (NoSuchAlgorithmException e) {
throw ExceptionUtils.createMd5AlgorithmException(e);
}
}
private static class ImageIdentity {
private final String pixelHash; // Hash of pixel data
private final String colorSpace; // e.g., "DeviceRGB", "DeviceCMYK"
private final int bitsPerComponent;
private final boolean hasMask; // Has transparency
private final String maskHash; // Hash of mask data if present
private final int width; // Image width in pixels
private final int height; // Image height in pixels
private final String filter; // Image filter/compression type
private final String colorProfile; // Color profile information
private final long streamLength; // Original stream length
private final String imageType; // Image type (JPEG, PNG, etc.)
private final String decodeParams; // Decode parameters hash
private final String metadataHash; // Hash of image metadata
public ImageIdentity(PDImageXObject image) throws IOException {
this.pixelHash = generateImageHash(image);
this.colorSpace = image.getColorSpace().getName();
this.bitsPerComponent = image.getBitsPerComponent();
this.hasMask = image.getMask() != null || image.getSoftMask() != null;
this.maskHash = hasMask ? generateMaskHash(image) : null;
this.width = image.getWidth();
this.height = image.getHeight();
this.filter = getImageFilter(image);
this.colorProfile = getColorProfileInfo(image);
this.streamLength = image.getCOSObject().getLength();
this.imageType = getImageType(image);
this.decodeParams = generateDecodeParamsHash(image);
this.metadataHash = ImageIdentity.generateMetadataHash(image);
}
// Generate hash of image metadata
private static String generateMetadataHash(PDImageXObject image) {
try {
StringBuilder metadata = new StringBuilder();
// Add image dimensions
metadata.append(image.getWidth()).append("x").append(image.getHeight());
// Add color space info
metadata.append("_").append(image.getColorSpace().getName());
// Add bits per component
metadata.append("_").append(image.getBitsPerComponent());
// Add stream length
metadata.append("_").append(image.getCOSObject().getLength());
// Add mask information
if (image.getMask() != null) {
metadata.append("_mask");
}
if (image.getSoftMask() != null) {
metadata.append("_softmask");
}
return bytesToHexString(
generateMD5(metadata.toString().getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
return "fallback-meta-" + System.identityHashCode(image);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ImageIdentity that)) return false;
return bitsPerComponent == that.bitsPerComponent
&& hasMask == that.hasMask
&& width == that.width
&& height == that.height
&& streamLength == that.streamLength
&& Objects.equals(pixelHash, that.pixelHash)
&& Objects.equals(colorSpace, that.colorSpace)
&& Objects.equals(maskHash, that.maskHash)
&& Objects.equals(filter, that.filter)
&& Objects.equals(colorProfile, that.colorProfile)
&& Objects.equals(imageType, that.imageType)
&& Objects.equals(decodeParams, that.decodeParams)
&& Objects.equals(metadataHash, that.metadataHash);
}
@Override
public int hashCode() {
return Objects.hash(
pixelHash,
colorSpace,
bitsPerComponent,
hasMask,
maskHash,
width,
height,
filter,
colorProfile,
streamLength,
imageType,
decodeParams,
metadataHash);
}
@Override
public String toString() {
return String.format(
Locale.ROOT,
"%s_%s_%d_%dx%d_%s_%s_%d_%s_%s_%s",
pixelHash.substring(0, Math.min(8, pixelHash.length())),
colorSpace,
bitsPerComponent,
width,
height,
filter,
imageType,
streamLength,
hasMask ? "masked" : "nomask",
decodeParams.substring(0, Math.min(4, decodeParams.length())),
metadataHash.substring(0, Math.min(4, metadataHash.length())));
}
}
// Scale factors for different optimization levels (lower => smaller)
private static double getScaleFactorForLevel(int optimizeLevel) {
return switch (optimizeLevel) {
case 1 -> 0.98; // negligible resizing
case 2 -> 0.95;
case 3 -> 0.88;
case 4 -> 0.78;
case 5 -> 0.68;
case 6 -> 0.58;
case 7 -> 0.48;
case 8 -> 0.38;
case 9 -> 0.28;
default -> 1.0;
};
}
// JPEG quality for different optimization levels (lower => smaller)
private static float getJpegQualityForLevel(int optimizeLevel) {
return switch (optimizeLevel) {
case 1 -> 0.92f; // very light
case 2 -> 0.88f;
case 3 -> 0.85f;
case 4 -> 0.80f;
case 5 -> 0.72f;
case 6 -> 0.65f;
case 7 -> 0.55f;
case 8 -> 0.45f;
case 9 -> 0.35f; // aggressive
default -> 0.75f;
};
}
// Pick optimization level based on target size
private static int determineOptimizeLevel(double sizeReductionRatio) {
if (sizeReductionRatio > 0.9) return 1;
if (sizeReductionRatio > 0.8) return 2;
if (sizeReductionRatio > 0.7) return 3;
if (sizeReductionRatio > 0.6) return 4;
if (sizeReductionRatio > 0.3) return 5;
if (sizeReductionRatio > 0.2) return 6;
if (sizeReductionRatio > 0.15) return 7;
if (sizeReductionRatio > 0.1) return 8;
return 9;
}
// Increment optimization level if we need more compression
private static int incrementOptimizeLevel(int currentLevel, long currentSize, long targetSize) {
double currentRatio = currentSize / (double) targetSize;
log.info("Current compression ratio: {}", String.format(Locale.ROOT, "%.2f", currentRatio));
if (currentRatio > 2.0) {
return Math.min(9, currentLevel + 3);
} else if (currentRatio > 1.5) {
return Math.min(9, currentLevel + 2);
}
return Math.min(9, currentLevel + 1);
}
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/compress-pdf",
resourceWeight = ResourceWeight.LARGE_WEIGHT)
@ToolIO(produces = ToolFormat.PDF)
@Operation(
summary = "Optimize PDF file",
description =
"This endpoint accepts a PDF file and optimizes it based on the provided"
+ " parameters.")
public ResponseEntity<Resource> optimizePdf(@ModelAttribute OptimizePdfRequest request)
throws Exception {
MultipartFile inputFile = request.getFileInput();
// Validate input file
if (inputFile == null || inputFile.isEmpty()) {
throw ExceptionUtils.createFileNullOrEmptyException();
}
Integer optimizeLevel = request.getOptimizeLevel();
String expectedOutputSizeString = request.getExpectedOutputSize();
Boolean convertToGrayscale = request.getGrayscale();
Boolean convertToLineArt = request.getLineArt();
Double lineArtThreshold = request.getLineArtThreshold();
Integer lineArtEdgeLevel = request.getLineArtEdgeLevel();
if (expectedOutputSizeString == null && optimizeLevel == null) {
throw ExceptionUtils.createCompressionOptionsRequiredException();
}
Long expectedOutputSize = 0L;
boolean autoMode = false;
if (expectedOutputSizeString != null && expectedOutputSizeString.length() > 1) {
expectedOutputSize = GeneralUtils.convertSizeToBytes(expectedOutputSizeString);
autoMode = true;
}
List<TempFile> tempFiles = new ArrayList<>();
// Create initial input file
TempFile originalTempFile = tempFileManager.createManagedTempFile(".pdf");
tempFiles.add(originalTempFile);
Path originalFile = originalTempFile.getPath();
inputFile.transferTo(originalTempFile.getFile());
long inputFileSize = Files.size(originalFile);
TempFile currentTempFile = tempFileManager.createManagedTempFile(".pdf");
tempFiles.add(currentTempFile);
Path currentFile = currentTempFile.getPath();
Files.copy(originalFile, currentFile, StandardCopyOption.REPLACE_EXISTING);
try {
if (autoMode) {
double sizeReductionRatio = expectedOutputSize / (double) inputFileSize;
optimizeLevel = determineOptimizeLevel(sizeReductionRatio);
}
if (Boolean.TRUE.equals(convertToLineArt)) {
if (lineArtConversionService == null) {
throw new ResponseStatusException(
HttpStatus.FORBIDDEN,
"Line art conversion is unavailable - ImageMagick service not found");
}
if (!isImageMagickEnabled()) {
throw new IOException(
"ImageMagick is not enabled but line art conversion was requested");
}
double thresholdValue =
lineArtThreshold == null
? 55d
: Math.min(100d, Math.max(0d, lineArtThreshold));
int edgeLevel =
lineArtEdgeLevel == null ? 1 : Math.min(3, Math.max(1, lineArtEdgeLevel));
currentFile =