Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Convert image inputs to PDF before JPDFium merge (#7828)

RaphaelFrantz85195c14b90a
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
index cb28a68177..3305e176e1 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
@@ -5,6 +5,7 @@ import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -15,6 +16,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.*;
+import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import org.apache.pdfbox.cos.COSName;
@@ -32,6 +34,7 @@ import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
+import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
@@ -448,32 +451,10 @@ public class PdfUtils {
throws IOException {
try (PDDocument doc = pdfDocumentFactory.createNewDocument()) {
for (MultipartFile file : files) {
- String contentType = file.getContentType();
- String originalFilename = Filenames.toSimpleFileName(file.getOriginalFilename());
- if (originalFilename != null
- && (originalFilename.toLowerCase(Locale.ROOT).endsWith(".tiff")
- || originalFilename.toLowerCase(Locale.ROOT).endsWith(".tif"))) {
- ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
- reader.setInput(ImageIO.createImageInputStream(file.getInputStream()));
- int numPages = reader.getNumImages(true);
- for (int i = 0; i < numPages; i++) {
- BufferedImage pageImage = reader.read(i);
- BufferedImage convertedImage =
- ImageProcessingUtils.convertColorType(pageImage, colorType);
- PDImageXObject pdImage =
- LosslessFactory.createFromImage(doc, convertedImage);
- addImageToDocument(doc, pdImage, fitOption, autoRotate);
- }
+ if (isTiff(file)) {
+ appendTiffFrames(doc, file, fitOption, autoRotate, colorType);
} else {
- BufferedImage image = ImageProcessingUtils.loadImageWithExifOrientation(file);
- BufferedImage convertedImage =
- ImageProcessingUtils.convertColorType(image, colorType);
- // Use JPEGFactory if it's JPEG since JPEG is lossy
- PDImageXObject pdImage =
- (contentType != null && MediaType.IMAGE_JPEG_VALUE.equals(contentType))
- ? JPEGFactory.createFromImage(doc, convertedImage)
- : LosslessFactory.createFromImage(doc, convertedImage);
- addImageToDocument(doc, pdImage, fitOption, autoRotate);
+ appendSingleImage(doc, file, fitOption, autoRotate, colorType);
}
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
@@ -483,6 +464,79 @@ public class PdfUtils {
}
}
+ /**
+ * A TIFF is recognised by declared content type as well as filename suffix: an extensionless
+ * upload would otherwise take the single-image path and silently drop every frame but one.
+ */
+ private boolean isTiff(MultipartFile file) {
+ if (hasTiffContentType(file.getContentType())) {
+ return true;
+ }
+ String filename = Filenames.toSimpleFileName(file.getOriginalFilename());
+ return filename != null
+ && (filename.toLowerCase(Locale.ROOT).endsWith(".tiff")
+ || filename.toLowerCase(Locale.ROOT).endsWith(".tif"));
+ }
+
+ /** Parsed, not compared whole: RFC 3302 allows parameters such as {@code application=}. */
+ private boolean hasTiffContentType(String contentType) {
+ if (contentType == null) {
+ return false;
+ }
+ try {
+ MediaType mediaType = MediaType.parseMediaType(contentType);
+ return "image".equals(mediaType.getType())
+ && ("tiff".equals(mediaType.getSubtype())
+ || "x-tiff".equals(mediaType.getSubtype()));
+ } catch (InvalidMediaTypeException e) {
+ return false;
+ }
+ }
+
+ /** Every frame becomes a page; streams and reader are released even when a frame fails. */
+ private void appendTiffFrames(
+ PDDocument doc,
+ MultipartFile file,
+ String fitOption,
+ boolean autoRotate,
+ String colorType)
+ throws IOException {
+ try (InputStream input = file.getInputStream();
+ ImageInputStream imageInput = ImageIO.createImageInputStream(input)) {
+ ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
+ try {
+ reader.setInput(imageInput);
+ int numPages = reader.getNumImages(true);
+ for (int i = 0; i < numPages; i++) {
+ BufferedImage convertedImage =
+ ImageProcessingUtils.convertColorType(reader.read(i), colorType);
+ PDImageXObject pdImage = LosslessFactory.createFromImage(doc, convertedImage);
+ addImageToDocument(doc, pdImage, fitOption, autoRotate);
+ }
+ } finally {
+ reader.dispose();
+ }
+ }
+ }
+
+ private void appendSingleImage(
+ PDDocument doc,
+ MultipartFile file,
+ String fitOption,
+ boolean autoRotate,
+ String colorType)
+ throws IOException {
+ BufferedImage image = ImageProcessingUtils.loadImageWithExifOrientation(file);
+ BufferedImage convertedImage = ImageProcessingUtils.convertColorType(image, colorType);
+ // Use JPEGFactory if it's JPEG since JPEG is lossy
+ String contentType = file.getContentType();
+ PDImageXObject pdImage =
+ (contentType != null && MediaType.IMAGE_JPEG_VALUE.equals(contentType))
+ ? JPEGFactory.createFromImage(doc, convertedImage)
+ : LosslessFactory.createFromImage(doc, convertedImage);
+ addImageToDocument(doc, pdImage, fitOption, autoRotate);
+ }
+
public void addImageToDocument(
PDDocument doc, PDImageXObject image, String fitOption, boolean autoRotate)
throws IOException {
diff --git a/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java b/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java
index 668ba98902..cf7e17a3e0 100644
--- a/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java
@@ -337,6 +337,43 @@ class PdfUtilsMoreTest {
}
}
+ @Test
+ @DisplayName("an extensionless upload with a TIFF content type keeps every frame")
+ void contentTypeTiffKeepsAllFrames() throws IOException {
+ CustomPDFDocumentFactory factory = mock(CustomPDFDocumentFactory.class);
+ when(factory.createNewDocument()).thenReturn(new PDDocument());
+
+ MockMultipartFile tiff =
+ new MockMultipartFile("file", "scan", "image/tiff", multiFrameTiff());
+
+ byte[] pdfOut =
+ PdfUtils.imageToPdf(
+ new MultipartFile[] {tiff}, "fillPage", false, "color", factory);
+
+ try (PDDocument doc = org.apache.pdfbox.Loader.loadPDF(pdfOut)) {
+ assertThat(doc.getNumberOfPages()).isEqualTo(2);
+ }
+ }
+
+ @Test
+ @DisplayName("a TIFF content type carrying parameters is still recognised")
+ void contentTypeWithParametersStillTiff() throws IOException {
+ CustomPDFDocumentFactory factory = mock(CustomPDFDocumentFactory.class);
+ when(factory.createNewDocument()).thenReturn(new PDDocument());
+
+ MockMultipartFile tiff =
+ new MockMultipartFile(
+ "file", "scan", "image/tiff; application=foo", multiFrameTiff());
+
+ byte[] pdfOut =
+ PdfUtils.imageToPdf(
+ new MultipartFile[] {tiff}, "fillPage", false, "color", factory);
+
+ try (PDDocument doc = org.apache.pdfbox.Loader.loadPDF(pdfOut)) {
+ assertThat(doc.getNumberOfPages()).isEqualTo(2);
+ }
+ }
+
@Test
@DisplayName("a .tif extension is also handled by the TIFF reader path")
void tifExtensionHandled() throws IOException {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
index 77a97b9b05..1503ecdfe6 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
@@ -9,6 +9,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
+import java.util.Locale;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
@@ -47,6 +48,7 @@ import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.PdfErrorUtils;
+import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -131,31 +133,11 @@ public class MergeController {
return Long.compare(t2, t1);
};
case "byPDFTitle" ->
- (file1, file2) -> {
- try (PDDocument doc1 = pdfDocumentFactory.load(file1);
- PDDocument doc2 = pdfDocumentFactory.load(file2)) {
- String title1 =
- doc1.getDocumentInformation() != null
- ? doc1.getDocumentInformation().getTitle()
- : null;
- String title2 =
- doc2.getDocumentInformation() != null
- ? doc2.getDocumentInformation().getTitle()
- : null;
- if (title1 == null && title2 == null) {
- return 0;
- }
- if (title1 == null) {
- return 1;
- }
- if (title2 == null) {
- return -1;
- }
- return title1.compareToIgnoreCase(title2);
- } catch (IOException e) {
- return 0;
- }
- };
+ // Titles must be read per file: a pairwise load that returns 0 when either
+ // side is unreadable (an image input) makes the comparator intransitive.
+ Comparator.comparing(
+ this::getPdfTitleSafe,
+ Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));
case "orderProvided" -> (file1, file2) -> 0;
default -> (file1, file2) -> 0;
};
@@ -188,6 +170,16 @@ public class MergeController {
}
}
+ /** Null when the file has no title or is not a loadable PDF (an image), sorting those last. */
+ private String getPdfTitleSafe(MultipartFile file) {
+ try (PDDocument doc = pdfDocumentFactory.load(file)) {
+ PDDocumentInformation info = doc.getDocumentInformation();
+ return info != null ? info.getTitle() : null;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
private long getPdfDateTimeSafe(MultipartFile file) {
try {
try (PDDocument doc = pdfDocumentFactory.load(file)) {
@@ -241,13 +233,20 @@ public class MergeController {
value = "/merge-pdfs",
resourceWeight = ResourceWeight.MEDIUM_WEIGHT)
@StandardPdfResponse
- @ToolIO(produces = ToolFormat.PDF, arity = ToolArity.MISO)
+ @ToolIO(
+ accepts = {ToolFormat.PDF, ToolFormat.IMAGE},
+ // The installed ImageIO readers cover these; ToolFormat.IMAGE's ai/eps have none.
+ inputExtensions = {
+ "pdf", "png", "jpg", "jpeg", "gif", "bmp", "tif", "tiff", "webp", "svg", "psd"
+ },
+ produces = ToolFormat.PDF,
+ arity = ToolArity.MISO)
@Operation(
summary = "Merge multiple PDF files into one",
description =
"This endpoint merges multiple PDF files into a single PDF file. The merged"
+ " file will contain all pages from the input files in the order they were"
- + " provided.")
+ + " provided. Image inputs are converted to PDF pages before merging.")
public ResponseEntity<Resource> mergePdfs(
@ModelAttribute MergePdfsRequest request,
@RequestParam(value = "fileOrder", required = false) String fileOrder)
@@ -277,7 +276,19 @@ public class MergeController {
List<Integer> invalidIndexes = new ArrayList<>();
for (int index = 0; index < files.length; index++) {
MultipartFile multipartFile = files[index];
- File tempFile = tempFileManager.convertMultipartFileToFile(multipartFile);
+ File tempFile;
+ if (isImageFile(multipartFile)) {
+ // Convert images to PDF so JPDFium can merge them; fall back to the raw
+ // upload if conversion fails so pre-validate can flag it.
+ try {
+ tempFile = convertImageToPdf(multipartFile);
+ } catch (Exception e) {
+ ExceptionUtils.logException("image to PDF conversion for merge", e);
+ tempFile = tempFileManager.convertMultipartFileToFile(multipartFile);
+ }
+ } else {
+ tempFile = tempFileManager.convertMultipartFileToFile(multipartFile);
+ }
filesToDelete.add(tempFile);
inputPaths.add(tempFile.toPath());
@@ -376,6 +387,42 @@ public class MergeController {
return WebResponseUtils.pdfFileToWebResponse(outputTempFile, mergedFileName);
}
+ private boolean isImageFile(MultipartFile file) {
+ String contentType = file.getContentType();
+ if (contentType != null && contentType.toLowerCase(Locale.ROOT).startsWith("image/")) {
+ return true;
+ }
+ String filename = file.getOriginalFilename();
+ if (filename == null) {
+ return false;
+ }
+ int dot = filename.lastIndexOf('.');
+ if (dot < 0 || dot == filename.length() - 1) {
+ return false;
+ }
+ return ToolFormat.IMAGE
+ .getExtensions()
+ .contains(filename.substring(dot + 1).toLowerCase(Locale.ROOT));
+ }
+
+ private File convertImageToPdf(MultipartFile image) throws IOException {
+ byte[] pdfBytes =
+ PdfUtils.imageToPdf(
+ new MultipartFile[] {image},
+ "maintainAspectRatio",
+ false,
+ "color",
+ pdfDocumentFactory);
+ File pdfFile = tempFileManager.createTempFile(".pdf");
+ try {
+ Files.write(pdfFile.toPath(), pdfBytes);
+ } catch (IOException e) {
+ tempFileManager.deleteTempFile(pdfFile);
+ throw e;
+ }
+ return pdfFile;
+ }
+
private int[] mergeWithJpdfium(
List<Path> inputPaths, MultipartFile[] files, boolean generateToc, Path outputPath)
throws IOException {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerGapTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerGapTest.java
index 0a6aa0efca..11c233ba55 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerGapTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerGapTest.java
@@ -190,10 +190,13 @@ class MergeControllerGapTest {
}
@Test
- @DisplayName("IOException while loading yields equal (0)")
- void ioExceptionYieldsEqual() throws Exception {
+ @DisplayName("IOException while loading sorts the unreadable file last")
+ void ioExceptionSortsLast() throws Exception {
+ PDDocument titled = docWithTitle("Beta");
when(pdfDocumentFactory.load(fileA)).thenThrow(new IOException("boom"));
- assertEquals(0, sortComparator("byPDFTitle").compare(fileA, fileB));
+ when(pdfDocumentFactory.load(fileB)).thenReturn(titled);
+
+ assertEquals(1, sortComparator("byPDFTitle").compare(fileA, fileB));
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerMoreTest.java
index 250773562b..aa0b6348fb 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerMoreTest.java
@@ -3,12 +3,17 @@ package stirling.software.SPDF.controller.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
+import javax.imageio.ImageIO;
+
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
@@ -18,6 +23,7 @@ import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
+import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
@@ -101,6 +107,18 @@ class MergeControllerMoreTest {
buildPdf(pages, title, modMillis));
}
+ private static MockMultipartFile png(String name) throws IOException {
+ BufferedImage image = new BufferedImage(120, 80, BufferedImage.TYPE_INT_RGB);
+ Graphics2D graphics = image.createGraphics();
+ graphics.setColor(Color.ORANGE);
+ graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
+ graphics.dispose();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ImageIO.write(image, "png", baos);
+ return new MockMultipartFile(
+ "fileInput", name, MediaType.IMAGE_PNG_VALUE, baos.toByteArray());
+ }
+
private static MergePdfsRequest request(
MockMultipartFile[] files, String sortType, boolean removeCertSign, boolean toc) {
MergePdfsRequest req = new MergePdfsRequest();
@@ -362,4 +380,52 @@ class MergeControllerMoreTest {
}
}
}
+
+ @Nested
+ @DisplayName("Image inputs")
+ class ImageInputs {
+
+ @Test
+ @DisplayName("merges a PNG with a PDF, rendering the image on the first page")
+ void mergesImageWithPdf() throws Exception {
+ MockMultipartFile[] files = {png("scan.png"), pdf("doc.pdf", 2)};
+ ResponseEntity<Resource> response =
+ mergeController.mergePdfs(request(files, "orderProvided", false, false), null);
+ try (PDDocument result = readResponse(response)) {
+ assertThat(result.getNumberOfPages()).isEqualTo(3);
+ assertThat(pageContainsOrange(result, 0)).isTrue();
+ assertThat(pageContainsOrange(result, 1)).isFalse();
+ }
+ }
+
+ @Test
+ @DisplayName("merges two images into a two-page PDF, rendering both")
+ void mergesTwoImages() throws Exception {
+ MockMultipartFile[] files = {png("a.png"), png("b.png")};
+ ResponseEntity<Resource> response =
+ mergeController.mergePdfs(request(files, "orderProvided", false, false), null);
+ try (PDDocument result = readResponse(response)) {
+ assertThat(result.getNumberOfPages()).isEqualTo(2);
+ assertThat(pageContainsOrange(result, 0)).isTrue();
+ assertThat(pageContainsOrange(result, 1)).isTrue();
+ }
+ }
+
+ /** True when the rendered page shows the orange fill painted by {@link #png(String)}. */
+ private boolean pageContainsOrange(PDDocument document, int pageIndex) throws IOException {
+ BufferedImage rendered = new PDFRenderer(document).renderImage(pageIndex);
+ for (int y = 0; y < rendered.getHeight(); y += 4) {
+ for (int x = 0; x < rendered.getWidth(); x += 4) {
+ int rgb = rendered.getRGB(x, y);
+ int red = (rgb >> 16) & 0xFF;
+ int green = (rgb >> 8) & 0xFF;
+ int blue = rgb & 0xFF;
+ if (Math.abs(red - 255) <= 8 && Math.abs(green - 200) <= 8 && blue <= 8) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ }
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerTest.java
index c245cffb09..3ceefcf08c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/MergeControllerTest.java
@@ -305,4 +305,39 @@ class MergeControllerTest {
assertEquals(mockMergedDocument, result);
verify(mockMergedDocument, never()).addPage(any(PDPage.class));
}
+
+ @Test
+ void isImageFile_detectsByContentType() throws Exception {
+ MockMultipartFile jpg =
+ new MockMultipartFile(
+ "file", "scan", MediaType.IMAGE_JPEG_VALUE, new byte[] {1, 2, 3});
+ assertTrue(invokeIsImageFile(jpg));
+ }
+
+ @Test
+ void isImageFile_detectsByExtension_whenContentTypeMissing() throws Exception {
+ // Uppercase extension and no content type: extension check must still match.
+ MockMultipartFile png = new MockMultipartFile("file", "photo.PNG", null, new byte[] {1});
+ assertTrue(invokeIsImageFile(png));
+ }
+
+ @Test
+ void isImageFile_returnsFalseForPdf() throws Exception {
+ assertFalse(invokeIsImageFile(mockFile1));
+ }
+
+ @Test
+ void isImageFile_returnsFalseWhenNoExtensionAndNotImageContentType() throws Exception {
+ MockMultipartFile noExt =
+ new MockMultipartFile(
+ "file", "document_no_ext", MediaType.APPLICATION_PDF_VALUE, new byte[] {1});
+ assertFalse(invokeIsImageFile(noExt));
+ }
+
+ private boolean invokeIsImageFile(MultipartFile file) throws Exception {
+ Method isImageFileMethod =
+ MergeController.class.getDeclaredMethod("isImageFile", MultipartFile.class);
+ isImageFileMethod.setAccessible(true);
+ return (boolean) isImageFileMethod.invoke(mergeController, file);
+ }
}
diff --git a/engine/src/stirling/models/tool_io.py b/engine/src/stirling/models/tool_io.py
index d8349961f4..7de2e72caa 100644
--- a/engine/src/stirling/models/tool_io.py
+++ b/engine/src/stirling/models/tool_io.py
@@ -176,7 +176,9 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO
),
ToolEndpoint.EDIT_TEXT: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
- ToolEndpoint.MERGE_PDFS: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.MISO),
+ ToolEndpoint.MERGE_PDFS: ToolIOSpec(
+ accepts=[ToolFormat.PDF, ToolFormat.IMAGE], produces=ToolFormat.PDF, arity=ToolArity.MISO
+ ),
ToolEndpoint.MULTI_PAGE_LAYOUT: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.PDF_TO_SINGLE_PAGE: ToolIOSpec(
accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index d478800870..9d0cf5b6bb 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -725,7 +725,7 @@ class SortType(StrEnum):
class MergePdfsParams(ApiModel):
"""
- This endpoint merges multiple PDF files into a single PDF file. The merged file will contain all pages from the input files in the order they were provided. Input:PDF Output:PDF Type:MISO
+ This endpoint merges multiple PDF files into a single PDF file. The merged file will contain all pages from the input files in the order they were provided. Image inputs are converted to PDF pages before merging. Input:PDF/IMAGE Output:PDF Type:MISO
"""
client_file_ids: str | None = Field(
diff --git a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
index d08af30655..261a1babfe 100644
--- a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
+++ b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
@@ -255,7 +255,22 @@ describe("tool file selection", () => {
);
});
- test("Merge requires two eligible PDFs and follows encryption changes", async () => {
+ test("Merge counts an image as an eligible input", async () => {
+ render(
+ <MantineProvider>
+ <Merge />
+ </MantineProvider>,
+ );
+ expect(
+ await screen.findByText(/2 files$/, { selector: "p" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Merge PDFs/ })).toBeEnabled();
+ });
+
+ test("Merge requires two eligible files and follows encryption changes", async () => {
+ // Images are eligible merge inputs now, so the threshold case needs a lone PDF.
+ workspace.files = workspace.files.slice(0, 1);
+ workspace.fileStubs = workspace.fileStubs.slice(0, 1);
const renderMerge = () => (
<MantineProvider>
<Merge />
diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.ts
index 95aeb2c361..aa70c99b57 100644
--- a/frontend/editor/src/core/types/toolIO.ts
+++ b/frontend/editor/src/core/types/toolIO.ts
@@ -458,9 +458,22 @@ export const TOOL_IO: ToolIOTable = {
arity: "SISO",
},
"/api/v1/general/merge-pdfs": {
- accepts: ["PDF"],
+ accepts: ["PDF", "IMAGE"],
produces: "PDF",
arity: "MISO",
+ inputExtensions: [
+ "pdf",
+ "png",
+ "jpg",
+ "jpeg",
+ "gif",
+ "bmp",
+ "tif",
+ "tiff",
+ "webp",
+ "svg",
+ "psd",
+ ],
},
"/api/v1/general/multi-page-layout": {
accepts: ["PDF"],