Skip to content

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

feat(crop): add support for selective page cropping (#7753)

brios3314fa822f98
diff --git a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
index 01dd700296..5ee0d17895 100644
--- a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
@@ -659,19 +659,20 @@ public class GeneralUtils {
int offset = oneBased ? 1 : 0;
int maxSize = Math.max(1000, totalPages * 3);
for (String page : pages) {
- if ("all".equalsIgnoreCase(page)) {
+ String trimmedPage = page == null ? "" : page.trim();
+ if ("all".equalsIgnoreCase(trimmedPage)) {
for (int i = 0; i < totalPages; i++) {
result.add(i + offset);
}
- } else if (page.contains(",")) {
+ } else if (trimmedPage.contains(",")) {
// Split the string into parts, could be single pages or ranges
- String[] parts = page.split(",");
+ String[] parts = trimmedPage.split(",");
for (String part : parts) {
result.addAll(handlePart(part, totalPages, offset));
}
} else {
- result.addAll(handlePart(page, totalPages, offset));
+ result.addAll(handlePart(trimmedPage, totalPages, offset));
}
if (result.size() > maxSize) {
throw new IllegalArgumentException(
@@ -801,23 +802,27 @@ public class GeneralUtils {
private List<Integer> handlePart(String part, int totalPages, int offset) {
List<Integer> partResult = new ArrayList<>();
+ String trimmedPart = part == null ? "" : part.trim();
+ if (trimmedPart.isEmpty()) {
+ return partResult;
+ }
// First check for n-syntax because it should not be processed as a range
- if (part.contains("n")) {
- partResult = evaluateNFunc(part, totalPages);
+ if (trimmedPart.contains("n")) {
+ partResult = evaluateNFunc(trimmedPart, totalPages);
// Adjust the results according to the offset
for (int i = 0; i < partResult.size(); i++) {
int adjustedValue = partResult.get(i) - 1 + offset;
partResult.set(i, adjustedValue);
}
- } else if (part.contains("-")) {
+ } else if (trimmedPart.contains("-")) {
// Process ranges only if it's not n-syntax
- String[] rangeParts = part.split("-");
+ String[] rangeParts = trimmedPart.split("-");
try {
- int start = Integer.parseInt(rangeParts[0]);
+ int start = Integer.parseInt(rangeParts[0].trim());
int end =
- (rangeParts.length > 1 && !rangeParts[1].isEmpty())
- ? Integer.parseInt(rangeParts[1])
+ (rangeParts.length > 1 && !rangeParts[1].trim().isEmpty())
+ ? Integer.parseInt(rangeParts[1].trim())
: totalPages;
for (int i = start; i <= end; i++) {
if (i >= 1 && i <= totalPages) {
@@ -825,17 +830,17 @@ public class GeneralUtils {
}
}
} catch (NumberFormatException e) {
- log.debug("Invalid range: {}", part);
+ log.debug("Invalid range: {}", trimmedPart);
}
} else {
// This is a single page number
try {
- int pageNum = Integer.parseInt(part.trim());
+ int pageNum = Integer.parseInt(trimmedPart);
if (pageNum >= 1 && pageNum <= totalPages) {
partResult.add(pageNum - 1 + offset);
}
} catch (NumberFormatException e) {
- log.debug("Invalid page number: {}", part);
+ log.debug("Invalid page number: {}", trimmedPart);
}
}
return partResult;
diff --git a/app/common/src/test/java/stirling/software/common/util/GeneralUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/GeneralUtilsTest.java
index 90e20f7577..6dd0860e9a 100644
--- a/app/common/src/test/java/stirling/software/common/util/GeneralUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/GeneralUtilsTest.java
@@ -53,6 +53,14 @@ public class GeneralUtilsTest {
"premium", "proFeatures", "customMetadata", "author"));
}
+ @Test
+ void testParsePageListSkipsNullAndBlankTokens() {
+ List<Integer> result =
+ GeneralUtils.parsePageList(new String[] {null, "", "1 , 2 "}, 5, false);
+ assertEquals(
+ List.of(0, 1), result, "Null and blank tokens are ignored; parts are trimmed.");
+ }
+
@Test
void testParsePageListWithAll() {
List<Integer> result = GeneralUtils.parsePageList(new String[] {"all"}, 5, false);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
index 571bb42914..95daf28043 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
@@ -2,6 +2,8 @@ package stirling.software.SPDF.controller.api;
import java.awt.image.BufferedImage;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.BitSet;
import java.util.List;
import org.apache.pdfbox.multipdf.LayerUtility;
@@ -16,6 +18,7 @@ import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
@@ -129,6 +132,17 @@ public class CropController {
return endpointConfiguration.isGroupEnabled("Ghostscript");
}
+ private static BitSet pageSelection(CropPdfForm request, PDDocument document) {
+ BitSet selected = new BitSet(document.getNumberOfPages());
+ request.getPageNumbersList(document, false).forEach(selected::set);
+ String pageNumbers = request.getPageNumbers();
+ if (selected.isEmpty() && pageNumbers != null && !pageNumbers.isBlank()) {
+ throw new IllegalArgumentException(
+ "pageNumbers '" + pageNumbers + "' does not select any page");
+ }
+ return selected;
+ }
+
@AutoJobPostMapping(
value = "/crop",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -169,8 +183,15 @@ public class CropController {
PDFRenderer renderer = new PDFRenderer(sourceDocument);
renderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
LayerUtility layerUtility = new LayerUtility(newDocument);
+ BitSet pagesToCrop = pageSelection(request, sourceDocument);
for (int i = 0; i < sourceDocument.getNumberOfPages(); i++) {
+ if (!pagesToCrop.get(i)) {
+ PDPage imported = newDocument.importPage(sourceDocument.getPage(i));
+ imported.setResources(sourceDocument.getPage(i).getResources());
+ continue;
+ }
+
PDPage sourcePage = sourceDocument.getPage(i);
PDRectangle mediaBox = sourcePage.getMediaBox();
@@ -222,8 +243,15 @@ public class CropController {
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {
int totalPages = sourceDocument.getNumberOfPages();
LayerUtility layerUtility = new LayerUtility(newDocument);
+ BitSet pagesToCrop = pageSelection(request, sourceDocument);
for (int i = 0; i < totalPages; i++) {
+ if (!pagesToCrop.get(i)) {
+ PDPage imported = newDocument.importPage(sourceDocument.getPage(i));
+ imported.setResources(sourceDocument.getPage(i).getResources());
+ continue;
+ }
+
PDPage sourcePage = sourceDocument.getPage(i);
// Create a new page with the size of the source page
@@ -272,11 +300,13 @@ public class CropController {
private ResponseEntity<Resource> cropWithGhostscript(@ModelAttribute CropPdfForm request)
throws IOException {
- TempFile tempInputFile = null;
- TempFile tempOutputFile = null;
-
try (PDDocument sourceDocument = pdfDocumentFactory.load(request)) {
- for (int i = 0; i < sourceDocument.getNumberOfPages(); i++) {
+ BitSet pagesToCrop = pageSelection(request, sourceDocument);
+ int totalPages = sourceDocument.getNumberOfPages();
+ for (int i = 0; i < totalPages; i++) {
+ if (!pagesToCrop.get(i)) {
+ continue;
+ }
PDPage page = sourceDocument.getPage(i);
PDRectangle cropBox =
new PDRectangle(
@@ -287,13 +317,78 @@ public class CropController {
page.setCropBox(cropBox);
}
- tempInputFile = tempFileManager.createManagedTempFile(PDF_EXTENSION);
- tempOutputFile = tempFileManager.createManagedTempFile(PDF_EXTENSION);
+ MultipartFile fileInput = request.getFileInput();
+ String sourceName =
+ fileInput != null ? fileInput.getOriginalFilename() : request.getFileId();
+ String outputFilename = GeneralUtils.generateFilename(sourceName, "_cropped.pdf");
+
+ List<Integer> selected = new ArrayList<>();
+ for (int i = 0; i < totalPages; i++) {
+ if (pagesToCrop.get(i)) {
+ selected.add(i);
+ }
+ }
+
+ // Ghostscript only ever sees the selected pages: unselected pages
+ // merge back pristine, so a document-wide re-distill can never
+ // alter their geometry or content.
+ TempFile croppedFile = null;
+ PDDocument croppedDocument = null;
+ try {
+ if (!selected.isEmpty()) {
+ try (PDDocument selectedDocument = new PDDocument()) {
+ for (int pageIndex : selected) {
+ selectedDocument.importPage(sourceDocument.getPage(pageIndex));
+ }
+ croppedFile = runGhostscriptDocument(selectedDocument);
+ }
+ croppedDocument = org.apache.pdfbox.Loader.loadPDF(croppedFile.getFile());
+ if (croppedDocument.getNumberOfPages() != selected.size()) {
+ throw new IOException(
+ "Ghostscript returned "
+ + croppedDocument.getNumberOfPages()
+ + " pages for "
+ + selected.size()
+ + " selected pages");
+ }
+ }
+
+ try (PDDocument mergedDocument =
+ pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {
+ int ghostscriptIndex = 0;
+ for (int i = 0; i < totalPages; i++) {
+ if (pagesToCrop.get(i)) {
+ mergedDocument.importPage(croppedDocument.getPage(ghostscriptIndex++));
+ } else {
+ PDPage imported = mergedDocument.importPage(sourceDocument.getPage(i));
+ imported.setResources(sourceDocument.getPage(i).getResources());
+ }
+ }
+ return WebResponseUtils.pdfDocToWebResponse(
+ mergedDocument, outputFilename, tempFileManager);
+ } finally {
+ if (croppedDocument != null) {
+ croppedDocument.close();
+ }
+ }
+ } finally {
+ if (croppedFile != null) {
+ croppedFile.close();
+ }
+ }
+ }
+ }
- // Save the source document with crop boxes
- sourceDocument.save(tempInputFile.getFile());
+ /**
+ * Saves the given document and runs Ghostscript over it with the per-page crop boxes applied.
+ * The caller owns the returned file.
+ */
+ private TempFile runGhostscriptDocument(PDDocument document) throws IOException {
+ TempFile tempInputFile = tempFileManager.createManagedTempFile(PDF_EXTENSION);
+ TempFile tempOutputFile = tempFileManager.createManagedTempFile(PDF_EXTENSION);
+ try {
+ document.save(tempInputFile.getFile());
- // Execute Ghostscript to process the crop boxes
ProcessExecutor processExecutor =
ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT);
List<String> command =
@@ -304,23 +399,18 @@ public class CropController {
"-o",
tempOutputFile.getAbsolutePath(),
tempInputFile.getAbsolutePath());
-
- processExecutor.runCommandWithOutputHandling(command);
+ try {
+ processExecutor.runCommandWithOutputHandling(command);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw ExceptionUtils.createProcessingInterruptedException("Ghostscript", e);
+ }
TempFile out = tempOutputFile;
- tempOutputFile = null; // ownership transferred to response Resource
- return WebResponseUtils.pdfFileToWebResponse(
- out,
- GeneralUtils.generateFilename(
- request.getFileInput().getOriginalFilename(), "_cropped.pdf"));
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw ExceptionUtils.createProcessingInterruptedException("Ghostscript", e);
+ tempOutputFile = null; // ownership transferred to the caller
+ return out;
} finally {
- if (tempInputFile != null) {
- tempInputFile.close();
- }
+ tempInputFile.close();
if (tempOutputFile != null) {
tempOutputFile.close();
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java
index 16d10b9427..4ff2eed2ba 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java
@@ -1,15 +1,46 @@
package stirling.software.SPDF.model.api.general;
+import java.util.List;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+
+import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
-import stirling.software.common.model.api.PDFFile;
+import stirling.software.SPDF.model.api.PDFWithPageNums;
+import stirling.software.common.util.GeneralUtils;
@Data
@EqualsAndHashCode(callSuper = true)
-public class CropPdfForm extends PDFFile {
+public class CropPdfForm extends PDFWithPageNums {
+
+ // Legacy clients omit pageNumbers; keep them cropping every page rather than
+ // falling back to parsePageList's single-first-page default.
+ @Override
+ @Hidden
+ public List<Integer> getPageNumbersList(PDDocument doc, boolean oneBased) {
+ String pageNumbers = getPageNumbers();
+ return GeneralUtils.parsePageList(
+ (pageNumbers == null || pageNumbers.isBlank()) ? "all" : pageNumbers,
+ doc.getNumberOfPages(),
+ oneBased);
+ }
+
+ // The base model marks pageNumbers required, but this endpoint treats an
+ // omitted or blank value as "all" (see above): advertise it as optional so
+ // generated clients do not fail local validation for a legal request.
+ @Override
+ @Schema(
+ description =
+ "Pages to crop (e.g. '1, 3, 5-8' or 'all'). Omit or leave blank for all pages.",
+ defaultValue = "all",
+ requiredMode = Schema.RequiredMode.NOT_REQUIRED)
+ public String getPageNumbers() {
+ return super.getPageNumbers();
+ }
@Schema(
description = "The x-coordinate of the top-left corner of the crop area",
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java
index 4c5c3ed8d0..3ec1cda16a 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java
@@ -14,6 +14,8 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -139,12 +141,58 @@ class CropControllerMoreTest {
when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(true);
// Real document so setCropBox + save() succeed inside the gs branch.
when(pdfDocumentFactory.load(request)).thenReturn(Loader.loadPDF(file.getBytes()));
+ when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(any(PDDocument.class)))
+ .thenAnswer(invocation -> new PDDocument());
ProcessExecutor executor = mock(ProcessExecutor.class);
try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
pe.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT))
.thenReturn(executor);
- when(executor.runCommandWithOutputHandling(any())).thenReturn(null);
+ // Identity Ghostscript: the mock copies its input to the -o
+ // path so the merge step reads back a valid document.
+ when(executor.runCommandWithOutputHandling(any()))
+ .thenAnswer(
+ invocation -> {
+ List<String> command = invocation.getArgument(0);
+ Path in = Path.of(command.get(command.size() - 1));
+ Path out = Path.of(command.get(command.indexOf("-o") + 1));
+ Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
+ return null;
+ });
+
+ ResponseEntity<Resource> response = cropController.cropPdf(request);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ assertThat(response.getBody()).isNotNull();
+ verify(executor).runCommandWithOutputHandling(any());
+ }
+ }
+
+ @Test
+ @DisplayName("Ghostscript processes only selected pages and merges pristine originals")
+ void ghostscriptMergesUnselectedPagesPristine() throws Exception {
+ MockMultipartFile file = pdf(3);
+ CropPdfForm request = form(file, true);
+ request.setPageNumbers("2");
+
+ when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(true);
+ when(pdfDocumentFactory.load(request)).thenReturn(Loader.loadPDF(file.getBytes()));
+ when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(any(PDDocument.class)))
+ .thenAnswer(invocation -> new PDDocument());
+
+ ProcessExecutor executor = mock(ProcessExecutor.class);
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ pe.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT))
+ .thenReturn(executor);
+ when(executor.runCommandWithOutputHandling(any()))
+ .thenAnswer(
+ invocation -> {
+ List<String> command = invocation.getArgument(0);
+ Path in = Path.of(command.get(command.size() - 1));
+ Path out = Path.of(command.get(command.indexOf("-o") + 1));
+ Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
+ return null;
+ });
ResponseEntity<Resource> response = cropController.cropPdf(request);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java
index 9ef8669295..d02528e8a5 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java
@@ -103,6 +103,11 @@ class CropControllerTest {
return this;
}
+ CropRequestBuilder withPageNumbers(String pageNumbers) {
+ form.setPageNumbers(pageNumbers);
+ return this;
+ }
+
CropPdfForm build() {
return form;
}
@@ -120,6 +125,32 @@ class CropControllerTest {
return createPdf(filename, PDRectangle.LETTER, content);
}
+ MockMultipartFile createMultiPagePdf(String filename, int pages) throws IOException {
+ Path testPdfPath = tempDir.resolve(filename);
+
+ try (PDDocument doc = new PDDocument()) {
+ for (int i = 0; i < pages; i++) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+ try (PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
+ contentStream.beginText();
+ contentStream.setFont(HELVETICA, 12);
+ contentStream.newLineAtOffset(50, 50);
+ contentStream.showText("Page " + (i + 1));
+ contentStream.endText();
+ }
+ }
+
+ doc.save(testPdfPath.toFile());
+ }
+
+ return new MockMultipartFile(
+ "fileInput",
+ filename,
+ MediaType.APPLICATION_PDF_VALUE,
+ Files.readAllBytes(testPdfPath));
+ }
+
MockMultipartFile createPdfWithSize(String filename, PDRectangle size) throws IOException {
return createPdf(filename, size, null);
}
@@ -254,6 +285,28 @@ class CropControllerTest {
verify(mockDocument, times(1)).close();
verify(newDocument, times(1)).close();
}
+
+ @Test
+ @DisplayName("Should reject a page selection that matches no page")
+ void shouldRejectEmptyPageSelection() throws IOException {
+ MockMultipartFile testFile = pdfFactory.createStandardPdf("test.pdf");
+ CropPdfForm request =
+ new CropRequestBuilder()
+ .withFile(testFile)
+ .withCoordinates(50f, 50f, 512f, 692f)
+ .withRemoveDataOutsideCrop(false)
+ .withAutoCrop(false)
+ .withPageNumbers("9")
+ .build();
+
+ PDDocument mockDocument = mock(PDDocument.class);
+ when(mockDocument.getNumberOfPages()).thenReturn(3);
+ when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
+
+ assertThatThrownBy(() -> cropController.cropPdf(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("does not select any page");
+ }
}
@Nested
@@ -713,4 +766,86 @@ class CropControllerTest {
verify(newDocument, times(1)).close();
}
}
+
+ @Nested
+ @DisplayName("Page Selection")
+ @Tag("integration")
+ class SinglePageCropTests {
+
+ @Test
+ @DisplayName("Only the selected page is cropped; the rest keep their original size")
+ void shouldCropOnlySelectedPage() throws IOException {
+ MockMultipartFile testFile = pdfFactory.createMultiPagePdf("multi.pdf", 3);
+ CropPdfForm request =
+ new CropRequestBuilder()
+ .withFile(testFile)
+ .withCoordinates(50f, 50f, 300f, 400f)
+ .withPageNumbers("2")
+ .withRemoveDataOutsideCrop(false)
+ .withAutoCrop(false)
+ .build();
+
+ try (PDDocument sourceDoc = Loader.loadPDF(testFile.getBytes());
+ PDDocument newDoc = new PDDocument()) {
+ when(pdfDocumentFactory.load(request)).thenReturn(sourceDoc);
+ when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDoc))
+ .thenReturn(newDoc);
+
+ ResponseEntity<Resource> response = cropController.cropPdf(request);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ try (PDDocument result = Loader.loadPDF(drainBody(response))) {
+ assertThat(result.getNumberOfPages()).isEqualTo(3);
+
+ assertThat(result.getPage(0).getMediaBox().getWidth())
+ .isEqualTo(PDRectangle.LETTER.getWidth());
+ assertThat(result.getPage(0).getMediaBox().getHeight())
+ .isEqualTo(PDRectangle.LETTER.getHeight());
+
+ assertThat(result.getPage(1).getMediaBox().getWidth())
+ .isCloseTo(300f, within(0.01f));
+ assertThat(result.getPage(1).getMediaBox().getHeight())
+ .isCloseTo(400f, within(0.01f));
+
+ assertThat(result.getPage(2).getMediaBox().getWidth())
+ .isEqualTo(PDRectangle.LETTER.getWidth());
+ assertThat(result.getPage(2).getMediaBox().getHeight())
+ .isEqualTo(PDRectangle.LETTER.getHeight());
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("Legacy clients that omit pageNumbers still crop every page")
+ void shouldCropAllPagesWhenPageNumbersOmitted() throws IOException {
+ MockMultipartFile testFile = pdfFactory.createMultiPagePdf("multi.pdf", 3);
+ CropPdfForm request =
+ new CropRequestBuilder()
+ .withFile(testFile)
+ .withCoordinates(50f, 50f, 300f, 400f)
+ .withRemoveDataOutsideCrop(false)
+ .withAutoCrop(false)
+ .build();
+
+ try (PDDocument sourceDoc = Loader.loadPDF(testFile.getBytes());
+ PDDocument newDoc = new PDDocument()) {
+ when(pdfDocumentFactory.load(request)).thenReturn(sourceDoc);
+ when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDoc))
+ .thenReturn(newDoc);
+
+ ResponseEntity<Resource> response = cropController.cropPdf(request);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ try (PDDocument result = Loader.loadPDF(drainBody(response))) {
+ assertThat(result.getNumberOfPages()).isEqualTo(3);
+ for (int i = 0; i < result.getNumberOfPages(); i++) {
+ assertThat(result.getPage(i).getMediaBox().getWidth())
+ .isCloseTo(300f, within(0.01f));
+ assertThat(result.getPage(i).getMediaBox().getHeight())
+ .isCloseTo(400f, within(0.01f));
+ }
+ }
+ }
+ }
+ }
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java
index ad95b0def0..2cb2ce12bc 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java
@@ -2,6 +2,11 @@ package stirling.software.SPDF.model.api.general;
import static org.assertj.core.api.Assertions.assertThat;
+import java.io.IOException;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -16,6 +21,14 @@ class CropPdfFormTest {
"fileInput", "in.pdf", "application/pdf", new byte[] {1, 2, 3});
}
+ private static PDDocument threePageDoc() throws IOException {
+ PDDocument doc = new PDDocument();
+ for (int i = 0; i < 3; i++) {
+ doc.addPage(new PDPage(PDRectangle.LETTER));
+ }
+ return doc;
+ }
+
@Nested
@DisplayName("defaults")
class Defaults {
@@ -61,6 +74,52 @@ class CropPdfFormTest {
}
}
+ @Nested
+ @DisplayName("page selection")
+ class PageSelection {
+
+ @Test
+ @DisplayName("null pageNumbers falls back to every page")
+ void nullPageNumbersMeansAllPages() throws IOException {
+ try (PDDocument doc = threePageDoc()) {
+ CropPdfForm form = new CropPdfForm();
+ assertThat(form.getPageNumbers()).isNull();
+ assertThat(form.getPageNumbersList(doc, false)).containsExactly(0, 1, 2);
+ }
+ }
+
+ @Test
+ @DisplayName("blank pageNumbers falls back to every page")
+ void blankPageNumbersMeansAllPages() throws IOException {
+ try (PDDocument doc = threePageDoc()) {
+ CropPdfForm form = new CropPdfForm();
+ form.setPageNumbers(" ");
+ assertThat(form.getPageNumbersList(doc, false)).containsExactly(0, 1, 2);
+ }
+ }
+
+ @Test
+ @DisplayName("'all' expands to every page")
+ void allExpandsToEveryPage() throws IOException {
+ try (PDDocument doc = threePageDoc()) {
+ CropPdfForm form = new CropPdfForm();
+ form.setPageNumbers("all");
+ assertThat(form.getPageNumbersList(doc, false)).containsExactly(0, 1, 2);
+ }
+ }
+
+ @Test
+ @DisplayName("a single page number selects only that zero-based index")
+ void singlePageSelectsOneIndex() throws IOException {
+ try (PDDocument doc = threePageDoc()) {
+ CropPdfForm form = new CropPdfForm();
+ form.setPageNumbers("2");
+ assertThat(form.getPageNumbersList(doc, false)).containsExactly(1);
+ assertThat(form.getPageNumbersList(doc, true)).containsExactly(2);
+ }
+ }
+ }
+
@Nested
@DisplayName("equals/hashCode/toString")
class Equality {
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index 9d0cf5b6bb..ab065de083 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -437,6 +437,9 @@ class CropParams(ApiModel):
auto_crop: bool | None = Field(None, description="Enable auto-crop to detect and remove white space")
height: float | None = Field(None, description="The height of the crop area")
+ page_numbers: str = Field(
+ "all", description="Pages to crop (e.g. '1, 3, 5-8' or 'all'). Omit or leave blank for all pages."
+ )
remove_data_outside_crop: bool | None = Field(
None, description="Whether to remove text outside the crop area (keeps images)"
)
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 7b5dc50552..dfe655eba9 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4160,6 +4160,12 @@ label = "Y Position"
[crop.error]
failed = "Failed to crop PDF"
+[crop.pageNumbers]
+description = "Crop the selected area on specific pages, or 'all' for every page."
+error = "Invalid page selection. Use e.g. 1, 3, 5-8 or all."
+label = "Pages to Crop"
+placeholder = "e.g. 1, 3, 5-8 or all"
+
[crop.preview]
title = "Crop Area Selection"
diff --git a/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx b/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx
index 47cda328d8..c3b7559f2a 100644
--- a/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx
+++ b/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text } from "@mantine/core";
+import { useDebouncedValue } from "@mantine/hooks";
import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
import { parseSelectionWithDiagnostics } from "@app/utils/bulkselection/parseSelection";
@@ -21,9 +22,10 @@ const PageSelectionSyntaxHint = ({
}: PageSelectionSyntaxHintProps) => {
const [syntaxError, setSyntaxError] = useState<string | null>(null);
const { t } = useTranslation();
+ const [debouncedInput] = useDebouncedValue(input, 300);
useEffect(() => {
- const text = (input || "").trim();
+ const text = (debouncedInput || "").trim();
if (!text) {
setSyntaxError(null);
return;
@@ -50,7 +52,7 @@ const PageSelectionSyntaxHint = ({
),
);
}
- }, [input, maxPages]);
+ }, [debouncedInput, maxPages]);
if (!syntaxError) return null;
diff --git a/frontend/editor/src/core/components/tools/crop/CropAutomationSettings.tsx b/frontend/editor/src/core/components/tools/crop/CropAutomationSettings.tsx
index 54539ce1b3..fd82e90a83 100644
--- a/frontend/editor/src/core/components/tools/crop/CropAutomationSettings.tsx
+++ b/frontend/editor/src/core/components/tools/crop/CropAutomationSettings.tsx
@@ -9,6 +9,7 @@ import { Stack } from "@mantine/core";
import { CropParameters } from "@app/hooks/tools/crop/useCropParameters";
import { Rectangle } from "@app/utils/cropCoordinates";
import CropCoordinateInputs from "@app/components/tools/crop/CropCoordinateInputs";
+import CropPageSelection from "@app/components/tools/crop/CropPageSelection";
interface CropAutomationSettingsProps {
parameters: CropParameters;
@@ -38,6 +39,11 @@ const CropAutomationSettings = ({
return (
<Stack gap="md">
+ <CropPageSelection
+ value={parameters.pageNumbers ?? "all"}
+ onChange={(value) => onParameterChange("pageNumbers", value)}
+ disabled={disabled}
+ />
<CropCoordinateInputs
cropArea={parameters.cropArea}
onCoordinateChange={handleCoordinateChange}
diff --git a/frontend/editor/src/core/components/tools/crop/CropPageSelection.tsx b/frontend/editor/src/core/components/tools/crop/CropPageSelection.tsx
new file mode 100644
index 0000000000..c554290b2f
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/crop/CropPageSelection.tsx
@@ -0,0 +1,49 @@
+import { Stack, TextInput } from "@mantine/core";
+import { useDebouncedValue } from "@mantine/hooks";
+import { useTranslation } from "react-i18next";
+import { validatePageNumbers } from "@app/utils/pageSelection";
+
+interface CropPageSelectionProps {
+ value: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+}
+
+const CropPageSelection = ({
+ value,
+ onChange,
+ disabled = false,
+}: CropPageSelectionProps) => {
+ const { t } = useTranslation();
+ const [debouncedValue] = useDebouncedValue(value, 300);
+
+ const trimmed = (debouncedValue ?? "").trim();
+ const error =
+ trimmed.length > 0 && !validatePageNumbers(trimmed)
+ ? t(
+ "crop.pageNumbers.error",
+ "Invalid page selection. Use e.g. 1, 3, 5-8 or all.",
+ )
+ : undefined;
+
+ return (
+ <Stack gap="xs">
+ <TextInput
+ label={t("crop.pageNumbers.label", "Pages to Crop")}
+ description={t(
+ "crop.pageNumbers.description",
+ "Crop the selected area on specific pages, or 'all' for every page.",
+ )}
+ value={value}
+ onChange={(event) => onChange(event.currentTarget.value)}
+ placeholder={t("crop.pageNumbers.placeholder", "e.g. 1, 3, 5-8 or all")}
+ error={error}
+ spellCheck={false}
+ autoComplete="off"
+ disabled={disabled}
+ />
+ </Stack>
+ );
+};
+
+export default CropPageSelection;
diff --git a/frontend/editor/src/core/components/tools/crop/CropSettings.tsx b/frontend/editor/src/core/components/tools/crop/CropSettings.tsx
index 77e59b70f5..56a6529182 100644
--- a/frontend/editor/src/core/components/tools/crop/CropSettings.tsx
+++ b/frontend/editor/src/core/components/tools/crop/CropSettings.tsx
@@ -10,6 +10,7 @@ import {
} from "@app/hooks/tools/shared/useViewScopedFiles";
import CropAreaSelector from "@app/components/tools/crop/CropAreaSelector";
import CropCoordinateInputs from "@app/components/tools/crop/CropCoordinateInputs";
+import CropPageSelection from "@app/components/tools/crop/CropPageSelection";
import { DEFAULT_CROP_AREA } from "@app/constants/cropConstants";
import { PAGE_SIZES } from "@app/constants/pageSizeConstants";
import {
@@ -157,6 +158,12 @@ const CropSettings = ({ parameters, disabled = false }: CropSettingsProps) => {
return (
<Stack gap="md" data-tour="crop-settings">
+ <CropPageSelection
+ value={parameters.parameters.pageNumbers}
+ onChange={(value) => parameters.updateParameter("pageNumbers", value)}
+ disabled={disabled}
+ />
+
{/* Auto-Crop Checkbox */}
<Checkbox
label={t("crop.autoCrop", "Auto-crop whitespace")}
diff --git a/frontend/editor/src/core/hooks/tools/crop/useCropOperation.test.ts b/frontend/editor/src/core/hooks/tools/crop/useCropOperation.test.ts
index 806ad40af0..f2e794294e 100644
--- a/frontend/editor/src/core/hooks/tools/crop/useCropOperation.test.ts
+++ b/frontend/editor/src/core/hooks/tools/crop/useCropOperation.test.ts
@@ -20,6 +20,13 @@ describe("crop mappers", () => {
cropArea: { x: 10, y: 20, width: 300, height: 400 },
},
},
+ {
+ label: "single page selection",
+ overrides: {
+ pageNumbers: "3",
+ cropArea: { x: 5, y: 5, width: 100, height: 200 },
+ },
+ },
])("round-trips backend params ($label)", ({ overrides }) => {
const api = cropToApiParams({ ...defaultParameters, ...overrides });
const roundTripped = cropToApiParams({
diff --git a/frontend/editor/src/core/hooks/tools/crop/useCropOperation.ts b/frontend/editor/src/core/hooks/tools/crop/useCropOperation.ts
index 287980ec03..7274b45720 100644
--- a/frontend/editor/src/core/hooks/tools/crop/useCropOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/crop/useCropOperation.ts
@@ -25,6 +25,7 @@ type CropApiParams = ToolApiParams[typeof ENDPOINT];
export const cropToApiParams = (parameters: CropParameters): CropApiParams => {
const apiParams: CropApiParams = {
autoCrop: parameters.autoCrop,
+ pageNumbers: parameters.pageNumbers,
};
if (!parameters.autoCrop) {
@@ -44,6 +45,7 @@ export const cropFromApiParams = (
apiParams: CropApiParams,
): Partial<CropParameters> => ({
autoCrop: apiParams.autoCrop ?? defaultParameters.autoCrop,
+ pageNumbers: apiParams.pageNumbers ?? defaultParameters.pageNumbers,
cropArea: {
x: apiParams.x ?? DEFAULT_CROP_AREA.x,
y: apiParams.y ?? DEFAULT_CROP_AREA.y,
diff --git a/frontend/editor/src/core/hooks/tools/crop/useCropParameters.test.ts b/frontend/editor/src/core/hooks/tools/crop/useCropParameters.test.ts
new file mode 100644
index 0000000000..e1e784b116
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/crop/useCropParameters.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test } from "vitest";
+import {
+ defaultParameters,
+ validateCropParameters,
+} from "@app/hooks/tools/crop/useCropParameters";
+
+describe("validateCropParameters", () => {
+ test("accepts 'all' and valid ranges with a valid crop area", () => {
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "all",
+ }),
+ ).toBe(true);
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "1,3,5-8",
+ }),
+ ).toBe(true);
+ });
+
+ test("rejects invalid page syntax", () => {
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "abc",
+ }),
+ ).toBe(false);
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "2--3",
+ }),
+ ).toBe(false);
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "",
+ }),
+ ).toBe(false);
+ });
+
+ test("accepts open-range syntax", () => {
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "2-",
+ }),
+ ).toBe(true);
+ });
+
+ test("still validates the crop area independently of pages", () => {
+ expect(
+ validateCropParameters({
+ ...defaultParameters,
+ pageNumbers: "all",
+ cropArea: { x: 0, y: 0, width: 0, height: 100 },
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/hooks/tools/crop/useCropParameters.ts b/frontend/editor/src/core/hooks/tools/crop/useCropParameters.ts
index 62e7ede14b..a2ad942181 100644
--- a/frontend/editor/src/core/hooks/tools/crop/useCropParameters.ts
+++ b/frontend/editor/src/core/hooks/tools/crop/useCropParameters.ts
@@ -14,15 +14,19 @@ import {
isRectangle,
} from "@app/utils/cropCoordinates";
import { DEFAULT_CROP_AREA } from "@app/constants/cropConstants";
+import { validatePageNumbers } from "@app/utils/pageSelection";
export interface CropParameters extends BaseParameters {
cropArea: Rectangle;
autoCrop: boolean;
+ /** Pages to crop, e.g. "3", "1,3,5-8" or "all" */
+ pageNumbers: string;
}
export const defaultParameters: CropParameters = {
cropArea: DEFAULT_CROP_AREA,
autoCrop: false,
+ pageNumbers: "all",
};
export type CropParametersHook = BaseParametersHook<CropParameters> & {
@@ -50,7 +54,13 @@ export type CropParametersHook = BaseParametersHook<CropParameters> & {
export function validateCropParameters(params: CropParameters): boolean {
const rect = params.cropArea;
// Basic validation - coordinates and dimensions must be positive
- return rect.x >= 0 && rect.y >= 0 && rect.width > 0 && rect.height > 0;
+ return (
+ rect.x >= 0 &&
+ rect.y >= 0 &&
+ rect.width > 0 &&
+ rect.height > 0 &&
+ validatePageNumbers(params.pageNumbers)
+ );
}
export const useCropParameters = (): CropParametersHook => {
diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.ts
index 8688d7ef3a..d857afaccd 100644
--- a/frontend/editor/src/core/types/toolApiTypes.ts
+++ b/frontend/editor/src/core/types/toolApiTypes.ts
@@ -421,6 +421,10 @@ export interface CropPdfForm {
* The height of the crop area
*/
height?: number;
+ /**
+ * Pages to crop (e.g. '1, 3, 5-8' or 'all'). Omit or leave blank for all pages.
+ */
+ pageNumbers?: string;
/**
* Whether to remove text outside the crop area (keeps images)
*/
diff --git a/frontend/editor/src/core/utils/bulkselection/parseSelection.test.ts b/frontend/editor/src/core/utils/bulkselection/parseSelection.test.ts
index 29c7dfb014..a7ebf48c97 100644
--- a/frontend/editor/src/core/utils/bulkselection/parseSelection.test.ts
+++ b/frontend/editor/src/core/utils/bulkselection/parseSelection.test.ts
@@ -28,6 +28,15 @@ describe("parseSelection", () => {
expect(parseSelection("odd", 10)).toEqual([1, 3, 5, 7, 9]);
});
+ it("6b) supports all keyword (case-insensitive)", () => {
+ expect(parseSelection("all", 5)).toEqual([1, 2, 3, 4, 5]);
+ expect(parseSelection("ALL", 3)).toEqual([1, 2, 3]);
+ });
+
+ it("6c) all in combination selects the full range", () => {
+ expect(parseSelection("all & even", 6)).toEqual([2, 4, 6]);
+ });
+
it("7) supports 2n progression", () => {
expect(parseSelection("2n", 12)).toEqual([2, 4, 6, 8, 10, 12]);
});
diff --git a/frontend/editor/src/core/utils/bulkselection/parseSelection.ts b/frontend/editor/src/core/utils/bulkselection/parseSelection.ts
index ed8b356651..f8d848cf88 100644
--- a/frontend/editor/src/core/utils/bulkselection/parseSelection.ts
+++ b/frontend/editor/src/core/utils/bulkselection/parseSelection.ts
@@ -10,7 +10,7 @@
primary := "(" expression ")" | range | progression | keyword | number
range := number "-" number // inclusive
progression := k ["*"] "n" (("+" | "-") c)? // k >= 1, c any integer, n starts at 0
- keyword := "even" | "odd"
+ keyword := "even" | "odd" | "all"
number := digits (>= 1)
Precedence: "!" (NOT) > "&"/"and" (AND) > "," "|" "or" (OR)
@@ -206,11 +206,12 @@ class ExpressionParser {
return inner;
}
- // Keywords: even / odd
+ // Keywords: even / odd / all
const keyword = this.tryReadKeyword();
if (keyword) {
if (keyword === "even") return this.buildEven();
if (keyword === "odd") return this.buildOdd();
+ if (keyword === "all") return this.buildAll();
}
// Progression: k n ( +/- c )?
@@ -275,12 +276,18 @@ class ExpressionParser {
return this.buildProgression(2, -1);
}
- private tryReadKeyword(): "even" | "odd" | null {
+ private buildAll(): Set<number> {
+ const set = new Set<number>();
+ for (let i = 1; i <= this.max; i++) set.add(i);
+ return set;
+ }
+
+ private tryReadKeyword(): "even" | "odd" | "all" | null {
const start = this.idx;
const word = this.readWord();
if (!word) return null;
const lower = word.toLowerCase();
- if (lower === "even" || lower === "odd") {
+ if (lower === "even" || lower === "odd" || lower === "all") {
return lower;
}
// Not a keyword; rewind
diff --git a/testing/cucumber/features/general_new.feature b/testing/cucumber/features/general_new.feature
index cd25b09650..6d0b31c4c6 100644
--- a/testing/cucumber/features/general_new.feature
+++ b/testing/cucumber/features/general_new.feature
@@ -155,6 +155,45 @@ Feature: General PDF Operations API Validation
And the response PDF should contain 1 pages
+ @crop @positive
+ Scenario: crop only the selected page and keep the others
+ Given I generate a PDF file as "fileInput"
+ And the pdf contains 3 pages
+ And the request data includes
+ | parameter | value |
+ | x | 0 |
+ | y | 0 |
+ | width | 50 |
+ | height | 50 |
+ | pageNumbers | 2 |
+ When I send the API request to the endpoint "/api/v1/general/crop"
+ Then the response content type should be "application/pdf"
+ And the response status code should be 200
+ And the response PDF should contain 3 pages
+ And the response PDF page 1 should have width 612 and height 792
+ And the response PDF page 2 should have width 50 and height 50
+ And the response PDF page 3 should have width 612 and height 792
+
+
+ @crop @positive
+ Scenario: legacy requests without pageNumbers crop every page
+ Given I generate a PDF file as "fileInput"
+ And the pdf contains 3 pages
+ And the request data includes
+ | parameter | value |
+ | x | 0 |
+ | y | 0 |
+ | width | 50 |
+ | height | 50 |
+ When I send the API request to the endpoint "/api/v1/general/crop"
+ Then the response content type should be "application/pdf"
+ And the response status code should be 200
+ And the response PDF should contain 3 pages
+ And the response PDF page 1 should have width 50 and height 50
+ And the response PDF page 2 should have width 50 and height 50
+ And the response PDF page 3 should have width 50 and height 50
+
+
@pdf-to-single-page @positive
Scenario: pdf-to-single-page combines all pages into one long page
Given I generate a PDF file as "fileInput"
diff --git a/testing/cucumber/features/steps/step_definitions.py b/testing/cucumber/features/steps/step_definitions.py
index 392e7c284d..e21f4ab9eb 100644
--- a/testing/cucumber/features/steps/step_definitions.py
+++ b/testing/cucumber/features/steps/step_definitions.py
@@ -762,6 +762,23 @@ def step_check_response_pdf_page_count(context, page_count):
), f"Expected {page_count} pages but got {actual_page_count} pages"
+@then(
+ "the response PDF page {page_number:d} should have width {width:d} and height {height:d}"
+)
+def step_check_response_pdf_page_size(context, page_number, width, height):
+ response_file = io.BytesIO(context.response.content)
+ reader = PdfReader(io.BytesIO(response_file.getvalue()))
+ page = reader.pages[page_number - 1]
+ actual_width = float(page.mediabox.width)
+ actual_height = float(page.mediabox.height)
+ assert (
+ abs(actual_width - width) < 0.5
+ ), f"Expected page {page_number} width {width} but got {actual_width}"
+ assert (
+ abs(actual_height - height) < 0.5
+ ), f"Expected page {page_number} height {height} but got {actual_height}"
+
+
@then("the response ZIP should contain {file_count:d} files")
def step_check_response_zip_file_count(context, file_count):
response_file = io.BytesIO(context.response.content)