From 3715c555d3e13e4c5904c35f2bcc0e507a107334 Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com> Date: Fri, 26 May 2023 15:25:18 +0100 Subject: [PATCH] fix for #213 --- src/main/java/stirling/software/SPDF/utils/PdfUtils.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/stirling/software/SPDF/utils/PdfUtils.java b/src/main/java/stirling/software/SPDF/utils/PdfUtils.java index 8b9b3bd2..bb172a7b 100644 --- a/src/main/java/stirling/software/SPDF/utils/PdfUtils.java +++ b/src/main/java/stirling/software/SPDF/utils/PdfUtils.java @@ -30,6 +30,7 @@ import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.rendering.ImageType; @@ -125,6 +126,7 @@ public class PdfUtils { public static byte[] imageToPdf(MultipartFile[] files, boolean stretchToFit, boolean autoRotate, String colorType) throws IOException { try (PDDocument doc = new PDDocument()) { for (MultipartFile file : files) { + String contentType = file.getContentType(); String originalFilename = file.getOriginalFilename(); if (originalFilename != null && (originalFilename.toLowerCase().endsWith(".tiff") || originalFilename.toLowerCase().endsWith(".tif")) ) { ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); @@ -146,7 +148,12 @@ public class PdfUtils { } BufferedImage image = ImageIO.read(imageFile); BufferedImage convertedImage = convertColorType(image, colorType); - PDImageXObject pdImage = LosslessFactory.createFromImage(doc, convertedImage); + PDImageXObject pdImage; + if (contentType != null && (contentType.equals("image/jpeg"))) { + pdImage = JPEGFactory.createFromImage(doc, convertedImage); + } else { + pdImage = LosslessFactory.createFromImage(doc, convertedImage); + } addImageToDocument(doc, pdImage, stretchToFit, autoRotate); } catch (IOException e) { logger.error("Error writing image to file: {}", imageFile.getAbsolutePath(), e);