Skip to content

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

Add Auto Rotate tool that detects and fixes page orientation (#7152)

ConnorYoh46865cd1543d
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
index a154ed2a7a..ff1a880010 100644
--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
@@ -338,6 +338,7 @@ public class EndpointConfiguration {
addEndpointToGroup("PageOps", "split-pages");
addEndpointToGroup("PageOps", "rearrange-pages");
addEndpointToGroup("PageOps", "rotate-pdf");
+ addEndpointToGroup("PageOps", "auto-rotate-pdf");
addEndpointToGroup("PageOps", "multi-page-layout");
addEndpointToGroup("PageOps", "booklet-imposition");
addEndpointToGroup("PageOps", "scale-pages");
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
new file mode 100644
index 0000000000..21a5885c7d
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
@@ -0,0 +1,385 @@
+package stirling.software.SPDF.controller.api.misc;
+
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import javax.imageio.ImageIO;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.rendering.ImageType;
+import org.apache.pdfbox.rendering.PDFRenderer;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ModelAttribute;
+
+import io.swagger.v3.oas.annotations.Operation;
+
+import jakarta.validation.Valid;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.SPDF.model.api.misc.AutoRotateAnalysisResult;
+import stirling.software.SPDF.model.api.misc.AutoRotateAnalysisResult.PageResult;
+import stirling.software.SPDF.model.api.misc.AutoRotatePdfRequest;
+import stirling.software.SPDF.model.api.misc.PageRotation;
+import stirling.software.SPDF.utils.AutoRotateDetection;
+import stirling.software.SPDF.utils.AutoRotateDetection.OsdResult;
+import stirling.software.SPDF.utils.AutoRotateDetection.TextDirection;
+import stirling.software.common.annotations.AutoJobPostMapping;
+import stirling.software.common.annotations.api.MiscApi;
+import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.enumeration.ResourceWeight;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+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.TempDirectory;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.WebResponseUtils;
+
+@MiscApi
+@Slf4j
+@RequiredArgsConstructor
+public class AutoRotateController {
+
+ // OSD decides orientation from script shape, not character identity, so it does not need
+ // OCR-grade resolution. 150 DPI is ample for that and a quarter of the pixels of 300.
+ private static final int OSD_RENDER_DPI = 150;
+
+ private static final String METHOD_TEXT = "text";
+ private static final String METHOD_OSD = "osd";
+ private static final String METHOD_INFERRED = "inferred";
+ private static final String METHOD_NONE = "none";
+
+ private final CustomPDFDocumentFactory pdfDocumentFactory;
+ private final TempFileManager tempFileManager;
+ private final EndpointConfiguration endpointConfiguration;
+ private final RuntimePathConfig runtimePathConfig;
+ private final ApplicationProperties applicationProperties;
+
+ @AutoJobPostMapping(
+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
+ value = "/auto-rotate-pdf",
+ resourceWeight = ResourceWeight.LARGE_WEIGHT)
+ @Operation(
+ summary = "Detect and fix the orientation of every page",
+ description =
+ "Detects each page's orientation (embedded-text direction first, Tesseract OSD"
+ + " for scanned pages) and sets the page rotation so the content"
+ + " displays upright. With dryRun=true, returns a JSON per-page report"
+ + " instead of the PDF. With pageRotations set, applies the given"
+ + " corrections without running detection."
+ + " Input:PDF Output:PDF Type:SISO")
+ public ResponseEntity<?> autoRotatePdf(@Valid @ModelAttribute AutoRotatePdfRequest request)
+ throws IOException, InterruptedException {
+ String mode =
+ request.getDetectionMode() == null
+ ? "auto"
+ : request.getDetectionMode().toLowerCase(Locale.ROOT);
+ if (!"auto".equals(mode) && !"text".equals(mode) && !"osd".equals(mode)) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "detectionMode",
+ "must be one of auto, text, osd");
+ }
+
+ try (PDDocument document = pdfDocumentFactory.load(request)) {
+ if (request.getPageRotations() != null && !request.getPageRotations().isEmpty()) {
+ applyExplicitRotations(document, request.getPageRotations());
+ return pdfResponse(document, request);
+ }
+
+ AutoRotateAnalysisResult analysis = analyse(document, mode, request);
+ if (request.isDryRun()) {
+ return ResponseEntity.ok(analysis);
+ }
+ for (PageResult pageResult : analysis.getPages()) {
+ if (pageResult.isApply()) {
+ PDPage page = document.getPage(pageResult.getPageNumber() - 1);
+ page.setRotation(
+ Math.floorMod(page.getRotation() + pageResult.getCorrection(), 360));
+ }
+ }
+ return pdfResponse(document, request);
+ }
+ }
+
+ private AutoRotateAnalysisResult analyse(
+ PDDocument document, String mode, AutoRotatePdfRequest request)
+ throws IOException, InterruptedException {
+ double threshold =
+ request.getConfidenceThreshold() == null ? 14.0 : request.getConfidenceThreshold();
+ boolean tesseractAvailable = endpointConfiguration.isGroupEnabled("tesseract");
+ boolean useText = !"osd".equals(mode);
+ boolean useOsd = !"text".equals(mode);
+
+ List<PageResult> results = new ArrayList<>();
+ List<Integer> osdCandidates = new ArrayList<>();
+
+ int pageCount = document.getNumberOfPages();
+ // One walk of the document for all pages, rather than one walk per page.
+ List<TextDirection> textDirections =
+ useText ? AutoRotateDetection.detectTextDirections(document) : List.of();
+
+ for (int i = 0; i < pageCount; i++) {
+ int currentRotation = Math.floorMod(document.getPage(i).getRotation(), 360);
+ PageResult result =
+ PageResult.builder()
+ .pageNumber(i + 1)
+ .currentRotation(currentRotation)
+ .method(METHOD_NONE)
+ .build();
+
+ if (useText) {
+ TextDirection direction = textDirections.get(i);
+ if (direction.isConclusive()) {
+ int correction =
+ AutoRotateDetection.correctionFromTextDirection(
+ direction.dominantDirection(), currentRotation);
+ result.setMethod(METHOD_TEXT);
+ result.setCorrection(correction);
+ result.setConfidence(direction.dominance() * 100);
+ result.setApply(correction != 0);
+ } else if (!useOsd) {
+ result.setNote(
+ direction.glyphCount() < AutoRotateDetection.MIN_GLYPHS
+ ? "tooFewGlyphs"
+ : "noDominantDirection");
+ }
+ }
+
+ if (useOsd && METHOD_NONE.equals(result.getMethod())) {
+ if (tesseractAvailable) {
+ osdCandidates.add(i);
+ } else {
+ result.setNote("tesseractUnavailable");
+ }
+ }
+ results.add(result);
+ }
+
+ if (!osdCandidates.isEmpty()) {
+ runOsdOnPages(document, osdCandidates, results, threshold);
+ }
+
+ if (request.isInferUndetected()) {
+ inferUndetectedPages(results);
+ }
+
+ return summarise(results, pageCount);
+ }
+
+ /**
+ * Fill in pages that no signal could decide, using the pages that could. When every decided
+ * page sharing an undecided page's current rotation agrees on one correction, that correction
+ * is the document's consensus for that rotation and is applied to the undecided page. This is
+ * the common "whole document rotated uniformly, but a cover or near-blank page has too little
+ * text to detect on its own" case. If decided pages disagree, nothing is inferred.
+ */
+ private void inferUndetectedPages(List<PageResult> results) {
+ // rotation -> the single agreed correction, or null once a conflict is seen
+ Map<Integer, Integer> consensus = new HashMap<>();
+ Set<Integer> conflicted = new HashSet<>();
+ for (PageResult result : results) {
+ if (METHOD_NONE.equals(result.getMethod())) {
+ continue;
+ }
+ int rotation = result.getCurrentRotation();
+ if (conflicted.contains(rotation)) {
+ continue;
+ }
+ Integer existing = consensus.get(rotation);
+ if (existing == null) {
+ consensus.put(rotation, result.getCorrection());
+ } else if (existing != result.getCorrection()) {
+ conflicted.add(rotation);
+ consensus.remove(rotation);
+ }
+ }
+
+ for (PageResult result : results) {
+ if (!METHOD_NONE.equals(result.getMethod())) {
+ continue;
+ }
+ Integer correction = consensus.get(result.getCurrentRotation());
+ if (correction == null) {
+ continue;
+ }
+ result.setMethod(METHOD_INFERRED);
+ result.setCorrection(correction);
+ result.setConfidence(null);
+ result.setApply(correction != 0);
+ result.setNote("inferredFromDocument");
+ }
+ }
+
+ private void runOsdOnPages(
+ PDDocument document,
+ List<Integer> pageIndexes,
+ List<PageResult> results,
+ double threshold)
+ throws IOException, InterruptedException {
+ String tessDataPath = runtimePathConfig.getTessDataPath();
+ boolean haveOsdData =
+ tessDataPath != null && new File(tessDataPath, "osd.traineddata").exists();
+
+ int dpi = OSD_RENDER_DPI;
+ if (applicationProperties != null && applicationProperties.getSystem() != null) {
+ dpi = Math.min(OSD_RENDER_DPI, applicationProperties.getSystem().getMaxDPI());
+ }
+ final int renderDpi = dpi;
+
+ try (TempDirectory tempDir = new TempDirectory(tempFileManager)) {
+ PDFRenderer renderer = new PDFRenderer(document);
+ renderer.setSubsamplingAllowed(true);
+ // One reused path, deleted after every page: the images are throwaway input for
+ // Tesseract, so a long document must not accumulate one file per page on disk.
+ File imageFile = new File(tempDir.getPath().toFile(), "osd-page.bmp");
+
+ for (int pageIndex : pageIndexes) {
+ PageResult result = results.get(pageIndex);
+ try {
+ // Rendering honours the page's current /Rotate, so OSD sees the page exactly
+ // as a viewer would and its verdict is always an additive correction.
+ BufferedImage image =
+ ExceptionUtils.handleOomRendering(
+ pageIndex + 1,
+ renderDpi,
+ () ->
+ renderer.renderImageWithDPI(
+ pageIndex, renderDpi, ImageType.GRAY));
+
+ if (AutoRotateDetection.isBlankRender(image)) {
+ // Nothing for OSD to read; skip the process spawn entirely.
+ result.setNote("blankPage");
+ continue;
+ }
+
+ // BMP, not PNG: the file is deleted straight after Tesseract reads it, so
+ // paying for compression only to discard the result is wasted work.
+ ImageIO.write(image, "bmp", imageFile);
+
+ List<String> command = new ArrayList<>();
+ command.add("tesseract");
+ command.add(imageFile.getAbsolutePath());
+ command.add("stdout");
+ command.add("--psm");
+ command.add("0");
+ if (haveOsdData) {
+ command.add("--tessdata-dir");
+ command.add(tessDataPath);
+ }
+
+ ProcessExecutorResult processResult =
+ ProcessExecutor.getInstance(ProcessExecutor.Processes.TESSERACT)
+ .runCommandWithOutputHandling(command);
+
+ Optional<OsdResult> osd =
+ AutoRotateDetection.parseOsd(processResult.getMessages());
+ if (osd.isEmpty()) {
+ result.setNote("osdNoVerdict");
+ continue;
+ }
+ result.setConfidence(osd.get().confidence());
+ result.setCorrection(osd.get().rotate());
+ if (osd.get().confidence() >= threshold) {
+ result.setMethod(METHOD_OSD);
+ result.setApply(osd.get().rotate() != 0);
+ } else {
+ result.setNote("belowThreshold");
+ }
+ } catch (IOException e) {
+ // Textless pages make Tesseract exit non-zero; skip, never guess.
+ log.debug("OSD failed for page {}: {}", pageIndex + 1, e.getMessage());
+ result.setNote("osdFailed");
+ } finally {
+ Files.deleteIfExists(imageFile.toPath());
+ }
+ }
+ }
+ }
+
+ private void applyExplicitRotations(PDDocument document, List<PageRotation> rotations) {
+ int pageCount = document.getNumberOfPages();
+ Set<Integer> seen = new HashSet<>();
+ for (PageRotation entry : rotations) {
+ Integer pageNumber = entry.getPageNumber();
+ Integer angle = entry.getRotation();
+ if (pageNumber == null
+ || angle == null
+ || pageNumber < 1
+ || pageNumber > pageCount
+ || angle % 90 != 0) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "pageRotations",
+ "page numbers must exist and rotations must be multiples of 90");
+ }
+ // Rotations are additive, so a repeated page would be turned twice; reject rather
+ // than silently pick a winner.
+ if (!seen.add(pageNumber)) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "pageRotations",
+ "page " + pageNumber + " is listed more than once");
+ }
+ PDPage page = document.getPage(pageNumber - 1);
+ page.setRotation(Math.floorMod(page.getRotation() + angle, 360));
+ }
+ }
+
+ private AutoRotateAnalysisResult summarise(List<PageResult> results, int pageCount) {
+ int toRotate = 0;
+ int byText = 0;
+ int byOsd = 0;
+ int byInference = 0;
+ int undetected = 0;
+ for (PageResult result : results) {
+ if (result.isApply()) {
+ toRotate++;
+ }
+ switch (result.getMethod()) {
+ case METHOD_TEXT -> byText++;
+ case METHOD_OSD -> byOsd++;
+ case METHOD_INFERRED -> byInference++;
+ default -> undetected++;
+ }
+ }
+ return AutoRotateAnalysisResult.builder()
+ .pages(results)
+ .totalPages(pageCount)
+ .pagesToRotate(toRotate)
+ .detectedByText(byText)
+ .detectedByOsd(byOsd)
+ .inferred(byInference)
+ .undetected(undetected)
+ .build();
+ }
+
+ private ResponseEntity<?> pdfResponse(PDDocument document, AutoRotatePdfRequest request)
+ throws IOException {
+ String originalName =
+ request.getFileInput() != null
+ ? request.getFileInput().getOriginalFilename()
+ : "document.pdf";
+ return WebResponseUtils.pdfDocToWebResponse(
+ document,
+ GeneralUtils.generateFilename(originalName, "_auto_rotated.pdf"),
+ tempFileManager);
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoRotateAnalysisResult.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoRotateAnalysisResult.java
new file mode 100644
index 0000000000..375e4eb646
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoRotateAnalysisResult.java
@@ -0,0 +1,73 @@
+package stirling.software.SPDF.model.api.misc;
+
+import java.util.List;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/** Per-page orientation report returned by auto-rotate-pdf when dryRun is set. */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class AutoRotateAnalysisResult {
+
+ private List<PageResult> pages;
+
+ private int totalPages;
+
+ @Schema(description = "Number of pages a correction would be applied to")
+ private int pagesToRotate;
+
+ private int detectedByText;
+
+ private int detectedByOsd;
+
+ @Schema(description = "Pages whose correction was inherited from the document consensus")
+ private int inferred;
+
+ private int undetected;
+
+ @Data
+ @Builder
+ @NoArgsConstructor
+ @AllArgsConstructor
+ public static class PageResult {
+
+ @Schema(description = "1-based page number")
+ private int pageNumber;
+
+ @Schema(description = "The page's current /Rotate value, normalised to 0-270")
+ private int currentRotation;
+
+ @Schema(
+ description =
+ "Detected additional clockwise rotation that would make the page upright."
+ + " Reported for diagnostics even when it is not used (for example"
+ + " an OSD verdict below the confidence threshold); 'apply' is the"
+ + " authority on whether it is actually applied")
+ private int correction;
+
+ @Schema(
+ description =
+ "Detection confidence: percentage of glyphs sharing the dominant direction"
+ + " for method 'text', Tesseract orientation confidence for method"
+ + " 'osd', absent when nothing was detected")
+ private Double confidence;
+
+ @Schema(
+ description = "How the orientation was determined",
+ allowableValues = {"text", "osd", "inferred", "none"})
+ private String method;
+
+ @Schema(description = "Whether the correction will be (or was) applied")
+ private boolean apply;
+
+ @Schema(description = "Machine-readable reason when no correction is applied")
+ private String note;
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoRotatePdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoRotatePdfRequest.java
new file mode 100644
index 0000000000..9994b033e6
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoRotatePdfRequest.java
@@ -0,0 +1,58 @@
+package stirling.software.SPDF.model.api.misc;
+
+import java.util.List;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.Min;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+import stirling.software.common.model.api.PDFFile;
+
+@Data
+@EqualsAndHashCode(callSuper = true)
+public class AutoRotatePdfRequest extends PDFFile {
+
+ @Schema(
+ description =
+ "Detection method. 'auto' tries embedded-text direction first and falls back"
+ + " to Tesseract OSD for pages without usable text; 'text' uses only"
+ + " embedded-text direction; 'osd' forces Tesseract OSD for every page",
+ allowableValues = {"auto", "text", "osd"},
+ defaultValue = "auto")
+ private String detectionMode = "auto";
+
+ @Schema(
+ description =
+ "Minimum Tesseract OSD orientation confidence required before a correction is"
+ + " applied. Matches OCRmyPDF's --rotate-pages-threshold scale",
+ minimum = "0",
+ defaultValue = "14.0")
+ @Min(value = 0, message = "Confidence threshold must be non-negative")
+ private Double confidenceThreshold = 14.0;
+
+ @Schema(
+ description =
+ "If true, no rotation is applied; returns a JSON report of the per-page"
+ + " detection results instead of a PDF")
+ private boolean dryRun;
+
+ @Schema(
+ description =
+ "When a page cannot be decided on its own but the pages that could be decided"
+ + " agree on a single correction for that same current rotation, apply"
+ + " that shared correction to the undecided page. Handles documents"
+ + " rotated uniformly where some pages are too sparse to detect alone",
+ defaultValue = "true")
+ private boolean inferUndetected = true;
+
+ @Schema(
+ description =
+ "Optional pre-computed corrections to apply without running detection. Pages"
+ + " not listed are left unchanged, and a page may only appear once")
+ @Valid
+ private List<PageRotation> pageRotations;
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/PageRotation.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/PageRotation.java
new file mode 100644
index 0000000000..dbdbee7de7
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/PageRotation.java
@@ -0,0 +1,28 @@
+package stirling.software.SPDF.model.api.misc;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/** A pre-computed rotation for one page, used by auto-rotate-pdf's apply-only path. */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class PageRotation {
+
+ @Schema(
+ description = "1-based page number to rotate",
+ requiredMode = Schema.RequiredMode.REQUIRED,
+ example = "1")
+ private Integer pageNumber;
+
+ @Schema(
+ description =
+ "Additional clockwise rotation to add to the page's current rotation, in"
+ + " degrees. Must be a multiple of 90",
+ requiredMode = Schema.RequiredMode.REQUIRED,
+ example = "90")
+ private Integer rotation;
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/utils/AutoRotateDetection.java b/app/core/src/main/java/stirling/software/SPDF/utils/AutoRotateDetection.java
new file mode 100644
index 0000000000..825705d9bd
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/utils/AutoRotateDetection.java
@@ -0,0 +1,189 @@
+package stirling.software.SPDF.utils;
+
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.text.PDFTextStripper;
+import org.apache.pdfbox.text.TextPosition;
+
+/**
+ * Page-orientation detection primitives for the auto-rotate tool.
+ *
+ * <p>Two independent signals are supported: the dominant direction of a page's embedded text
+ * (cheap, digital PDFs only) and Tesseract's orientation-and-script-detection output (works on
+ * scans, requires the external binary). Both express their result as the additional clockwise
+ * /Rotate correction that makes the page display upright.
+ */
+public final class AutoRotateDetection {
+
+ private AutoRotateDetection() {}
+
+ /** Glyphs needed to trust the text signal at the ordinary dominance bar. */
+ public static final int MIN_GLYPHS = 30;
+
+ /** Fraction of glyphs that must share one direction at the ordinary bar. */
+ public static final double MIN_DOMINANCE = 0.95;
+
+ /**
+ * Glyphs needed to trust the text signal when the glyphs are near-unanimous. Lets sparse pages
+ * (a header, a single line, a rotated URL) be decided from their own text instead of falling
+ * through to OSD, as long as effectively every glyph agrees on the direction.
+ */
+ public static final int MIN_GLYPHS_UNANIMOUS = 8;
+
+ /** Dominance required for the sparse-page path — essentially total agreement. */
+ public static final double UNANIMOUS_DOMINANCE = 0.99;
+
+ /**
+ * Dominant embedded-text direction of one page.
+ *
+ * @param dominantDirection glyph direction in page space, degrees CCW (0/90/180/270)
+ * @param dominance fraction of counted glyphs sharing the dominant direction (0..1)
+ * @param glyphCount number of non-whitespace glyphs counted
+ */
+ public record TextDirection(int dominantDirection, double dominance, int glyphCount) {
+
+ public boolean isConclusive() {
+ if (glyphCount >= MIN_GLYPHS && dominance >= MIN_DOMINANCE) {
+ return true;
+ }
+ return glyphCount >= MIN_GLYPHS_UNANIMOUS && dominance >= UNANIMOUS_DOMINANCE;
+ }
+ }
+
+ /**
+ * Parsed Tesseract OSD verdict.
+ *
+ * @param rotate clockwise degrees to rotate the rendered page so text is upright
+ * @param confidence Tesseract's orientation confidence (same scale OCRmyPDF thresholds on)
+ */
+ public record OsdResult(int rotate, double confidence) {}
+
+ private static final Pattern OSD_ROTATE =
+ Pattern.compile("^Rotate:\\s*(\\d+)", Pattern.MULTILINE);
+ private static final Pattern OSD_CONFIDENCE =
+ Pattern.compile("^Orientation confidence:\\s*([0-9.]+)", Pattern.MULTILINE);
+
+ /**
+ * Counts non-whitespace glyph directions for every page in one pass. A stripper per page would
+ * re-walk the document once per page, which is quadratic on long documents; this walks it once
+ * and buckets glyphs by the page being processed.
+ *
+ * @return one entry per page, in page order
+ */
+ public static List<TextDirection> detectTextDirections(PDDocument document) throws IOException {
+ int pageCount = document.getNumberOfPages();
+ DirectionCountingStripper stripper = new DirectionCountingStripper(pageCount);
+ stripper.setStartPage(1);
+ stripper.setEndPage(pageCount);
+ stripper.getText(document);
+
+ List<TextDirection> directions = new ArrayList<>(pageCount);
+ for (int page = 0; page < pageCount; page++) {
+ int[] counts = stripper.counts[page];
+ int total = 0;
+ int bestIndex = 0;
+ for (int i = 0; i < 4; i++) {
+ total += counts[i];
+ if (counts[i] > counts[bestIndex]) {
+ bestIndex = i;
+ }
+ }
+ double dominance = total == 0 ? 0 : (double) counts[bestIndex] / total;
+ directions.add(new TextDirection(bestIndex * 90, dominance, total));
+ }
+ return directions;
+ }
+
+ /**
+ * True when a rendered page carries no ink worth analysing. Checked after rendering but before
+ * spawning Tesseract, since the process spawn costs far more than the pixel scan and this
+ * catches both empty generated pages and scanned blanks (the back of a duplex sheet).
+ */
+ public static boolean isBlankRender(BufferedImage image) {
+ final int darkThreshold = 200; // 8-bit grey; anything lighter counts as paper
+ final int step = 4; // subsample: blank pages are uniform, no need for every pixel
+ long sampled = 0;
+ long dark = 0;
+ for (int y = 0; y < image.getHeight(); y += step) {
+ for (int x = 0; x < image.getWidth(); x += step) {
+ sampled++;
+ if ((image.getRGB(x, y) & 0xFF) < darkThreshold) {
+ dark++;
+ // A page needs a meaningful amount of ink before OSD can do anything;
+ // bail out as soon as we know there is enough.
+ if (dark > sampled / 1000 + 20) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Clockwise /Rotate correction for a page whose dominant glyph direction (page space, CCW) is
+ * {@code dominantDirection} and whose current /Rotate is {@code pageRotation}. Derivation: the
+ * on-screen text angle is (direction - rotation) CCW, and adding d to /Rotate turns the display
+ * a further d clockwise, so the correction that zeroes the screen angle is their difference.
+ */
+ public static int correctionFromTextDirection(int dominantDirection, int pageRotation) {
+ return Math.floorMod(dominantDirection - pageRotation, 360);
+ }
+
+ /** Extracts rotation and confidence from `tesseract <img> stdout --psm 0` output. */
+ public static Optional<OsdResult> parseOsd(String tesseractOutput) {
+ if (tesseractOutput == null) {
+ return Optional.empty();
+ }
+ Matcher rotate = OSD_ROTATE.matcher(tesseractOutput);
+ Matcher confidence = OSD_CONFIDENCE.matcher(tesseractOutput);
+ if (!rotate.find() || !confidence.find()) {
+ return Optional.empty();
+ }
+ try {
+ return Optional.of(
+ new OsdResult(
+ Integer.parseInt(rotate.group(1)),
+ Double.parseDouble(confidence.group(1))));
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+
+ private static class DirectionCountingStripper extends PDFTextStripper {
+
+ // counts[page][i] holds glyphs on that page whose direction is i * 90 degrees
+ final int[][] counts;
+
+ DirectionCountingStripper(int pageCount) throws IOException {
+ this.counts = new int[pageCount][4];
+ }
+
+ /**
+ * PDFBox snaps glyph direction to a quadrant, so getDir() only ever yields 0/90/180/270 —
+ * obliquely drawn text (30, 45, 135 degrees) is reported as 0 rather than as its true
+ * angle. Skew is therefore invisible to this signal by construction, which is consistent
+ * with skew being out of scope here: only 90-degree orientation is corrected.
+ */
+ @Override
+ protected void processTextPosition(TextPosition text) {
+ String unicode = text.getUnicode();
+ if (unicode == null || unicode.isBlank()) {
+ return;
+ }
+ int page = getCurrentPageNo() - 1;
+ if (page < 0 || page >= counts.length) {
+ return;
+ }
+ counts[page][Math.floorMod(Math.round(text.getDir()), 360) / 90]++;
+ // super is intentionally not called: we only count, no text assembly needed
+ }
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java
new file mode 100644
index 0000000000..0545a17058
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java
@@ -0,0 +1,342 @@
+package stirling.software.SPDF.controller.api.misc;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.List;
+
+import org.apache.pdfbox.Loader;
+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.font.PDType1Font;
+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
+import org.apache.pdfbox.text.PDFTextStripper;
+import org.apache.pdfbox.text.TextPosition;
+import org.apache.pdfbox.util.Matrix;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.core.io.Resource;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.MockMultipartFile;
+
+import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.SPDF.model.api.misc.AutoRotateAnalysisResult;
+import stirling.software.SPDF.model.api.misc.AutoRotatePdfRequest;
+import stirling.software.SPDF.model.api.misc.PageRotation;
+import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.TempFile;
+import stirling.software.common.util.TempFileManager;
+
+@ExtendWith(MockitoExtension.class)
+class AutoRotateControllerTest {
+
+ private static final String SAMPLE_TEXT =
+ "The quick brown fox jumps over the lazy dog again and again";
+
+ @Mock private CustomPDFDocumentFactory pdfDocumentFactory;
+ @Mock private TempFileManager tempFileManager;
+ @Mock private EndpointConfiguration endpointConfiguration;
+ @Mock private RuntimePathConfig runtimePathConfig;
+ @Mock private ApplicationProperties applicationProperties;
+
+ @InjectMocks private AutoRotateController controller;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ lenient()
+ .when(tempFileManager.createManagedTempFile(anyString()))
+ .thenAnswer(
+ inv -> {
+ File f =
+ Files.createTempFile("test", inv.<String>getArgument(0))
+ .toFile();
+ TempFile tf = mock(TempFile.class);
+ lenient().when(tf.getFile()).thenReturn(f);
+ lenient().when(tf.getPath()).thenReturn(f.toPath());
+ return tf;
+ });
+ lenient().when(endpointConfiguration.isGroupEnabled("tesseract")).thenReturn(false);
+ }
+
+ private static PDDocument docWithUprightText(int... pageRotations) throws IOException {
+ PDDocument document = new PDDocument();
+ for (int rotation : pageRotations) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(Matrix.getTranslateInstance(72, 400));
+ content.showText(SAMPLE_TEXT);
+ content.endText();
+ }
+ page.setRotation(rotation);
+ }
+ return document;
+ }
+
+ private AutoRotatePdfRequest request(PDDocument document) throws IOException {
+ AutoRotatePdfRequest request = new AutoRotatePdfRequest();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ new byte[] {1, 2, 3}));
+ when(pdfDocumentFactory.load(request)).thenReturn(document);
+ return request;
+ }
+
+ private static PDDocument reload(ResponseEntity<?> response) throws IOException {
+ Resource resource = (Resource) response.getBody();
+ return Loader.loadPDF(resource.getContentAsByteArray());
+ }
+
+ private static PDDocument docWithTextAt(int textAngleDegrees, int pageRotation)
+ throws IOException {
+ PDDocument document = new PDDocument();
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(
+ Matrix.getRotateInstance(Math.toRadians(textAngleDegrees), 300, 400));
+ content.showText(SAMPLE_TEXT);
+ content.endText();
+ }
+ page.setRotation(pageRotation);
+ return document;
+ }
+
+ /**
+ * Reads the dominant glyph direction straight from a document, independently of the production
+ * detection code, so the round-trip assertion below validates the result rather than restating
+ * the formula under test.
+ */
+ private static int dominantGlyphDirection(PDDocument document) throws IOException {
+ int[] counts = new int[4];
+ PDFTextStripper stripper =
+ new PDFTextStripper() {
+ @Override
+ protected void processTextPosition(TextPosition text) {
+ if (!text.getUnicode().isBlank()) {
+ counts[Math.floorMod(Math.round(text.getDir()), 360) / 90]++;
+ }
+ }
+ };
+ stripper.setStartPage(1);
+ stripper.setEndPage(1);
+ stripper.getText(document);
+ int best = 0;
+ for (int i = 1; i < 4; i++) {
+ if (counts[i] > counts[best]) {
+ best = i;
+ }
+ }
+ return best * 90;
+ }
+
+ /**
+ * End-to-end round trip: build a page whose text is drawn at a known angle under a known
+ * /Rotate, run the real controller, then assert the output actually displays upright. Upright
+ * means the glyph direction and the page rotation cancel — computed here in the test, not via
+ * the production helper.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "0, 0",
+ "0, 90",
+ "0, 180",
+ "0, 270",
+ "90, 0",
+ "90, 90",
+ "180, 0",
+ "180, 270",
+ "270, 90",
+ })
+ void roundTripLeavesPageUpright(int textAngle, int pageRotation) throws Exception {
+ AutoRotatePdfRequest request = request(docWithTextAt(textAngle, pageRotation));
+ request.setDetectionMode("text");
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ try (PDDocument corrected = reload(response)) {
+ int glyphDirection = dominantGlyphDirection(corrected);
+ int finalRotation = Math.floorMod(corrected.getPage(0).getRotation(), 360);
+ assertThat(Math.floorMod(glyphDirection - finalRotation, 360))
+ .as(
+ "text drawn at %d under /Rotate %d should display upright, got glyph"
+ + " direction %d with /Rotate %d",
+ textAngle, pageRotation, glyphDirection, finalRotation)
+ .isZero();
+ }
+ }
+
+ @Test
+ void dryRunReportsTextDetection() throws Exception {
+ AutoRotatePdfRequest request = request(docWithUprightText(90, 0));
+ request.setDryRun(true);
+ request.setDetectionMode("text");
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ AutoRotateAnalysisResult result = (AutoRotateAnalysisResult) response.getBody();
+ assertThat(result.getTotalPages()).isEqualTo(2);
+ assertThat(result.getPagesToRotate()).isEqualTo(1);
+ assertThat(result.getDetectedByText()).isEqualTo(2);
+
+ AutoRotateAnalysisResult.PageResult first = result.getPages().get(0);
+ assertThat(first.getMethod()).isEqualTo("text");
+ assertThat(first.getCorrection()).isEqualTo(270);
+ assertThat(first.isApply()).isTrue();
+ assertThat(first.getConfidence()).isEqualTo(100.0);
+
+ AutoRotateAnalysisResult.PageResult second = result.getPages().get(1);
+ assertThat(second.getCorrection()).isZero();
+ assertThat(second.isApply()).isFalse();
+ }
+
+ @Test
+ void appliesDetectedCorrections() throws Exception {
+ AutoRotatePdfRequest request = request(docWithUprightText(90, 0));
+ request.setDetectionMode("text");
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ try (PDDocument corrected = reload(response)) {
+ assertThat(corrected.getPage(0).getRotation()).isZero();
+ assertThat(corrected.getPage(1).getRotation()).isZero();
+ }
+ }
+
+ @Test
+ void appliesExplicitPageRotations() throws Exception {
+ AutoRotatePdfRequest request = request(docWithUprightText(0, 0));
+ request.setPageRotations(List.of(new PageRotation(1, 90)));
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ try (PDDocument corrected = reload(response)) {
+ assertThat(corrected.getPage(0).getRotation()).isEqualTo(90);
+ assertThat(corrected.getPage(1).getRotation()).isZero();
+ }
+ }
+
+ @Test
+ void reportsTesseractUnavailableForTextlessPages() throws Exception {
+ PDDocument document = new PDDocument();
+ document.addPage(new PDPage(PDRectangle.LETTER));
+ AutoRotatePdfRequest request = request(document);
+ request.setDryRun(true);
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ AutoRotateAnalysisResult result = (AutoRotateAnalysisResult) response.getBody();
+ AutoRotateAnalysisResult.PageResult page = result.getPages().get(0);
+ assertThat(page.getMethod()).isEqualTo("none");
+ assertThat(page.getNote()).isEqualTo("tesseractUnavailable");
+ assertThat(result.getUndetected()).isEqualTo(1);
+ }
+
+ @Test
+ void infersUndetectedPageFromDocumentConsensus() throws Exception {
+ // Page 1 has body text and is rotated 90 (-> 270 correction); page 2 is blank and shares
+ // the same rotation. With OSD unavailable, page 2 can't be detected on its own, so it
+ // should inherit page 1's 270 correction.
+ PDDocument document = docWithUprightText(90);
+ PDPage blank = new PDPage(PDRectangle.LETTER);
+ blank.setRotation(90);
+ document.addPage(blank);
+ AutoRotatePdfRequest request = request(document);
+ request.setDryRun(true);
+ request.setDetectionMode("text");
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ AutoRotateAnalysisResult result = (AutoRotateAnalysisResult) response.getBody();
+ AutoRotateAnalysisResult.PageResult page2 = result.getPages().get(1);
+ assertThat(page2.getMethod()).isEqualTo("inferred");
+ assertThat(page2.getCorrection()).isEqualTo(270);
+ assertThat(page2.isApply()).isTrue();
+ assertThat(page2.getNote()).isEqualTo("inferredFromDocument");
+ assertThat(result.getInferred()).isEqualTo(1);
+ assertThat(result.getPagesToRotate()).isEqualTo(2);
+ }
+
+ @Test
+ void doesNotInferWhenDisabled() throws Exception {
+ PDDocument document = docWithUprightText(90);
+ PDPage blank = new PDPage(PDRectangle.LETTER);
+ blank.setRotation(90);
+ document.addPage(blank);
+ AutoRotatePdfRequest request = request(document);
+ request.setDryRun(true);
+ request.setDetectionMode("text");
+ request.setInferUndetected(false);
+
+ ResponseEntity<?> response = controller.autoRotatePdf(request);
+
+ AutoRotateAnalysisResult result = (AutoRotateAnalysisResult) response.getBody();
+ AutoRotateAnalysisResult.PageResult page2 = result.getPages().get(1);
+ assertThat(page2.getMethod()).isEqualTo("none");
+ assertThat(page2.isApply()).isFalse();
+ assertThat(result.getInferred()).isZero();
+ assertThat(result.getUndetected()).isEqualTo(1);
+ }
+
+ @Test
+ void rejectsInvalidDetectionMode() {
+ AutoRotatePdfRequest request = new AutoRotatePdfRequest();
+ request.setDetectionMode("magic");
+
+ assertThatThrownBy(() -> controller.autoRotatePdf(request))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void rejectsRotationThatIsNotAMultipleOf90() throws Exception {
+ AutoRotatePdfRequest request = request(docWithUprightText(0));
+ request.setPageRotations(List.of(new PageRotation(1, 45)));
+
+ assertThatThrownBy(() -> controller.autoRotatePdf(request))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void rejectsPageRotationOutsideTheDocument() throws Exception {
+ AutoRotatePdfRequest request = request(docWithUprightText(0));
+ request.setPageRotations(List.of(new PageRotation(5, 90)));
+
+ assertThatThrownBy(() -> controller.autoRotatePdf(request))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void rejectsDuplicatePageInRotations() throws Exception {
+ // Rotations are additive, so applying the same page twice would over-rotate it.
+ AutoRotatePdfRequest request = request(docWithUprightText(0, 0));
+ request.setPageRotations(List.of(new PageRotation(1, 90), new PageRotation(1, 90)));
+
+ assertThatThrownBy(() -> controller.autoRotatePdf(request))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/utils/AutoRotateDetectionTest.java b/app/core/src/test/java/stirling/software/SPDF/utils/AutoRotateDetectionTest.java
new file mode 100644
index 0000000000..741d18e652
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/utils/AutoRotateDetectionTest.java
@@ -0,0 +1,248 @@
+package stirling.software.SPDF.utils;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+
+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.font.PDType1Font;
+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
+import org.apache.pdfbox.util.Matrix;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import stirling.software.SPDF.utils.AutoRotateDetection.OsdResult;
+import stirling.software.SPDF.utils.AutoRotateDetection.TextDirection;
+
+class AutoRotateDetectionTest {
+
+ private static final String SAMPLE_TEXT =
+ "The quick brown fox jumps over the lazy dog again and again";
+
+ private PDDocument docWithText(int textAngleDegrees, int pageRotation) throws IOException {
+ PDDocument document = new PDDocument();
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(
+ Matrix.getRotateInstance(Math.toRadians(textAngleDegrees), 300, 400));
+ content.showText(SAMPLE_TEXT);
+ content.endText();
+ }
+ page.setRotation(pageRotation);
+ return document;
+ }
+
+ /**
+ * Ground truth per the PDF spec: /Rotate R displays the page R degrees clockwise, so upright
+ * page-space text under /Rotate R needs a further (360 - R) % 360 to display upright again;
+ * text drawn rotated T degrees CCW in page space needs T clockwise to correct. Combined, the
+ * expected correction is (T - R) mod 360.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ // textAngle, pageRotation, expectedCorrection
+ "0, 0, 0",
+ "0, 90, 270",
+ "0, 180, 180",
+ "0, 270, 90",
+ "90, 0, 90",
+ "180, 0, 180",
+ "270, 0, 270",
+ "90, 90, 0",
+ "180, 90, 90",
+ })
+ void detectsCorrectionForRotatedTextAndPages(
+ int textAngle, int pageRotation, int expectedCorrection) throws IOException {
+ try (PDDocument document = docWithText(textAngle, pageRotation)) {
+ TextDirection direction = AutoRotateDetection.detectTextDirections(document).get(0);
+
+ assertThat(direction.isConclusive())
+ .as(
+ "direction should be conclusive, glyphs=%d dominance=%s",
+ direction.glyphCount(), direction.dominance())
+ .isTrue();
+ assertThat(
+ AutoRotateDetection.correctionFromTextDirection(
+ direction.dominantDirection(),
+ Math.floorMod(pageRotation, 360)))
+ .isEqualTo(expectedCorrection);
+ }
+ }
+
+ @Test
+ void mixedDirectionsAreNotConclusive() throws IOException {
+ PDDocument document = new PDDocument();
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(Matrix.getTranslateInstance(100, 400));
+ content.showText(SAMPLE_TEXT);
+ content.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(90), 300, 200));
+ content.showText(SAMPLE_TEXT);
+ content.endText();
+ }
+ try (document) {
+ TextDirection direction = AutoRotateDetection.detectTextDirections(document).get(0);
+ assertThat(direction.isConclusive()).isFalse();
+ }
+ }
+
+ @Test
+ void emptyPageIsNotConclusive() throws IOException {
+ try (PDDocument document = new PDDocument()) {
+ document.addPage(new PDPage(PDRectangle.LETTER));
+ TextDirection direction = AutoRotateDetection.detectTextDirections(document).get(0);
+ assertThat(direction.glyphCount()).isZero();
+ assertThat(direction.isConclusive()).isFalse();
+ }
+ }
+
+ @Test
+ void shortTextIsNotConclusive() throws IOException {
+ PDDocument document = new PDDocument();
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(Matrix.getTranslateInstance(100, 400));
+ content.showText("Short");
+ content.endText();
+ }
+ try (document) {
+ TextDirection direction = AutoRotateDetection.detectTextDirections(document).get(0);
+ assertThat(direction.isConclusive()).isFalse();
+ }
+ }
+
+ @Test
+ void unanimousShortTextIsConclusive() throws IOException {
+ // Between MIN_GLYPHS_UNANIMOUS (8) and MIN_GLYPHS (30): trusted only because every
+ // glyph agrees on direction, the sparse-page path (e.g. a lone header or URL line).
+ PDDocument document = new PDDocument();
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(90), 300, 200));
+ content.showText("york.gov.uk/pay");
+ content.endText();
+ }
+ try (document) {
+ TextDirection direction = AutoRotateDetection.detectTextDirections(document).get(0);
+ assertThat(direction.glyphCount())
+ .isBetween(
+ AutoRotateDetection.MIN_GLYPHS_UNANIMOUS,
+ AutoRotateDetection.MIN_GLYPHS - 1);
+ assertThat(direction.dominance()).isEqualTo(1.0);
+ assertThat(direction.isConclusive()).isTrue();
+ assertThat(direction.dominantDirection()).isEqualTo(90);
+ }
+ }
+
+ @Test
+ void bucketsGlyphsPerPageInOneWalk() throws IOException {
+ // Each page carries text at a different angle; the single-pass walk must attribute
+ // glyphs to the right page rather than pooling them.
+ int[] angles = {0, 90, 180, 270};
+ try (PDDocument document = new PDDocument()) {
+ for (int angle : angles) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.setTextMatrix(
+ Matrix.getRotateInstance(Math.toRadians(angle), 300, 400));
+ content.showText(SAMPLE_TEXT);
+ content.endText();
+ }
+ }
+
+ List<TextDirection> directions = AutoRotateDetection.detectTextDirections(document);
+
+ assertThat(directions).hasSize(angles.length);
+ for (int i = 0; i < angles.length; i++) {
+ assertThat(directions.get(i).isConclusive()).as("page %d", i + 1).isTrue();
+ assertThat(directions.get(i).dominantDirection())
+ .as("page %d direction", i + 1)
+ .isEqualTo(angles[i]);
+ }
+ }
+ }
+
+ @Test
+ void detectsBlankAndInkedRenders() {
+ BufferedImage blank = new BufferedImage(200, 200, BufferedImage.TYPE_BYTE_GRAY);
+ Graphics2D g = blank.createGraphics();
+ g.setColor(Color.WHITE);
+ g.fillRect(0, 0, 200, 200);
+ g.dispose();
+ assertThat(AutoRotateDetection.isBlankRender(blank)).isTrue();
+
+ BufferedImage speck = copyOf(blank);
+ Graphics2D specked = speck.createGraphics();
+ specked.setColor(Color.BLACK);
+ specked.fillRect(0, 0, 2, 2); // a dust speck must not count as content
+ specked.dispose();
+ assertThat(AutoRotateDetection.isBlankRender(speck)).isTrue();
+
+ BufferedImage inked = copyOf(blank);
+ Graphics2D inkedG = inked.createGraphics();
+ inkedG.setColor(Color.BLACK);
+ inkedG.fillRect(20, 20, 120, 60);
+ inkedG.dispose();
+ assertThat(AutoRotateDetection.isBlankRender(inked)).isFalse();
+ }
+
+ private static BufferedImage copyOf(BufferedImage source) {
+ BufferedImage copy =
+ new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
+ Graphics2D g = copy.createGraphics();
+ g.drawImage(source, 0, 0, null);
+ g.dispose();
+ return copy;
+ }
+
+ @Test
+ void parsesTypicalOsdOutput() {
+ String output =
+ """
+ Estimating resolution as 336
+ Page number: 0
+ Orientation in degrees: 180
+ Rotate: 180
+ Orientation confidence: 9.15
+ Script: Latin
+ Script confidence: 4.43
+ """;
+ Optional<OsdResult> result = AutoRotateDetection.parseOsd(output);
+ assertThat(result).isPresent();
+ assertThat(result.get().rotate()).isEqualTo(180);
+ assertThat(result.get().confidence()).isEqualTo(9.15);
+ }
+
+ @Test
+ void parseOsdRejectsIncompleteOutput() {
+ assertThat(AutoRotateDetection.parseOsd("Too few characters. Skipping this page"))
+ .isEmpty();
+ assertThat(AutoRotateDetection.parseOsd("Rotate: 90")).isEmpty();
+ assertThat(AutoRotateDetection.parseOsd(null)).isEmpty();
+ assertThat(AutoRotateDetection.parseOsd("")).isEmpty();
+ }
+}
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index 1827730283..712e3575af 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -241,6 +241,16 @@ class AutoRenameParams(ApiModel):
)
+class DetectionMode(StrEnum):
+ """
+ Detection method. 'auto' tries embedded-text direction first and falls back to Tesseract OSD for pages without usable text; 'text' uses only embedded-text direction; 'osd' forces Tesseract OSD for every page
+ """
+
+ auto = "auto"
+ text = "text"
+ osd = "osd"
+
+
class AutoSplitPdfParams(ApiModel):
duplex_mode: bool = Field(
False,
@@ -705,6 +715,19 @@ class OcrPdfParams(ApiModel):
sidecar: bool | None = Field(None, description="Include OCR text in a sidecar text file if set to true")
+class PageRotation(ApiModel):
+ """
+ Optional pre-computed corrections to apply without running detection. Pages not listed are left unchanged, and a page may only appear once
+ """
+
+ page_number: int = Field(..., description="1-based page number to rotate", examples=[1])
+ rotation: int = Field(
+ ...,
+ description="Additional clockwise rotation to add to the page's current rotation, in degrees. Must be a multiple of 90",
+ examples=[90],
+ )
+
+
class PdfToCbrParams(ApiModel):
dpi: int = Field(..., description="The DPI (Dots Per Inch) for rendering PDF pages as images", examples=[150])
@@ -1348,6 +1371,30 @@ class VectorToPdfParams(ApiModel):
prepress: Prepress = Field(Prepress.boolean_false, description="Apply Ghostscript prepress settings")
+class AutoRotatePdfParams(ApiModel):
+ confidence_threshold: float = Field(
+ 14.0,
+ description="Minimum Tesseract OSD orientation confidence required before a correction is applied. Matches OCRmyPDF's --rotate-pages-threshold scale",
+ ge=0.0,
+ )
+ detection_mode: DetectionMode = Field(
+ DetectionMode.auto,
+ description="Detection method. 'auto' tries embedded-text direction first and falls back to Tesseract OSD for pages without usable text; 'text' uses only embedded-text direction; 'osd' forces Tesseract OSD for every page",
+ )
+ dry_run: bool | None = Field(
+ None,
+ description="If true, no rotation is applied; returns a JSON report of the per-page detection results instead of a PDF",
+ )
+ infer_undetected: bool = Field(
+ True,
+ description="When a page cannot be decided on its own but the pages that could be decided agree on a single correction for that same current rotation, apply that shared correction to the undecided page. Handles documents rotated uniformly where some pages are too sparse to detect alone",
+ )
+ page_rotations: list[PageRotation] | None = Field(
+ None,
+ description="Optional pre-computed corrections to apply without running detection. Pages not listed are left unchanged, and a page may only appear once",
+ )
+
+
class RedactExecuteParams(ApiModel):
image_boxes: list[ImageBox] | None = Field(
None, description="Rectangular areas to black out, each defined by a page number and bounding box coordinates."
@@ -1432,6 +1479,7 @@ class Model(
| AddPageNumbersParams
| AddStampParams
| AutoRenameParams
+ | AutoRotatePdfParams
| AutoSplitPdfParams
| CompressPdfParams
| DeleteAttachmentParams
@@ -1505,6 +1553,7 @@ class Model(
| AddPageNumbersParams
| AddStampParams
| AutoRenameParams
+ | AutoRotatePdfParams
| AutoSplitPdfParams
| CompressPdfParams
| DeleteAttachmentParams
@@ -1579,6 +1628,7 @@ type ParamToolModel = (
| AddPageNumbersParams
| AddStampParams
| AutoRenameParams
+ | AutoRotatePdfParams
| AutoSplitPdfParams
| CompressPdfParams
| DeleteAttachmentParams
@@ -1654,6 +1704,7 @@ class ToolEndpoint(StrEnum):
ADD_PAGE_NUMBERS = "/api/v1/misc/add-page-numbers"
ADD_STAMP = "/api/v1/misc/add-stamp"
AUTO_RENAME = "/api/v1/misc/auto-rename"
+ AUTO_ROTATE_PDF = "/api/v1/misc/auto-rotate-pdf"
AUTO_SPLIT_PDF = "/api/v1/misc/auto-split-pdf"
COMPRESS_PDF = "/api/v1/misc/compress-pdf"
DELETE_ATTACHMENT = "/api/v1/misc/delete-attachment"
@@ -1727,6 +1778,7 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {
ToolEndpoint.ADD_PAGE_NUMBERS: AddPageNumbersParams,
ToolEndpoint.ADD_STAMP: AddStampParams,
ToolEndpoint.AUTO_RENAME: AutoRenameParams,
+ ToolEndpoint.AUTO_ROTATE_PDF: AutoRotatePdfParams,
ToolEndpoint.AUTO_SPLIT_PDF: AutoSplitPdfParams,
ToolEndpoint.COMPRESS_PDF: CompressPdfParams,
ToolEndpoint.DELETE_ATTACHMENT: DeleteAttachmentParams,
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index d02e60b84c..d02925fe46 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -2175,6 +2175,73 @@ secureWorkflowDesc = "Secures PDF documents by removing potentially malicious co
description = "This tool will automatically rename PDF files based on their content. It analyzes the document to find the most suitable title from the text."
tags = "auto-detect,header-based,organize,relabel,auto rename,automatic rename,smart rename,rename by content,filename,file naming,detect title"
+[autoRotate]
+submit = "Auto Rotate"
+tags = "auto rotate,fix orientation,upside down,sideways,straighten,orient,detect orientation,correct rotation,auto orient,scanned,OSD"
+
+[autoRotate.confidenceThreshold]
+title = "Confidence threshold"
+
+[autoRotate.detectionMode]
+auto = "Auto"
+osd = "OCR only"
+text = "Text only"
+title = "Detection method"
+
+[autoRotate.error]
+failed = "An error occurred while auto-rotating the PDF."
+
+[autoRotate.inferUndetected]
+title = "Rotate low confidence pages to match"
+
+[autoRotate.report]
+applied = "{{degrees}}° CW"
+confidenceValue = "Confidence {{value}}"
+noChange = "No change"
+pageLabel = "Page {{number}}"
+summary = "{{rotated}} of {{total}} pages rotated, {{unchanged}} left as they are"
+title = "Detection report"
+
+[autoRotate.report.method]
+inferred = "Matched"
+none = "Skipped"
+osd = "OCR"
+text = "Text"
+
+[autoRotate.report.note]
+belowThreshold = "Below threshold"
+blankPage = "Page is blank"
+inferredFromDocument = "Same as the other pages"
+noDominantDirection = "Mixed text directions"
+osdFailed = "No readable text found"
+osdNoVerdict = "Could not tell which way up"
+tesseractUnavailable = "OCR not installed"
+tooFewGlyphs = "Too little text"
+
+[autoRotate.results]
+title = "Auto Rotate Results"
+
+[autoRotate.settings]
+title = "Settings"
+
+[autoRotate.tooltip.confidenceThreshold]
+text = "How certain the check has to be before a page is turned. Lower it to rotate more pages, raise it to leave more pages untouched."
+title = "Confidence threshold"
+
+[autoRotate.tooltip.description]
+text = "Works out which way up each page should be and turns it the right way round. Pages that are already upright are left alone."
+
+[autoRotate.tooltip.detectionMode]
+text = "Auto reads the text on the page first, then looks at the page as an image if that is not enough. Text only skips the image check, which is quickest for documents that were never scanned. OCR only treats every page as an image."
+title = "Detection method"
+
+[autoRotate.tooltip.header]
+title = "Auto Rotate"
+
+[autoRotate.tooltip.inferUndetected]
+text = "Blank or nearly blank pages cannot be checked on their own. When every page that could be read needs the same turn, these pages are turned to match them."
+title = "Rotate low confidence pages to match"
+
[autoSizeSplitPDF]
tags = "pdf,split,document,organization"
@@ -4494,6 +4561,11 @@ desc = "Auto renames a PDF file based on its detected header"
tags = "auto-detect,header-based,organize,relabel,auto rename,automatic rename,smart rename,rename by content,filename,file naming,detect title"
title = "Auto Rename PDF File"
+[home.autoRotate]
+desc = "Detect each page's orientation and rotate it upright automatically."
+tags = "auto rotate,fix orientation,upside down,sideways,straighten,orient,detect orientation,correct rotation,auto orient,scanned,OSD"
+title = "Auto Rotate"
+
[home.autoSizeSplitPDF]
tags = "auto,split,size"
title = "Auto Split by Size/Count"
diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.json
index 3053b4fd9e..07cd6f0d27 100644
--- a/frontend/editor/public/og-metadata.json
+++ b/frontend/editor/public/og-metadata.json
@@ -100,6 +100,11 @@
"title": "Rotate - Stirling PDF",
"description": "Easily rotate your PDFs."
},
+ "autoRotate": {
+ "image": "/og_images/home.png",
+ "title": "Auto Rotate - Stirling PDF",
+ "description": "Detect each page's orientation and rotate it upright automatically."
+ },
"annotate": {
"image": "/og_images/annotate.png",
"title": "Annotate - Stirling PDF",
@@ -551,6 +556,7 @@
"/ocr": "ocr",
"/add-image": "addImage",
"/rotate": "rotate",
+ "/auto-rotate": "autoRotate",
"/annotate": "annotate",
"/scanner-image-split": "scannerImageSplit",
"/edit-table-of-contents": "editTableOfContents",
diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.json
index 39f6bf414e..da1ab7fc66 100644
--- a/frontend/editor/public/og-metadata.saas.json
+++ b/frontend/editor/public/og-metadata.saas.json
@@ -101,6 +101,11 @@
"title": "Rotate - Stirling PDF",
"description": "Easily rotate your PDFs."
},
+ "autoRotate": {
+ "image": "/og_images/home.png",
+ "title": "Auto Rotate - Stirling PDF",
+ "description": "Detect each page's orientation and rotate it upright automatically."
+ },
"annotate": {
"image": "/og_images/annotate.png",
"title": "Annotate - Stirling PDF",
@@ -564,6 +569,7 @@
"/ocr": "ocr",
"/add-image": "addImage",
"/rotate": "rotate",
+ "/auto-rotate": "autoRotate",
"/annotate": "annotate",
"/scanner-image-split": "scannerImageSplit",
"/edit-table-of-contents": "editTableOfContents",
diff --git a/frontend/editor/src/core/components/tools/autoRotate/AutoRotateAutomationSettings.tsx b/frontend/editor/src/core/components/tools/autoRotate/AutoRotateAutomationSettings.tsx
new file mode 100644
index 0000000000..ac828c1b59
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/autoRotate/AutoRotateAutomationSettings.tsx
@@ -0,0 +1,83 @@
+import { Stack, Text, NumberInput } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import {
+ AutoRotateParameters,
+ AutoRotateDetectionMode,
+} from "@app/hooks/tools/autoRotate/useAutoRotateParameters";
+import ButtonSelector from "@app/components/shared/ButtonSelector";
+import { Checkbox } from "@app/ui/Checkbox";
+
+interface AutoRotateAutomationSettingsProps {
+ parameters: AutoRotateParameters;
+ onParameterChange: <K extends keyof AutoRotateParameters>(
+ key: K,
+ value: AutoRotateParameters[K],
+ ) => void;
+ disabled?: boolean;
+}
+
+const AutoRotateAutomationSettings = ({
+ parameters,
+ onParameterChange,
+ disabled = false,
+}: AutoRotateAutomationSettingsProps) => {
+ const { t } = useTranslation();
+
+ return (
+ <Stack gap="md">
+ <Text size="sm" fw={500}>
+ {t("autoRotate.detectionMode.title", "Detection method")}
+ </Text>
+
+ <ButtonSelector
+ value={parameters.detectionMode}
+ onChange={(value: AutoRotateDetectionMode) =>
+ onParameterChange("detectionMode", value)
+ }
+ options={[
+ { value: "auto", label: t("autoRotate.detectionMode.auto", "Auto") },
+ {
+ value: "text",
+ label: t("autoRotate.detectionMode.text", "Text only"),
+ },
+ {
+ value: "osd",
+ label: t("autoRotate.detectionMode.osd", "OCR only"),
+ },
+ ]}
+ disabled={disabled}
+ />
+
+ <NumberInput
+ label={t(
+ "autoRotate.confidenceThreshold.title",
+ "Confidence threshold",
+ )}
+ min={0}
+ step={1}
+ disabled={disabled}
+ value={parameters.confidenceThreshold}
+ onChange={(value) =>
+ onParameterChange(
+ "confidenceThreshold",
+ typeof value === "number" ? value : 14,
+ )
+ }
+ />
+
+ <Checkbox
+ label={t(
+ "autoRotate.inferUndetected.title",
+ "Rotate low confidence pages to match",
+ )}
+ disabled={disabled}
+ checked={parameters.inferUndetected}
+ onChange={(event) =>
+ onParameterChange("inferUndetected", event.currentTarget.checked)
+ }
+ />
+ </Stack>
+ );
+};
+
+export default AutoRotateAutomationSettings;
diff --git a/frontend/editor/src/core/components/tools/autoRotate/AutoRotateReport.tsx b/frontend/editor/src/core/components/tools/autoRotate/AutoRotateReport.tsx
new file mode 100644
index 0000000000..0445864ff8
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/autoRotate/AutoRotateReport.tsx
@@ -0,0 +1,191 @@
+import {
+ Stack,
+ Text,
+ Badge,
+ ScrollArea,
+ Group,
+ Divider,
+ Box,
+} from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import type { TFunction } from "i18next";
+import {
+ AutoRotateReport as ReportData,
+ AutoRotatePageResult,
+} from "@app/hooks/tools/autoRotate/useAutoRotateOperation";
+
+interface AutoRotateReportProps {
+ reports: { fileName: string; report: ReportData }[];
+}
+
+const methodBadge = (t: TFunction, method: AutoRotatePageResult["method"]) => {
+ switch (method) {
+ case "text":
+ return (
+ <Badge size="sm" variant="light" color="blue">
+ {t("autoRotate.report.method.text", "Text")}
+ </Badge>
+ );
+ case "osd":
+ return (
+ <Badge size="sm" variant="light" color="teal">
+ {t("autoRotate.report.method.osd", "OCR")}
+ </Badge>
+ );
+ case "inferred":
+ return (
+ <Badge size="sm" variant="light" color="grape">
+ {t("autoRotate.report.method.inferred", "Matched")}
+ </Badge>
+ );
+ default:
+ return (
+ <Badge size="sm" variant="light" color="gray">
+ {t("autoRotate.report.method.none", "Skipped")}
+ </Badge>
+ );
+ }
+};
+
+const noteLabel = (t: TFunction, note: string | null | undefined): string => {
+ switch (note) {
+ case "tooFewGlyphs":
+ return t("autoRotate.report.note.tooFewGlyphs", "Too little text");
+ case "noDominantDirection":
+ return t(
+ "autoRotate.report.note.noDominantDirection",
+ "Mixed text directions",
+ );
+ case "tesseractUnavailable":
+ return t(
+ "autoRotate.report.note.tesseractUnavailable",
+ "OCR not installed",
+ );
+ case "blankPage":
+ return t("autoRotate.report.note.blankPage", "Page is blank");
+ case "osdFailed":
+ return t("autoRotate.report.note.osdFailed", "No readable text found");
+ case "osdNoVerdict":
+ return t(
+ "autoRotate.report.note.osdNoVerdict",
+ "Could not tell which way up",
+ );
+ case "belowThreshold":
+ return t("autoRotate.report.note.belowThreshold", "Below threshold");
+ case "inferredFromDocument":
+ return t(
+ "autoRotate.report.note.inferredFromDocument",
+ "Same as the other pages",
+ );
+ default:
+ return note ?? "";
+ }
+};
+
+// Text confidence is a glyph-dominance percentage; OCR confidence is an
+// unbounded score. Format them differently so the numbers stay interpretable
+// when tuning the threshold.
+const confidenceValue = (page: AutoRotatePageResult): string | null => {
+ if (page.confidence == null) return null;
+ return page.method === "text"
+ ? `${page.confidence.toFixed(1)}%`
+ : page.confidence.toFixed(2);
+};
+
+const AutoRotateReport = ({ reports }: AutoRotateReportProps) => {
+ const { t } = useTranslation();
+
+ if (reports.length === 0) return null;
+
+ return (
+ <Stack gap="md">
+ {reports.map(({ fileName, report }) => (
+ <Stack gap="xs" key={fileName}>
+ {reports.length > 1 && (
+ <Text size="sm" fw={500} truncate>
+ {fileName}
+ </Text>
+ )}
+ <Text size="xs" c="dimmed">
+ {t("autoRotate.report.summary", {
+ defaultValue:
+ "{{rotated}} of {{total}} pages rotated, {{unchanged}} left as they are",
+ rotated: report.pagesToRotate,
+ total: report.totalPages,
+ unchanged: report.totalPages - report.pagesToRotate,
+ })}
+ </Text>
+
+ {/* A per-page list rather than a table: the tool panel is too narrow
+ for five columns, which truncated the badges and wrapped notes. */}
+ <ScrollArea.Autosize mah={300}>
+ <Stack gap={0}>
+ {report.pages.map((page, index) => {
+ const confidence = confidenceValue(page);
+ const note = noteLabel(t, page.note);
+ return (
+ <Box key={page.pageNumber}>
+ {index > 0 && <Divider />}
+ <Stack gap={2} py={6}>
+ <Group justify="space-between" gap="xs" wrap="nowrap">
+ <Text size="sm" fw={500}>
+ {t("autoRotate.report.pageLabel", {
+ defaultValue: "Page {{number}}",
+ number: page.pageNumber,
+ })}
+ </Text>
+ <Text
+ size="sm"
+ fw={page.apply ? 600 : 400}
+ c={page.apply ? undefined : "dimmed"}
+ style={{ fontVariantNumeric: "tabular-nums" }}
+ >
+ {page.apply
+ ? t("autoRotate.report.applied", {
+ defaultValue: "{{degrees}}° CW",
+ degrees: page.correction,
+ })
+ : t("autoRotate.report.noChange", "No change")}
+ </Text>
+ </Group>
+ {/* Second line mirrors the first: detail under the page
+ number, method badge under the rotation. */}
+ <Group
+ justify="space-between"
+ gap="xs"
+ wrap="nowrap"
+ align="flex-start"
+ >
+ <Text
+ size="xs"
+ c="dimmed"
+ style={{ fontVariantNumeric: "tabular-nums" }}
+ >
+ {[
+ confidence &&
+ t("autoRotate.report.confidenceValue", {
+ defaultValue: "Confidence {{value}}",
+ value: confidence,
+ }),
+ note,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </Text>
+ <Box style={{ flexShrink: 0 }}>
+ {methodBadge(t, page.method)}
+ </Box>
+ </Group>
+ </Stack>
+ </Box>
+ );
+ })}
+ </Stack>
+ </ScrollArea.Autosize>
+ </Stack>
+ ))}
+ </Stack>
+ );
+};
+
+export default AutoRotateReport;
diff --git a/frontend/editor/src/core/components/tools/autoRotate/AutoRotateSettings.tsx b/frontend/editor/src/core/components/tools/autoRotate/AutoRotateSettings.tsx
new file mode 100644
index 0000000000..ed3d22965e
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/autoRotate/AutoRotateSettings.tsx
@@ -0,0 +1,89 @@
+import { Stack, Text, NumberInput } from "@mantine/core";
+import { SegmentedControl } from "@app/ui/SegmentedControl";
+import { Checkbox } from "@app/ui/Checkbox";
+import { useTranslation } from "react-i18next";
+import {
+ AutoRotateParametersHook,
+ AutoRotateDetectionMode,
+} from "@app/hooks/tools/autoRotate/useAutoRotateParameters";
+
+interface AutoRotateSettingsProps {
+ parameters: AutoRotateParametersHook;
+ disabled?: boolean;
+}
+
+// Explanatory copy for these controls lives in the step tooltip
+// (useAutoRotateTips), so the panel itself stays to labels only.
+const AutoRotateSettings = ({
+ parameters,
+ disabled = false,
+}: AutoRotateSettingsProps) => {
+ const { t } = useTranslation();
+
+ return (
+ <Stack gap="md">
+ <Stack gap="xs">
+ <Text size="sm" fw={500}>
+ {t("autoRotate.detectionMode.title", "Detection method")}
+ </Text>
+ <SegmentedControl<AutoRotateDetectionMode>
+ fullWidth
+ disabled={disabled}
+ ariaLabel={t("autoRotate.detectionMode.title", "Detection method")}
+ value={parameters.parameters.detectionMode}
+ onChange={(value) =>
+ parameters.updateParameter("detectionMode", value)
+ }
+ options={[
+ {
+ value: "auto",
+ label: t("autoRotate.detectionMode.auto", "Auto"),
+ },
+ {
+ value: "text",
+ label: t("autoRotate.detectionMode.text", "Text only"),
+ },
+ {
+ value: "osd",
+ label: t("autoRotate.detectionMode.osd", "OCR only"),
+ },
+ ]}
+ />
+ </Stack>
+
+ <NumberInput
+ label={t(
+ "autoRotate.confidenceThreshold.title",
+ "Confidence threshold",
+ )}
+ min={0}
+ step={1}
+ disabled={disabled}
+ value={parameters.parameters.confidenceThreshold}
+ onChange={(value) =>
+ parameters.updateParameter(
+ "confidenceThreshold",
+ typeof value === "number" ? value : 14,
+ )
+ }
+ />
+
+ <Checkbox
+ label={t(
+ "autoRotate.inferUndetected.title",
+ "Rotate low confidence pages to match",
+ )}
+ disabled={disabled}
+ checked={parameters.parameters.inferUndetected}
+ onChange={(event) =>
+ parameters.updateParameter(
+ "inferUndetected",
+ event.currentTarget.checked,
+ )
+ }
+ />
+ </Stack>
+ );
+};
+
+export default AutoRotateSettings;
diff --git a/frontend/editor/src/core/components/tooltips/useAutoRotateTips.ts b/frontend/editor/src/core/components/tooltips/useAutoRotateTips.ts
new file mode 100644
index 0000000000..6d0bc20864
--- /dev/null
+++ b/frontend/editor/src/core/components/tooltips/useAutoRotateTips.ts
@@ -0,0 +1,47 @@
+import { useTranslation } from "react-i18next";
+import { TooltipContent } from "@app/types/tips";
+
+export const useAutoRotateTips = (): TooltipContent => {
+ const { t } = useTranslation();
+
+ return {
+ header: {
+ title: t("autoRotate.tooltip.header.title", "Auto Rotate"),
+ },
+ tips: [
+ {
+ description: t(
+ "autoRotate.tooltip.description.text",
+ "Works out which way up each page should be and turns it the right way round. Pages that are already upright are left alone.",
+ ),
+ },
+ {
+ title: t("autoRotate.tooltip.detectionMode.title", "Detection method"),
+ description: t(
+ "autoRotate.tooltip.detectionMode.text",
+ "Auto reads the text on the page first, then looks at the page as an image if that is not enough. Text only skips the image check, which is quickest for documents that were never scanned. OCR only treats every page as an image.",
+ ),
+ },
+ {
+ title: t(
+ "autoRotate.tooltip.confidenceThreshold.title",
+ "Confidence threshold",
+ ),
+ description: t(
+ "autoRotate.tooltip.confidenceThreshold.text",
+ "How certain the check has to be before a page is turned. Lower it to rotate more pages, raise it to leave more pages untouched.",
+ ),
+ },
+ {
+ title: t(
+ "autoRotate.tooltip.inferUndetected.title",
+ "Rotate low confidence pages to match",
+ ),
+ description: t(
+ "autoRotate.tooltip.inferUndetected.text",
+ "Blank or nearly blank pages cannot be checked on their own. When every page that could be read needs the same turn, these pages are turned to match them.",
+ ),
+ },
+ ],
+ };
+};
diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
index 120f955b42..16b69d6983 100644
--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
@@ -45,6 +45,7 @@ import { usePrototypeToolRegistry } from "@app/data/usePrototypeToolRegistry";
import { flattenOperationConfig } from "@app/hooks/tools/flatten/useFlattenOperation";
import { redactOperationConfig } from "@app/hooks/tools/redact/useRedactOperation";
import { rotateOperationConfig } from "@app/hooks/tools/rotate/useRotateOperation";
+import { autoRotateOperationConfig } from "@app/hooks/tools/autoRotate/useAutoRotateOperation";
import { changeMetadataOperationConfig } from "@app/hooks/tools/changeMetadata/useChangeMetadataOperation";
import { signOperationConfig } from "@app/hooks/tools/sign/useSignOperation";
import { cropOperationConfig } from "@app/hooks/tools/crop/useCropOperation";
@@ -634,6 +635,31 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
),
synonyms: getSynonyms(t, "rotate"),
},
+ autoRotate: {
+ icon: (
+ <LocalIcon
+ icon="screen-rotation-alt-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
+ ),
+ name: t("home.autoRotate.title", "Auto Rotate"),
+ component: lazy(() => import("@app/tools/AutoRotate")),
+ description: t(
+ "home.autoRotate.desc",
+ "Detect each page's orientation and rotate it upright automatically.",
+ ),
+ categoryId: ToolCategoryId.STANDARD_TOOLS,
+ subcategoryId: SubcategoryId.PAGE_FORMATTING,
+ maxFiles: -1,
+ endpoints: ["auto-rotate-pdf"],
+ operationConfig: asRegistryConfig(autoRotateOperationConfig),
+ automationSettings: lazySettings(
+ () =>
+ import("@app/components/tools/autoRotate/AutoRotateAutomationSettings"),
+ ),
+ synonyms: getSynonyms(t, "autoRotate"),
+ },
split: {
icon: (
<LocalIcon
diff --git a/frontend/editor/src/core/hooks/tools/autoRotate/useAutoRotateOperation.ts b/frontend/editor/src/core/hooks/tools/autoRotate/useAutoRotateOperation.ts
new file mode 100644
index 0000000000..6460a66cfa
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/autoRotate/useAutoRotateOperation.ts
@@ -0,0 +1,175 @@
+import { useState, useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import apiClient from "@app/services/apiClient";
+import {
+ getPdfiumModule,
+ openRawDocumentSafe,
+ setPageRotation,
+ degreesToPdfiumRotation,
+ saveRawDocument,
+ closeDocAndFreeBuffer,
+} from "@app/services/pdfiumService";
+import {
+ useToolOperation,
+ defineCustomTool,
+ CustomProcessorResult,
+ ToolOperationHook,
+} from "@app/hooks/tools/shared/useToolOperation";
+import { createStandardErrorHandler } from "@app/utils/toolErrorHandler";
+import {
+ AutoRotateParameters,
+ defaultParameters,
+} from "@app/hooks/tools/autoRotate/useAutoRotateParameters";
+
+export const AUTO_ROTATE_ENDPOINT = "/api/v1/misc/auto-rotate-pdf";
+
+export type AutoRotateMethod = "text" | "osd" | "inferred" | "none";
+
+/** Mirrors the backend's AutoRotateAnalysisResult.PageResult. */
+export interface AutoRotatePageResult {
+ pageNumber: number;
+ currentRotation: number;
+ correction: number;
+ /** Percentage of glyphs sharing a direction (text) or Tesseract OSD score (osd). */
+ confidence: number | null;
+ method: AutoRotateMethod;
+ apply: boolean;
+ note?: string | null;
+}
+
+export interface AutoRotateReport {
+ pages: AutoRotatePageResult[];
+ totalPages: number;
+ pagesToRotate: number;
+ detectedByText: number;
+ detectedByOsd: number;
+ inferred: number;
+ undetected: number;
+}
+
+/**
+ * Detection needs the server (page rendering and OCR); setting /Rotate does not.
+ * So the file is uploaded once for the analysis pass and the resulting rotations
+ * are applied in the browser with PDFium, as the page editor does. Uploading a
+ * second time to apply would double the bandwidth, the PDFBox load and the job's
+ * resource accounting for what amounts to one dictionary entry per page.
+ *
+ * onReport receives the report from the analysis pass; the registry (automation)
+ * config passes no callback.
+ */
+const createAutoRotateProcessor =
+ (onReport?: (report: AutoRotateReport, fileName: string) => void) =>
+ async (
+ parameters: AutoRotateParameters,
+ files: File[],
+ ): Promise<CustomProcessorResult> => {
+ const outputs: File[] = [];
+
+ for (const inputFile of files) {
+ const analysisForm = new FormData();
+ analysisForm.append("fileInput", inputFile);
+ analysisForm.append("detectionMode", parameters.detectionMode);
+ analysisForm.append(
+ "confidenceThreshold",
+ String(parameters.confidenceThreshold),
+ );
+ analysisForm.append(
+ "inferUndetected",
+ String(parameters.inferUndetected),
+ );
+ analysisForm.append("dryRun", "true");
+
+ const analysis = await apiClient.post<AutoRotateReport>(
+ AUTO_ROTATE_ENDPOINT,
+ analysisForm,
+ );
+ const report = analysis.data;
+ onReport?.(report, inputFile.name);
+
+ // The report carries each page's existing rotation, so the absolute target
+ // is known without reading the PDF. Corrections are additive, matching the
+ // server's own apply path.
+ const targets = report.pages
+ .filter((page) => page.apply && page.correction !== 0)
+ .map((page) => ({
+ pageIndex: page.pageNumber - 1,
+ absoluteRotation:
+ (((page.currentRotation + page.correction) % 360) + 360) % 360,
+ }));
+
+ // Nothing to fix: pass the input through unchanged so the flow completes
+ // and the report explains why (all upright, or nothing detected).
+ if (targets.length === 0) {
+ outputs.push(inputFile);
+ continue;
+ }
+
+ const pdfium = await getPdfiumModule();
+ const docPtr = await openRawDocumentSafe(await inputFile.arrayBuffer());
+ try {
+ for (const { pageIndex, absoluteRotation } of targets) {
+ await setPageRotation(
+ docPtr,
+ pageIndex,
+ degreesToPdfiumRotation(absoluteRotation),
+ );
+ }
+ const rotatedBytes = await saveRawDocument(docPtr);
+ const baseName = inputFile.name.replace(/\.pdf$/i, "");
+ outputs.push(
+ new File([rotatedBytes], `${baseName}_auto_rotated.pdf`, {
+ type: "application/pdf",
+ }),
+ );
+ } finally {
+ closeDocAndFreeBuffer(pdfium, docPtr);
+ }
+ }
+
+ return { files: outputs, consumedAllInputs: true };
+ };
+
+// Static config for the registry/automation: same processing, no report UI.
+export const autoRotateOperationConfig = defineCustomTool<AutoRotateParameters>(
+ {
+ operationType: "autoRotate",
+ endpoint: AUTO_ROTATE_ENDPOINT,
+ customProcessor: createAutoRotateProcessor(),
+ defaultParameters,
+ },
+);
+
+export interface AutoRotateOperationHook extends ToolOperationHook<AutoRotateParameters> {
+ /** Per-file detection reports from the last run, keyed in run order. */
+ reports: { fileName: string; report: AutoRotateReport }[];
+}
+
+export const useAutoRotateOperation = (): AutoRotateOperationHook => {
+ const { t } = useTranslation();
+ const [reports, setReports] = useState<
+ { fileName: string; report: AutoRotateReport }[]
+ >([]);
+
+ const onReport = useCallback((report: AutoRotateReport, fileName: string) => {
+ setReports((previous) => [...previous, { fileName, report }]);
+ }, []);
+
+ const operation = useToolOperation<AutoRotateParameters>({
+ ...autoRotateOperationConfig,
+ customProcessor: useCallback(
+ async (parameters: AutoRotateParameters, files: File[]) => {
+ setReports([]);
+ return createAutoRotateProcessor(onReport)(parameters, files);
+ },
+ [onReport],
+ ),
+ getErrorMessage: createStandardErrorHandler(
+ t(
+ "autoRotate.error.failed",
+ "An error occurred while auto-rotating the PDF.",
+ ),
+ ),
+ });
+
+ return { ...operation, reports };
+};
diff --git a/frontend/editor/src/core/hooks/tools/autoRotate/useAutoRotateParameters.ts b/frontend/editor/src/core/hooks/tools/autoRotate/useAutoRotateParameters.ts
new file mode 100644
index 0000000000..fd61395eb1
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/autoRotate/useAutoRotateParameters.ts
@@ -0,0 +1,31 @@
+import { BaseParameters } from "@app/types/parameters";
+import {
+ useBaseParameters,
+ BaseParametersHook,
+} from "@app/hooks/tools/shared/useBaseParameters";
+
+export type AutoRotateDetectionMode = "auto" | "text" | "osd";
+
+export interface AutoRotateParameters extends BaseParameters {
+ /** auto = embedded-text direction first, OSD fallback; text/osd force one method. */
+ detectionMode: AutoRotateDetectionMode;
+ /** Minimum Tesseract OSD confidence before a correction is applied. */
+ confidenceThreshold: number;
+ /** Give undetected pages the document's consensus rotation when its pages agree. */
+ inferUndetected: boolean;
+}
+
+export const defaultParameters: AutoRotateParameters = {
+ detectionMode: "auto",
+ confidenceThreshold: 14,
+ inferUndetected: true,
+};
+
+export type AutoRotateParametersHook = BaseParametersHook<AutoRotateParameters>;
+
+export const useAutoRotateParameters = (): AutoRotateParametersHook =>
+ useBaseParameters({
+ defaultParameters,
+ endpointName: "auto-rotate-pdf",
+ validateFn: (params) => params.confidenceThreshold >= 0,
+ });
diff --git a/frontend/editor/src/core/services/pdfExportService.ts b/frontend/editor/src/core/services/pdfExportService.ts
index 1883d9efc9..2e32319207 100644
--- a/frontend/editor/src/core/services/pdfExportService.ts
+++ b/frontend/editor/src/core/services/pdfExportService.ts
@@ -5,6 +5,7 @@ import {
saveRawDocument,
importPages,
setPageRotation,
+ degreesToPdfiumRotation,
addNewPage,
} from "@app/services/pdfiumService";
import { downloadFileWithPolicy } from "@app/services/exportWithPolicy";
@@ -354,22 +355,5 @@ export class PDFExportService {
}
}
-/**
- * Convert degrees (0, 90, 180, 270) to PDFium rotation enum (0, 1, 2, 3).
- */
-function degreesToPdfiumRotation(degrees: number): number {
- const normalized = ((degrees % 360) + 360) % 360;
- switch (normalized) {
- case 90:
- return 1;
- case 180:
- return 2;
- case 270:
- return 3;
- default:
- return 0;
- }
-}
-
// Export singleton instance
export const pdfExportService = new PDFExportService();
diff --git a/frontend/editor/src/core/services/pdfiumService.ts b/frontend/editor/src/core/services/pdfiumService.ts
index 107e36d8ca..a9a44c693b 100644
--- a/frontend/editor/src/core/services/pdfiumService.ts
+++ b/frontend/editor/src/core/services/pdfiumService.ts
@@ -1165,6 +1165,24 @@ export async function importPages(
);
}
+/**
+ * Convert degrees (0, 90, 180, 270) to the PDFium rotation enum (0, 1, 2, 3).
+ * Lives here beside setPageRotation, which is the only thing that consumes it.
+ */
+export function degreesToPdfiumRotation(degrees: number): number {
+ const normalized = ((degrees % 360) + 360) % 360;
+ switch (normalized) {
+ case 90:
+ return 1;
+ case 180:
+ return 2;
+ case 270:
+ return 3;
+ default:
+ return 0;
+ }
+}
+
/**
* Set page rotation on a raw document.
* @param rotation 0, 1, 2, 3 for 0°, 90°, 180°, 270°
diff --git a/frontend/editor/src/core/tools/AutoRotate.tsx b/frontend/editor/src/core/tools/AutoRotate.tsx
new file mode 100644
index 0000000000..ac0643ea43
--- /dev/null
+++ b/frontend/editor/src/core/tools/AutoRotate.tsx
@@ -0,0 +1,70 @@
+import { useTranslation } from "react-i18next";
+import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
+import AutoRotateSettings from "@app/components/tools/autoRotate/AutoRotateSettings";
+import AutoRotateReport from "@app/components/tools/autoRotate/AutoRotateReport";
+import { useAutoRotateParameters } from "@app/hooks/tools/autoRotate/useAutoRotateParameters";
+import { useAutoRotateOperation } from "@app/hooks/tools/autoRotate/useAutoRotateOperation";
+import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";
+import { BaseToolProps, ToolComponent } from "@app/types/tool";
+import { useAutoRotateTips } from "@app/components/tooltips/useAutoRotateTips";
+
+const AutoRotate = (props: BaseToolProps) => {
+ const { t } = useTranslation();
+ const autoRotateTips = useAutoRotateTips();
+
+ // Instantiated here (not inside useBaseTool) so the component can read the
+ // per-page detection reports the operation hook additionally exposes.
+ const operation = useAutoRotateOperation();
+
+ const base = useBaseTool(
+ "autoRotate",
+ useAutoRotateParameters,
+ () => operation,
+ props,
+ );
+
+ return createToolFlow({
+ files: {
+ selectedFiles: base.selectedFiles,
+ isCollapsed: base.hasResults,
+ },
+ steps: [
+ {
+ title: t("autoRotate.settings.title", "Settings"),
+ isCollapsed: base.settingsCollapsed,
+ onCollapsedClick: base.settingsCollapsed
+ ? base.handleSettingsReset
+ : undefined,
+ tooltip: autoRotateTips,
+ content: (
+ <AutoRotateSettings
+ parameters={base.params}
+ disabled={base.endpointLoading}
+ />
+ ),
+ },
+ {
+ title: t("autoRotate.report.title", "Detection report"),
+ isVisible: base.hasResults && operation.reports.length > 0,
+ content: <AutoRotateReport reports={operation.reports} />,
+ },
+ ],
+ executeButton: {
+ text: t("autoRotate.submit", "Auto Rotate"),
+ isVisible: !base.hasResults,
+ loadingText: t("loading"),
+ onClick: base.handleExecute,
+ endpointEnabled: base.endpointEnabled,
+ paramsValid: base.params.validateParameters(),
+ },
+ review: {
+ isVisible: base.hasResults,
+ operation: base.operation,
+ title: t("autoRotate.results.title", "Auto Rotate Results"),
+ onFileClick: base.handleThumbnailClick,
+ onUndo: base.handleUndo,
+ },
+ });
+};
+
+export default AutoRotate as ToolComponent;
diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.ts
index d62e13b20f..af7339d936 100644
--- a/frontend/editor/src/core/types/toolApiTypes.ts
+++ b/frontend/editor/src/core/types/toolApiTypes.ts
@@ -201,6 +201,41 @@ export interface AddWatermarkRequest {
*/
widthSpacer?: number;
}
+export interface AutoRotatePdfRequest {
+ /**
+ * Minimum Tesseract OSD orientation confidence required before a correction is applied. Matches OCRmyPDF's --rotate-pages-threshold scale
+ */
+ confidenceThreshold?: number;
+ /**
+ * Detection method. 'auto' tries embedded-text direction first and falls back to Tesseract OSD for pages without usable text; 'text' uses only embedded-text direction; 'osd' forces Tesseract OSD for every page
+ */
+ detectionMode?: "auto" | "text" | "osd";
+ /**
+ * If true, no rotation is applied; returns a JSON report of the per-page detection results instead of a PDF
+ */
+ dryRun?: boolean;
+ /**
+ * When a page cannot be decided on its own but the pages that could be decided agree on a single correction for that same current rotation, apply that shared correction to the undecided page. Handles documents rotated uniformly where some pages are too sparse to detect alone
+ */
+ inferUndetected?: boolean;
+ /**
+ * Optional pre-computed corrections to apply without running detection. Pages not listed are left unchanged, and a page may only appear once
+ */
+ pageRotations?: PageRotation[];
+}
+/**
+ * Optional pre-computed corrections to apply without running detection. Pages not listed are left unchanged, and a page may only appear once
+ */
+export interface PageRotation {
+ /**
+ * 1-based page number to rotate
+ */
+ pageNumber: number;
+ /**
+ * Additional clockwise rotation to add to the page's current rotation, in degrees. Must be a multiple of 90
+ */
+ rotation: number;
+}
export interface AutoSplitPdfRequest {
/**
* Flag indicating if the duplex mode is active, where the page after the divider also gets removed.
@@ -1373,6 +1408,7 @@ export type ToolEndpoint =
| "/api/v1/misc/add-page-numbers"
| "/api/v1/misc/add-stamp"
| "/api/v1/misc/auto-rename"
+ | "/api/v1/misc/auto-rotate-pdf"
| "/api/v1/misc/auto-split-pdf"
| "/api/v1/misc/compress-pdf"
| "/api/v1/misc/decompress-pdf"
@@ -1463,6 +1499,7 @@ export interface ToolApiParams {
"/api/v1/misc/add-page-numbers": AddPageNumbersRequest;
"/api/v1/misc/add-stamp": AddStampRequest;
"/api/v1/misc/auto-rename": ExtractHeaderRequest;
+ "/api/v1/misc/auto-rotate-pdf": AutoRotatePdfRequest;
"/api/v1/misc/auto-split-pdf": AutoSplitPdfRequest;
"/api/v1/misc/compress-pdf": OptimizePdfRequest;
"/api/v1/misc/decompress-pdf": MiscDecompressPdfRequest;
@@ -1554,6 +1591,7 @@ export const TOOL_ENDPOINTS = [
"/api/v1/misc/add-page-numbers",
"/api/v1/misc/add-stamp",
"/api/v1/misc/auto-rename",
+ "/api/v1/misc/auto-rotate-pdf",
"/api/v1/misc/auto-split-pdf",
"/api/v1/misc/compress-pdf",
"/api/v1/misc/decompress-pdf",
diff --git a/frontend/editor/src/core/types/toolId.ts b/frontend/editor/src/core/types/toolId.ts
index 1fc231b427..13799ad869 100644
--- a/frontend/editor/src/core/types/toolId.ts
+++ b/frontend/editor/src/core/types/toolId.ts
@@ -31,6 +31,7 @@ export const CORE_REGULAR_TOOL_IDS = [
"ocr",
"addImage",
"rotate",
+ "autoRotate",
"annotate",
"scannerImageSplit",
"editTableOfContents",