#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
feat(page-scale): Custom page size for Scale Pages (#8489)
EthanHealy01c9c023ee2bfe
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.javaindex 16b72e8745..f0f2fbb0b3 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java@@ -47,6 +47,11 @@ public class ScalePagesController {private final CustomPDFDocumentFactory pdfDocumentFactory;private final TempFileManager tempFileManager;+ private static final float POINTS_PER_INCH = 72f;+ // ISO 32000-1 Annex C page size limits; the frontend validator mirrors them.+ private static final float MIN_CUSTOM_SIDE_POINTS = 3f;+ private static final float MAX_CUSTOM_SIDE_POINTS = 200 * POINTS_PER_INCH;+private static boolean keepsPageSize(String targetPDRectangle) {return targetPDRectangle == null|| targetPDRectangle.isBlank()@@ -61,19 +66,56 @@ public class ScalePagesController {return new PDRectangle(mediaBox.getWidth(), mediaBox.getHeight());}- private static PDRectangle getTargetSize(String targetPDRectangle, String orientation) {+ private static PDRectangle getTargetSize(ScalePagesRequest request) {+ String targetPDRectangle = request.getPageSize();+ if ("CUSTOM".equals(targetPDRectangle)) {+ // Explicit dimensions define orientation, so the orientation parameter is ignored.+ return getCustomSize(request);+ }Map<String, PDRectangle> sizeMap = getSizeMap();PDRectangle base = sizeMap.get(targetPDRectangle);if (base == null) {throw ExceptionUtils.createInvalidPageSizeException(targetPDRectangle);}- if ("LANDSCAPE".equalsIgnoreCase(orientation)) {+ if ("LANDSCAPE".equalsIgnoreCase(request.getOrientation())) {return new PDRectangle(base.getHeight(), base.getWidth());}return base;}+ private static PDRectangle getCustomSize(ScalePagesRequest request) {+ String unit = request.getCustomUnit();+ float pointsPerUnit =+ switch (unit) {+ case "mm" -> POINTS_PER_INCH / 25.4f;+ case "cm" -> POINTS_PER_INCH / 2.54f;+ case "in" -> POINTS_PER_INCH;+ case null, default ->+ throw ExceptionUtils.createInvalidArgumentException(+ "customUnit", String.valueOf(unit));+ };+ return new PDRectangle(+ toCustomSidePoints("customWidth", request.getCustomWidth(), pointsPerUnit),+ toCustomSidePoints("customHeight", request.getCustomHeight(), pointsPerUnit));+ }++ private static float toCustomSidePoints(String name, Float value, float pointsPerUnit) {+ if (value == null) {+ throw ExceptionUtils.createInvalidArgumentException(+ name, "required when pageSize is CUSTOM");+ }+ float points = value * pointsPerUnit;+ // False for NaN, so NaN is rejected too.+ boolean withinAllowedRange =+ points >= MIN_CUSTOM_SIDE_POINTS && points <= MAX_CUSTOM_SIDE_POINTS;+ if (!withinAllowedRange) {+ throw ExceptionUtils.createInvalidArgumentException(+ name, value + " (must be between 3 points and 200 inches)");+ }+ return points;+ }+private static Map<String, PDRectangle> getSizeMap() {Map<String, PDRectangle> sizeMap = new HashMap<>();sizeMap.put("A0", PDRectangle.A0);@@ -101,19 +143,17 @@ public class ScalePagesController {public ResponseEntity<Resource> scalePages(@ModelAttribute ScalePagesRequest request)throws IOException {MultipartFile file = request.getFileInput();- String targetPDRectangle = request.getPageSize();- String orientation = request.getOrientation();float scaleFactor = request.getScaleFactor();try (PDDocument sourceDocument = pdfDocumentFactory.load(file);PDDocument outputDocument =pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {- boolean keepSize = keepsPageSize(targetPDRectangle);+ boolean keepSize = keepsPageSize(request.getPageSize());if (keepSize && sourceDocument.getNumberOfPages() == 0) {throw ExceptionUtils.createPdfNoPages();}- PDRectangle fixedSize = keepSize ? null : getTargetSize(targetPDRectangle, orientation);+ PDRectangle fixedSize = keepSize ? null : getTargetSize(request);// Create LayerUtility once outside the loop for better performanceLayerUtility layerUtility = new LayerUtility(outputDocument);diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.javaindex 269a709da0..a72e6859fd 100644--- a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java@@ -14,14 +14,17 @@ public class PDFWithPageSize extends PDFFile {@Schema(description ="The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER,"- + " LEGAL, KEEP. KEEP keeps each page's own size.",+ + " LEGAL, KEEP, CUSTOM. KEEP keeps each page's own size.",defaultValue = "KEEP",- allowableValues = {"A0", "A1", "A2", "A3", "A4", "A5", "A6", "LETTER", "LEGAL", "KEEP"})+ allowableValues = {+ "A0", "A1", "A2", "A3", "A4", "A5", "A6", "LETTER", "LEGAL", "KEEP", "CUSTOM"+ })private String pageSize = "KEEP";@Schema(description =- "Orientation to apply to the target page size. Ignored when pageSize is KEEP.",+ "Orientation to apply to the target page size. Ignored when pageSize is KEEP or"+ + " CUSTOM.",defaultValue = "PORTRAIT",allowableValues = {"PORTRAIT", "LANDSCAPE"})private String orientation = "PORTRAIT";diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.javaindex c5f9018e8e..184f46ef65 100644--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java@@ -18,4 +18,26 @@ public class ScalePagesRequest extends PDFWithPageSize {"The scale of the content on the pages of the output PDF. Acceptable values are"+ " floats.")private float scaleFactor = 1f;++ @Schema(+ minimum = "0",+ exclusiveMinimum = true,+ description =+ "Width of the output pages in customUnit. Required when pageSize is CUSTOM;"+ + " between 3 points (about 1.06 mm) and 200 inches.")+ private Float customWidth;++ @Schema(+ minimum = "0",+ exclusiveMinimum = true,+ description =+ "Height of the output pages in customUnit. Required when pageSize is CUSTOM;"+ + " between 3 points (about 1.06 mm) and 200 inches.")+ private Float customHeight;++ @Schema(+ defaultValue = "mm",+ allowableValues = {"mm", "cm", "in"},+ description = "Unit of customWidth and customHeight.")+ private String customUnit = "mm";}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.javaindex 09476aa279..d89b39d010 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java@@ -11,9 +11,11 @@ import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;+import org.apache.pdfbox.Loader;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.PDPageContentStream;@@ -57,9 +59,9 @@ class ScalePagesControllerTest {return ResponseEntity.ok(new ByteArrayResource(bytes));}- private static byte[] drainBody(ResponseEntity<Resource> response) throws java.io.IOException {- java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();- try (java.io.InputStream __in = response.getBody().getInputStream()) {+ private static byte[] drainBody(ResponseEntity<Resource> response) throws IOException {+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ try (InputStream __in = response.getBody().getInputStream()) {__in.transferTo(baos);}return baos.toByteArray();@@ -102,7 +104,7 @@ class ScalePagesControllerTest {.thenAnswer(inv -> {byte[] bytes = ((MultipartFile) inv.getArgument(0)).getBytes();- return org.apache.pdfbox.Loader.loadPDF(bytes);+ return Loader.loadPDF(bytes);});when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(any(PDDocument.class))).thenAnswer(inv -> new PDDocument());@@ -389,6 +391,78 @@ class ScalePagesControllerTest {assertEquals(200, response.getStatusCode().value());}+ @ParameterizedTest+ @CsvSource({+ "in, 8.5, 11, 612, 792",+ "mm, 210, 297, 595.28, 841.89",+ "cm, 20, 10, 566.93, 283.46",+ "mm, 5080, 1.06, 14400, 3.00"+ })+ void testScalePages_CustomSize(+ String unit, float width, float height, float expectedWidth, float expectedHeight)+ throws Exception {+ setupFactory();+ ScalePagesRequest request = customSizeRequest(unit, width, height);+ request.setOrientation("LANDSCAPE");++ try (PDDocument output = Loader.loadPDF(drainBody(controller.scalePages(request)))) {+ PDRectangle mediaBox = output.getPage(0).getMediaBox();+ assertEquals(expectedWidth, mediaBox.getWidth(), 0.01);+ assertEquals(expectedHeight, mediaBox.getHeight(), 0.01);+ }+ }++ @ParameterizedTest+ @CsvSource(+ value = {+ "mm, , 100",+ "mm, 0, 100",+ "mm, -5, 100",+ "mm, 1, 100",+ "in, 201, 10",+ "mm, NaN, 100",+ "in, Infinity, 10",+ "ft, 1, 1"+ },+ nullValues = "")+ void testScalePages_CustomSizeRejectsInvalidInput(String unit, Float width, Float height)+ throws Exception {+ setupFactory();+ ScalePagesRequest request = customSizeRequest(unit, width, height);++ assertThrows(IllegalArgumentException.class, () -> controller.scalePages(request));+ }++ @Test+ void testScalePages_PresetSizeIgnoresCustomFields() throws Exception {+ setupFactory();+ ScalePagesRequest request = customSizeRequest("ft", -5f, null);+ request.setPageSize("LETTER");++ try (PDDocument output = Loader.loadPDF(drainBody(controller.scalePages(request)))) {+ PDRectangle mediaBox = output.getPage(0).getMediaBox();+ assertEquals(PDRectangle.LETTER.getWidth(), mediaBox.getWidth(), 0.01);+ assertEquals(PDRectangle.LETTER.getHeight(), mediaBox.getHeight(), 0.01);+ }+ }++ private ScalePagesRequest customSizeRequest(String unit, Float width, Float height)+ throws IOException {+ ScalePagesRequest request = new ScalePagesRequest();+ request.setFileInput(+ new MockMultipartFile(+ "fileInput",+ "test.pdf",+ MediaType.APPLICATION_PDF_VALUE,+ createRealPdf(PDRectangle.A4, 1)));+ request.setPageSize("CUSTOM");+ request.setCustomUnit(unit);+ request.setCustomWidth(width);+ request.setCustomHeight(height);+ request.setScaleFactor(1.0f);+ return request;+ }+@ParameterizedTest@CsvSource({"0, false, KEEP, PORTRAIT, 1",@@ -404,12 +478,9 @@ class ScalePagesControllerTest {setupFactory();byte[] stamped = createSignaturePdf(true, rotation, cropped);byte[] embedded = createSignaturePdf(false, rotation, cropped);- try (PDDocument actual =- org.apache.pdfbox.Loader.loadPDF(- scalePdf(stamped, size, orientation, scale));+ try (PDDocument actual = Loader.loadPDF(scalePdf(stamped, size, orientation, scale));PDDocument expected =- org.apache.pdfbox.Loader.loadPDF(- scalePdf(embedded, size, orientation, scale))) {+ Loader.loadPDF(scalePdf(embedded, size, orientation, scale))) {assertEquals(2, actual.getNumberOfPages());assertTrue(new PDFTextStripper()@@ -462,8 +533,7 @@ class ScalePagesControllerTest {@ValueSource(strings = {"hidden", "noView", "missingAppearance", "emptyBounds"})void skipsNonVisibleStampAppearances(String kind) throws Exception {setupFactory();- try (PDDocument source =- org.apache.pdfbox.Loader.loadPDF(createSignaturePdf(true, 0, false))) {+ try (PDDocument source = Loader.loadPDF(createSignaturePdf(true, 0, false))) {for (PDPage page : source.getPages()) {var stamp = page.getAnnotations().getFirst();switch (kind) {@@ -478,8 +548,7 @@ class ScalePagesControllerTest {ByteArrayOutputStream bytes = new ByteArrayOutputStream();source.save(bytes);try (PDDocument output =- org.apache.pdfbox.Loader.loadPDF(- scalePdf(bytes.toByteArray(), "KEEP", "PORTRAIT", 1))) {+ Loader.loadPDF(scalePdf(bytes.toByteArray(), "KEEP", "PORTRAIT", 1))) {BufferedImage rendered = new PDFRenderer(output).renderImage(0);assertEquals(Color.WHITE.getRGB(), rendered.getRGB(75, 275));assertTrue(new PDFTextStripper().getText(output).contains("Searchable text"));@@ -491,8 +560,7 @@ class ScalePagesControllerTest {@ValueSource(booleans = {true, false})void preservesSignatureLayerVisibility(boolean enabled) throws Exception {setupFactory();- try (PDDocument source =- org.apache.pdfbox.Loader.loadPDF(createSignaturePdf(true, 0, false))) {+ try (PDDocument source = Loader.loadPDF(createSignaturePdf(true, 0, false))) {PDOptionalContentGroup layer = new PDOptionalContentGroup("Signatures");PDOptionalContentProperties layers = new PDOptionalContentProperties();layers.addGroup(layer);@@ -504,8 +572,7 @@ class ScalePagesControllerTest {ByteArrayOutputStream bytes = new ByteArrayOutputStream();source.save(bytes);try (PDDocument output =- org.apache.pdfbox.Loader.loadPDF(- scalePdf(bytes.toByteArray(), "KEEP", "PORTRAIT", 1))) {+ Loader.loadPDF(scalePdf(bytes.toByteArray(), "KEEP", "PORTRAIT", 1))) {PDOptionalContentProperties outputLayers =output.getDocumentCatalog().getOCProperties();assertNotNull(outputLayers);diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.pyindex ba785a7b46..e517d666fe 100644--- a/engine/src/stirling/models/tool_models.py+++ b/engine/src/stirling/models/tool_models.py@@ -1464,9 +1464,19 @@ class SanitizePdfParams(ApiModel):remove_xmp_metadata: bool = Field(False, description="Remove XMP metadata from the PDF")+class CustomUnit(StrEnum):+ """+ Unit of customWidth and customHeight.+ """++ mm = "mm"+ cm = "cm"+ in_ = "in"++class Orientation1(StrEnum):"""- Orientation to apply to the target page size. Ignored when pageSize is KEEP.+ Orientation to apply to the target page size. Ignored when pageSize is KEEP or CUSTOM."""portrait = "PORTRAIT"@@ -1475,7 +1485,7 @@ class Orientation1(StrEnum):class PageSize(StrEnum):"""- The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP. KEEP keeps each page's own size.+ The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP, CUSTOM. KEEP keeps each page's own size."""a0 = "A0"@@ -1488,6 +1498,7 @@ class PageSize(StrEnum):letter = "LETTER"legal = "LEGAL"keep = "KEEP"+ custom = "CUSTOM"class ScalePagesParams(ApiModel):@@ -1495,13 +1506,24 @@ class ScalePagesParams(ApiModel):This operation takes an input PDF file and the size to scale the pages to in the output PDF file. Input:PDF Output:PDF Type:SISO"""+ custom_height: float | None = Field(+ None,+ description="Height of the output pages in customUnit. Required when pageSize is CUSTOM; between 3 points (about 1.06 mm) and 200 inches.",+ gt=0.0,+ )+ custom_unit: CustomUnit = Field(CustomUnit.mm, description="Unit of customWidth and customHeight.")+ custom_width: float | None = Field(+ None,+ description="Width of the output pages in customUnit. Required when pageSize is CUSTOM; between 3 points (about 1.06 mm) and 200 inches.",+ gt=0.0,+ )orientation: Orientation1 = Field(Orientation1.portrait,- description="Orientation to apply to the target page size. Ignored when pageSize is KEEP.",+ description="Orientation to apply to the target page size. Ignored when pageSize is KEEP or CUSTOM.",)page_size: PageSize = Field(PageSize.keep,- description="The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP. KEEP keeps each page's own size.",+ description="The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP, CUSTOM. KEEP keeps each page's own size.",)scale_factor: float = Field(1, description="The scale of the content on the pages of the output PDF. Acceptable values are floats.", ge=0.0diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 268a09d61d..2982d741ff 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -512,6 +512,11 @@ submit = "Adjust Page Scale"tags = "resize,modify,dimension,adapt"title = "Adjust Page Scale"+[adjustPageScale.customSize]+height = "Height"+unit = "Unit"+width = "Width"+[adjustPageScale.error]failed = "An error occurred while adjusting the page scale."@@ -521,6 +526,7 @@ landscape = "Landscape"portrait = "Portrait"[adjustPageScale.pageSize]+custom = "Custom"keep = "Keep Original Size"label = "Target Page Size"legal = "Legal"@@ -540,7 +546,7 @@ title = "Description"title = "Page Scale Settings Overview"[adjustPageScale.tooltip.pageSize]-text = "Sets the dimensions of the output PDF pages. 'Keep Original Size' maintains current dimensions, while other options resize to standard paper sizes."+text = "Sets the dimensions of the output PDF pages. 'Keep Original Size' maintains current dimensions, 'Custom' uses the width and height you enter, and the other options resize to standard paper sizes."title = "Target Page Size"[adjustPageScale.tooltip.scaleFactor]diff --git a/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.stories.tsx b/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.stories.tsxindex bdedce4b07..073d567b79 100644--- a/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.stories.tsx+++ b/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.stories.tsx@@ -3,6 +3,7 @@ import AdjustPageScaleSettings from "@editor/components/tools/adjustPageScale/Adimport {AdjustPageScaleParameters,PageSize,+ defaultParameters as hookDefaultParameters,} from "@editor/hooks/tools/adjustPageScale/useAdjustPageScaleParameters";const meta = {@@ -14,6 +15,7 @@ export default meta;type Story = StoryObj<typeof meta>;const defaultParameters: AdjustPageScaleParameters = {+ ...hookDefaultParameters,scaleFactor: 1.0,pageSize: PageSize.KEEP,orientation: "PORTRAIT",@@ -29,6 +31,7 @@ export const Default: Story = {export const CustomPageSize: Story = {args: {parameters: {+ ...hookDefaultParameters,scaleFactor: 2.5,pageSize: PageSize.A4,orientation: "LANDSCAPE",diff --git a/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.test.tsx b/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.test.tsxindex e17eaf5d2e..f0d1ddbc62 100644--- a/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.test.tsx+++ b/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.test.tsx@@ -1,10 +1,13 @@import { describe, expect, test, vi, beforeEach } from "vitest";-import { render, screen } from "@testing-library/react";+import { useState } from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { MantineProvider } from "@mantine/core";import AdjustPageScaleSettings from "@editor/components/tools/adjustPageScale/AdjustPageScaleSettings";import {AdjustPageScaleParameters,PageSize,+ defaultParameters as hookDefaultParameters,} from "@editor/hooks/tools/adjustPageScale/useAdjustPageScaleParameters";// Mock useTranslation with predictable return values@@ -22,6 +25,7 @@ const TestWrapper = ({ children }: { children: React.ReactNode }) => (describe("AdjustPageScaleSettings", () => {const defaultParameters: AdjustPageScaleParameters = {+ ...hookDefaultParameters,scaleFactor: 1.0,pageSize: PageSize.KEEP,orientation: "PORTRAIT",@@ -50,6 +54,7 @@ describe("AdjustPageScaleSettings", () => {test("should render with custom parameters", () => {const customParameters: AdjustPageScaleParameters = {+ ...hookDefaultParameters,scaleFactor: 2.5,pageSize: PageSize.A4,orientation: "LANDSCAPE",@@ -67,5 +72,116 @@ describe("AdjustPageScaleSettings", () => {// Component renders successfully with custom parametersexpect(screen.getByText("Scale Factor")).toBeInTheDocument();expect(screen.getByText("Target Page Size")).toBeInTheDocument();+ expect(screen.queryByText("Width")).not.toBeInTheDocument();+ });++ test("shows width, height and unit inputs for a custom page size", () => {+ render(+ <TestWrapper>+ <AdjustPageScaleSettings+ parameters={{ ...defaultParameters, pageSize: PageSize.CUSTOM }}+ onParameterChange={mockOnParameterChange}+ />+ </TestWrapper>,+ );++ expect(screen.getByText("Width")).toBeInTheDocument();+ expect(screen.getByText("Height")).toBeInTheDocument();+ expect(+ screen.getByRole("radiogroup", { name: "Unit" }),+ ).toBeInTheDocument();+ });++ test("converts the width and height when the unit changes", () => {+ render(+ <TestWrapper>+ <AdjustPageScaleSettings+ parameters={{+ ...defaultParameters,+ pageSize: PageSize.CUSTOM,+ customWidth: 210,+ customHeight: 297,+ customUnit: "mm",+ }}+ onParameterChange={mockOnParameterChange}+ />+ </TestWrapper>,+ );++ fireEvent.click(screen.getByRole("radio", { name: "in" }));++ expect(mockOnParameterChange).toHaveBeenCalledWith("customWidth", 8.27);+ expect(mockOnParameterChange).toHaveBeenCalledWith("customHeight", 11.69);+ expect(mockOnParameterChange).toHaveBeenCalledWith("customUnit", "in");+ });++ const renderControlled = () => {+ let latest: AdjustPageScaleParameters | undefined;+ const ControlledSettings = () => {+ const [parameters, setParameters] = useState<AdjustPageScaleParameters>({+ ...defaultParameters,+ pageSize: PageSize.CUSTOM,+ customWidth: 8.27,+ customHeight: 11.69,+ customUnit: "in",+ });+ latest = parameters;+ return (+ <AdjustPageScaleSettings+ parameters={parameters}+ onParameterChange={(key, value) =>+ setParameters((prev) => ({ ...prev, [key]: value }))+ }+ />+ );+ };+ render(+ <TestWrapper>+ <ControlledSettings />+ </TestWrapper>,+ );+ return () => latest;+ };++ test.each([+ ["Width", "customWidth"],+ ["Height", "customHeight"],+ ] as const)(+ "keeps a decimal point typed into the custom %s",+ async (label, key) => {+ const getParameters = renderControlled();+ const input = screen.getByRole<HTMLInputElement>("textbox", {+ name: label,+ });++ await userEvent.type(input, "8.5", {+ initialSelectionStart: 0,+ initialSelectionEnd: input.value.length,+ });++ expect(input).toHaveValue("8.5");+ expect(getParameters()?.[key]).toBe(8.5);+ },+ );++ test("reports an emptied dimension as zero so the size fails validation", async () => {+ const getParameters = renderControlled();++ await userEvent.clear(screen.getByRole("textbox", { name: "Width" }));++ expect(getParameters()?.customWidth).toBe(0);+ });++ test("shows the converted dimensions after a unit switch", () => {+ renderControlled();++ fireEvent.click(screen.getByRole("radio", { name: "mm" }));++ expect(screen.getByRole("textbox", { name: "Width" })).toHaveValue(+ "210.06",+ );+ expect(screen.getByRole("textbox", { name: "Height" })).toHaveValue(+ "296.93",+ );});});diff --git a/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.tsx b/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.tsxindex 5038699cad..2f9170c5a7 100644--- a/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.tsx+++ b/frontend/src/editor/core/components/tools/adjustPageScale/AdjustPageScaleSettings.tsx@@ -1,4 +1,5 @@-import { Stack, NumberInput, Select } from "@mantine/core";+import { useState } from "react";+import { Group, Stack, NumberInput, Select } from "@mantine/core";import {SegmentedControl,type SegmentedOption,@@ -6,11 +7,68 @@ import {import { useTranslation } from "react-i18next";import {AdjustPageScaleParameters,+ CustomSizeUnit,Orientation,PageSize,+ convertCustomSide,+ customSideLimits,} from "@editor/hooks/tools/adjustPageScale/useAdjustPageScaleParameters";import { Z_INDEX_AUTOMATE_DROPDOWN } from "@editor/styles/zIndex";+const CUSTOM_UNIT_OPTIONS: SegmentedOption<CustomSizeUnit>[] = [+ { value: "mm", label: "mm" },+ { value: "cm", label: "cm" },+ { value: "in", label: "in" },+];++interface CustomSideInputProps {+ label: string;+ value: number;+ onChange: (value: number) => void;+ min: number;+ max: number;+ disabled: boolean;+}++// Mantine reports a half-typed number such as "8." as a string. Feeding the+// parsed number back as the controlled value would erase the separator+// mid-keystroke, so the text lives in a local draft and is reset only when the+// value changes from outside, such as a unit switch.+const CustomSideInput = ({+ label,+ value,+ onChange,+ min,+ max,+ disabled,+}: CustomSideInputProps) => {+ const [draft, setDraft] = useState<number | string>(value);+ const [reported, setReported] = useState(value);+ if (value !== reported) {+ setReported(value);+ setDraft(value);+ }++ const handleChange = (next: number | string) => {+ const parsed = typeof next === "number" ? next : Number(next) || 0;+ setDraft(next);+ setReported(parsed);+ onChange(parsed);+ };++ return (+ <NumberInput+ label={label}+ value={draft}+ onChange={handleChange}+ min={min}+ max={max}+ decimalScale={2}+ disabled={disabled}+ />+ );+};+interface AdjustPageScaleSettingsProps {parameters: AdjustPageScaleParameters;onParameterChange: <K extends keyof AdjustPageScaleParameters>(@@ -28,6 +86,7 @@ const AdjustPageScaleSettings = ({const { t } = useTranslation();const isKeepSelected = parameters.pageSize === PageSize.KEEP;+ const isCustomSelected = parameters.pageSize === PageSize.CUSTOM;const pageSizeOptions = [{@@ -49,9 +108,28 @@ const AdjustPageScaleSettings = ({value: PageSize.LEGAL,label: t("adjustPageScale.pageSize.legal", "Legal"),},+ {+ value: PageSize.CUSTOM,+ label: t("adjustPageScale.pageSize.custom", "Custom"),+ },];- const orientationDisabled = disabled || isKeepSelected;+ const sideLimits = customSideLimits(parameters.customUnit);++ const handleCustomUnitChange = (unit: CustomSizeUnit) => {+ const from = parameters.customUnit;+ onParameterChange(+ "customWidth",+ convertCustomSide(parameters.customWidth, from, unit),+ );+ onParameterChange(+ "customHeight",+ convertCustomSide(parameters.customHeight, from, unit),+ );+ onParameterChange("customUnit", unit);+ };++ const orientationDisabled = disabled || isKeepSelected || isCustomSelected;const orientationOptions: SegmentedOption<Orientation>[] = [{value: "PORTRAIT",@@ -100,8 +178,39 @@ const AdjustPageScaleSettings = ({}}/>+ {isCustomSelected && (+ <>+ <Group grow>+ <CustomSideInput+ label={t("adjustPageScale.customSize.width", "Width")}+ value={parameters.customWidth}+ onChange={(value) => onParameterChange("customWidth", value)}+ min={sideLimits.min}+ max={sideLimits.max}+ disabled={disabled}+ />+ <CustomSideInput+ label={t("adjustPageScale.customSize.height", "Height")}+ value={parameters.customHeight}+ onChange={(value) => onParameterChange("customHeight", value)}+ min={sideLimits.min}+ max={sideLimits.max}+ disabled={disabled}+ />+ </Group>+ <SegmentedControl+ ariaLabel={t("adjustPageScale.customSize.unit", "Unit")}+ value={parameters.customUnit}+ onChange={handleCustomUnitChange}+ options={CUSTOM_UNIT_OPTIONS}+ disabled={disabled}+ fullWidth+ />+ </>+ )}+<SegmentedControl- aria-label={t("adjustPageScale.orientation.label", "Page orientation")}+ ariaLabel={t("adjustPageScale.orientation.label", "Page orientation")}value={parameters.orientation}onChange={(value) => onParameterChange("orientation", value)}options={orientationOptions}diff --git a/frontend/src/editor/core/components/tooltips/useAdjustPageScaleTips.ts b/frontend/src/editor/core/components/tooltips/useAdjustPageScaleTips.tsindex 50ab044667..82969e153b 100644--- a/frontend/src/editor/core/components/tooltips/useAdjustPageScaleTips.ts+++ b/frontend/src/editor/core/components/tooltips/useAdjustPageScaleTips.ts@@ -44,7 +44,7 @@ export const useAdjustPageScaleTips = (): TooltipContent => {title: t("adjustPageScale.tooltip.pageSize.title", "Target Page Size"),description: t("adjustPageScale.tooltip.pageSize.text",- "Sets the dimensions of the output PDF pages. 'Keep Original Size' maintains current dimensions, while other options resize to standard paper sizes.",+ "Sets the dimensions of the output PDF pages. 'Keep Original Size' maintains current dimensions, 'Custom' uses the width and height you enter, and the other options resize to standard paper sizes.",),},],diff --git a/frontend/src/editor/core/hooks/tools/adjustPageScale/adjustPageScaleFormData.ts b/frontend/src/editor/core/hooks/tools/adjustPageScale/adjustPageScaleFormData.tsindex 71e3395dca..b0e2920b57 100644--- a/frontend/src/editor/core/hooks/tools/adjustPageScale/adjustPageScaleFormData.ts+++ b/frontend/src/editor/core/hooks/tools/adjustPageScale/adjustPageScaleFormData.ts@@ -19,6 +19,11 @@ export const adjustPageScaleToApiParams = (scaleFactor: parameters.scaleFactor,pageSize: parameters.pageSize,orientation: parameters.orientation,+ ...(parameters.pageSize === PageSize.CUSTOM && {+ customWidth: parameters.customWidth,+ customHeight: parameters.customHeight,+ customUnit: parameters.customUnit,+ }),});export const adjustPageScaleFromApiParams = (@@ -27,6 +32,18 @@ export const adjustPageScaleFromApiParams = (scaleFactor: apiParams.scaleFactor,pageSize: apiParams.pageSize as PageSize,orientation: apiParams.orientation,+ // The backend omits these for preset sizes. Restoring parameters spreads the+ // result over the defaults, so an explicit undefined would wipe the+ // 210 x 297 mm fallback the Custom size option starts from.+ ...(apiParams.customWidth !== undefined && {+ customWidth: apiParams.customWidth,+ }),+ ...(apiParams.customHeight !== undefined && {+ customHeight: apiParams.customHeight,+ }),+ ...(apiParams.customUnit !== undefined && {+ customUnit: apiParams.customUnit,+ }),});export const buildAdjustPageScaleFormData = (diff --git a/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleOperation.test.ts b/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleOperation.test.tsindex d23696a083..ef095cdd8d 100644--- a/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleOperation.test.ts+++ b/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleOperation.test.ts@@ -48,6 +48,27 @@ describe("buildAdjustPageScaleFormData", () => {expect(formData.get("pageSize")).toBe("LEGAL");});+ it("sends the custom dimensions only when pageSize is CUSTOM", () => {+ const custom = buildAdjustPageScaleFormData(+ {+ ...defaultParameters,+ pageSize: PageSize.CUSTOM,+ customWidth: 100,+ customHeight: 50,+ customUnit: "cm",+ },+ stubFile(),+ );+ expect(custom.get("customWidth")).toBe("100");+ expect(custom.get("customHeight")).toBe("50");+ expect(custom.get("customUnit")).toBe("cm");++ const preset = buildAdjustPageScaleFormData(defaultParameters, stubFile());+ expect(preset.has("customWidth")).toBe(false);+ expect(preset.has("customHeight")).toBe(false);+ expect(preset.has("customUnit")).toBe(false);+ });+it("attaches the uploaded file under fileInput", () => {const file = stubFile();const formData = buildAdjustPageScaleFormData(defaultParameters, file);@@ -70,4 +91,19 @@ describe("adjustPageScale mappers", () => {expect(roundTripped).toEqual(api);});++ test("keeps the custom defaults when the backend used a preset size", () => {+ const api = adjustPageScaleToApiParams({+ ...defaultParameters,+ pageSize: PageSize.A4,+ });+ const restored = {+ ...defaultParameters,+ ...adjustPageScaleFromApiParams(api),+ };++ expect(restored.customWidth).toBe(defaultParameters.customWidth);+ expect(restored.customHeight).toBe(defaultParameters.customHeight);+ expect(restored.customUnit).toBe(defaultParameters.customUnit);+ });});diff --git a/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.test.ts b/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.test.tsindex 067c04f78c..454cc7827c 100644--- a/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.test.ts+++ b/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.test.ts@@ -5,6 +5,7 @@ import {defaultParameters,PageSize,AdjustPageScaleParametersHook,+ convertCustomSide,} from "@editor/hooks/tools/adjustPageScale/useAdjustPageScaleParameters";describe("useAdjustPageScaleParameters", () => {@@ -88,6 +89,40 @@ describe("useAdjustPageScaleParameters", () => {},expected: true,},+ {+ description: "with custom page size missing a width",+ setup: (hook: AdjustPageScaleParametersHook) => {+ hook.updateParameter("pageSize", PageSize.CUSTOM);+ hook.updateParameter("customWidth", 0);+ },+ expected: false,+ },+ {+ description: "with custom page size over 200 inches",+ setup: (hook: AdjustPageScaleParametersHook) => {+ hook.updateParameter("pageSize", PageSize.CUSTOM);+ hook.updateParameter("customUnit", "in");+ hook.updateParameter("customWidth", 200.01);+ },+ expected: false,+ },+ {+ description: "with custom page size at 200 inches",+ setup: (hook: AdjustPageScaleParametersHook) => {+ hook.updateParameter("pageSize", PageSize.CUSTOM);+ hook.updateParameter("customUnit", "mm");+ hook.updateParameter("customWidth", 5080);+ },+ expected: true,+ },+ {+ description: "with custom page size under 3 points",+ setup: (hook: AdjustPageScaleParametersHook) => {+ hook.updateParameter("pageSize", PageSize.CUSTOM);+ hook.updateParameter("customHeight", 1);+ },+ expected: false,+ },{description: "with invalid scale factor 0",setup: (hook: AdjustPageScaleParametersHook) => {@@ -150,3 +185,24 @@ describe("useAdjustPageScaleParameters", () => {expect(result.current.validateParameters()).toBe(false);});});++describe("convertCustomSide", () => {+ test.each([+ { value: 210, from: "mm" as const, to: "in" as const, expected: 8.27 },+ { value: 210, from: "mm" as const, to: "cm" as const, expected: 21 },+ { value: 8.5, from: "in" as const, to: "mm" as const, expected: 215.9 },+ ])(+ "converts $value $from to $expected $to",+ ({ value, from, to, expected }) => {+ expect(convertCustomSide(value, from, to)).toBe(expected);+ },+ );++ test("clamps a rounded result that falls below the target unit's minimum", () => {+ expect(convertCustomSide(1.06, "mm", "in")).toBe(0.05);+ });++ test("leaves a missing side missing", () => {+ expect(convertCustomSide(0, "mm", "in")).toBe(0);+ });+});diff --git a/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.ts b/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.tsindex 4d64ce4c03..e40c9b2327 100644--- a/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.ts+++ b/frontend/src/editor/core/hooks/tools/adjustPageScale/useAdjustPageScaleParameters.ts@@ -15,30 +15,94 @@ export enum PageSize {A6 = "A6",LETTER = "LETTER",LEGAL = "LEGAL",+ CUSTOM = "CUSTOM",}export type Orientation = "PORTRAIT" | "LANDSCAPE";+export type CustomSizeUnit = "mm" | "cm" | "in";+export interface AdjustPageScaleParameters extends BaseParameters {scaleFactor: number;pageSize: PageSize;orientation: Orientation;+ customWidth: number;+ customHeight: number;+ customUnit: CustomSizeUnit;}export const defaultParameters: AdjustPageScaleParameters = {scaleFactor: 1.0,pageSize: PageSize.KEEP,orientation: "PORTRAIT",+ customWidth: 210,+ customHeight: 297,+ customUnit: "mm",};export type AdjustPageScaleParametersHook =BaseParametersHook<AdjustPageScaleParameters>;+const UNITS_PER_INCH: Record<CustomSizeUnit, number> = {+ mm: 25.4,+ cm: 2.54,+ in: 1,+};++// Must match ScalePagesController: ISO 32000-1 Annex C bounds a page side to+// 3..14,400 points.+const MIN_CUSTOM_SIDE_INCHES = 3 / 72;+const MAX_CUSTOM_SIDE_INCHES = 200;++const roundToHundredths = (value: number) => Math.round(value * 100) / 100;++/** Smallest and largest side length the backend accepts, in `unit`, rounded inwards+ * to the two decimals the inputs allow. */+export function customSideLimits(unit: CustomSizeUnit): {+ min: number;+ max: number;+} {+ const unitsPerInch = UNITS_PER_INCH[unit];+ return {+ min: Math.ceil(MIN_CUSTOM_SIDE_INCHES * unitsPerInch * 100) / 100,+ max: Math.floor(MAX_CUSTOM_SIDE_INCHES * unitsPerInch * 100) / 100,+ };+}++/** Re-expresses a side length in another unit, so switching units keeps the page the+ * same physical size. Clamped to the target unit's limits, because rounding to two+ * decimals can step just outside them; a non-positive length is returned unchanged+ * so it still fails validation. */+export function convertCustomSide(+ value: number,+ from: CustomSizeUnit,+ to: CustomSizeUnit,+): number {+ if (!(value > 0)) return value;+ const { min, max } = customSideLimits(to);+ const converted = roundToHundredths(+ (value * UNITS_PER_INCH[to]) / UNITS_PER_INCH[from],+ );+ return Math.min(Math.max(converted, min), max);+}++function isCustomSideInRange(value: number, unit: CustomSizeUnit): boolean {+ const { min, max } = customSideLimits(unit);+ return value >= min && value <= max;+}+/** Whether these parameters are complete enough to run. Shared by the tool's settings* hook and its operationConfig, so the editor and the pipeline builder agree. */export function validateAdjustPageScaleParameters(params: AdjustPageScaleParameters,): boolean {+ if (params.pageSize === PageSize.CUSTOM) {+ return (+ params.scaleFactor > 0 &&+ isCustomSideInRange(params.customWidth, params.customUnit) &&+ isCustomSideInRange(params.customHeight, params.customUnit)+ );+ }return params.scaleFactor > 0;}diff --git a/frontend/src/editor/core/types/toolApiTypes.ts b/frontend/src/editor/core/types/toolApiTypes.tsindex 02ffb4c51f..8f7c8f1de3 100644--- a/frontend/src/editor/core/types/toolApiTypes.ts+++ b/frontend/src/editor/core/types/toolApiTypes.ts@@ -1326,11 +1326,23 @@ export interface SanitizePdfRequest {}export interface ScalePagesRequest {/**- * Orientation to apply to the target page size. Ignored when pageSize is KEEP.+ * Height of the output pages in customUnit. Required when pageSize is CUSTOM; between 3 points (about 1.06 mm) and 200 inches.+ */+ customHeight?: number;+ /**+ * Unit of customWidth and customHeight.+ */+ customUnit?: "mm" | "cm" | "in";+ /**+ * Width of the output pages in customUnit. Required when pageSize is CUSTOM; between 3 points (about 1.06 mm) and 200 inches.+ */+ customWidth?: number;+ /**+ * Orientation to apply to the target page size. Ignored when pageSize is KEEP or CUSTOM.*/orientation?: "PORTRAIT" | "LANDSCAPE";/**- * The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP. KEEP keeps each page's own size.+ * The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP, CUSTOM. KEEP keeps each page's own size.*/pageSize?:| "A0"@@ -1342,7 +1354,8 @@ export interface ScalePagesRequest {| "A6"| "LETTER"| "LEGAL"- | "KEEP";+ | "KEEP"+ | "CUSTOM";/*** The scale of the content on the pages of the output PDF. Acceptable values are floats.*/