#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
Tell the user when compression could not shrink a file (#8482)
EthanHealy013c8f50647e57
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.javaindex 3f194f32f0..907f993237 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java@@ -1088,23 +1088,23 @@ public class CompressController {}}- // Use original if optimized file is somehow larger or currentFile is invalidif (!Files.exists(currentFile)) {log.warn("Optimized file missing or invalid. Using the original file instead.");currentFile = originalFile;}- long finalFileSize = Files.size(currentFile);- if (finalFileSize >= inputFileSize) {- log.warn(- "Optimized file is larger than the original. Using the original file"- + " instead.");- currentFile = originalFile;- }String outputFilename =GeneralUtils.generateFilename(inputFile.getOriginalFilename(), "_Optimized.pdf");+ // Return the upload byte for byte: re-saving it through PDFBox can grow it, and the+ // frontend reports "could not be compressed further" by the size being unchanged.+ if (Files.size(currentFile) >= inputFileSize) {+ log.info("Compression did not reduce the file size. Returning the original file.");+ tempFiles.remove(originalTempFile);+ return WebResponseUtils.pdfFileToWebResponse(originalTempFile, outputFilename);+ }+try {try (PDDocument document = pdfDocumentFactory.load(currentFile.toFile())) {return WebResponseUtils.pdfDocToWebResponse(diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/CompressControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/CompressControllerTest.javaindex d5a5c6a30c..ba5b81d347 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/CompressControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/CompressControllerTest.java@@ -258,6 +258,20 @@ class CompressControllerTest {assertThat(drain(response)).isNotEmpty();}+ @Test+ @DisplayName("no size reduction returns the uploaded bytes unchanged")+ void noReduction_returnsOriginalBytes() throws Exception {+ byte[] pdf = textOnlyPdfBytes();+ OptimizePdfRequest request = new OptimizePdfRequest();+ request.setFileInput(multipart(pdf));+ request.setOptimizeLevel(1);++ ResponseEntity<Resource> response = controller.optimizePdf(request);++ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);+ assertThat(drain(response)).isEqualTo(pdf);+ }+@Test@DisplayName("level 4 with a sub-threshold image still returns OK (image skipped)")void level4_smallImage_skipped_returnsOk() throws Exception {diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 1b2b94c5cd..02b941e659 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -3838,6 +3838,12 @@ filesize = "File Size"quality = "Quality"title = "Compression Method"+[compress.noReduction]+multiple = "Compression ran successfully, but {{count}} of {{total}} files can't be compressed any further."+multipleAtLevel = "Compression at this level made no improvement to {{count}} of {{total}} files. Try a higher compression level."+single = "Compression ran successfully, but this file can't be compressed any further."+singleAtLevel = "Compression at this level made no improvement to this file. Try a higher compression level."+[compress.settings]desiredSize = "Desired File Size"desiredSizePlaceholder = "Enter size"diff --git a/frontend/editor/src/core/components/tools/compress/CompressSettings.tsx b/frontend/editor/src/core/components/tools/compress/CompressSettings.tsxindex e083da5ca2..b736320378 100644--- a/frontend/editor/src/core/components/tools/compress/CompressSettings.tsx+++ b/frontend/editor/src/core/components/tools/compress/CompressSettings.tsx@@ -12,7 +12,11 @@ import {import { SegmentedControl } from "@app/ui/SegmentedControl";import SliderWithInput from "@app/components/shared/sliderWithInput/SliderWithInput";import { useTranslation } from "react-i18next";-import { CompressParameters } from "@app/hooks/tools/compress/useCompressParameters";+import {+ CompressParameters,+ MAX_COMPRESSION_LEVEL,+ MIN_COMPRESSION_LEVEL,+} from "@app/hooks/tools/compress/useCompressParameters";import ButtonSelector from "@app/components/shared/ButtonSelector";import { useGroupEnabled } from "@app/hooks/useGroupEnabled";import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";@@ -67,8 +71,8 @@ const CompressSettings = ({value={parameters.compressionLevel}onChange={(value) => onParameterChange("compressionLevel", value)}disabled={disabled}- min={1}- max={9}+ min={MIN_COMPRESSION_LEVEL}+ max={MAX_COMPRESSION_LEVEL}step={1}suffix=""/>diff --git a/frontend/editor/src/core/components/tools/compress/NoReductionNotice.tsx b/frontend/editor/src/core/components/tools/compress/NoReductionNotice.tsxnew file mode 100644index 0000000000..2f8c824ebc--- /dev/null+++ b/frontend/editor/src/core/components/tools/compress/NoReductionNotice.tsx@@ -0,0 +1,53 @@+import { useTranslation } from "react-i18next";+import { Banner } from "@app/ui/Banner";+import { Icon } from "@app/ui/Icon";++interface NoReductionNoticeProps {+ unreduced: number;+ total: number;+ /** Whether the run already used the strongest compression, so a retry cannot help. */+ atStrongest: boolean;+}++export function NoReductionNotice({+ unreduced,+ total,+ atStrongest,+}: NoReductionNoticeProps) {+ const { t } = useTranslation();++ let message: string;+ if (total === 1) {+ message = atStrongest+ ? t(+ "compress.noReduction.single",+ "Compression ran successfully, but this file can't be compressed any further.",+ )+ : t(+ "compress.noReduction.singleAtLevel",+ "Compression at this level made no improvement to this file. Try a higher compression level.",+ );+ } else {+ message = atStrongest+ ? t("compress.noReduction.multiple", {+ count: unreduced,+ total,+ defaultValue:+ "Compression ran successfully, but {{count}} of {{total}} files can't be compressed any further.",+ })+ : t("compress.noReduction.multipleAtLevel", {+ count: unreduced,+ total,+ defaultValue:+ "Compression at this level made no improvement to {{count}} of {{total}} files. Try a higher compression level.",+ });+ }++ return (+ <Banner+ tone="warning"+ icon={<Icon name="triangle-alert" />}+ description={message}+ />+ );+}diff --git a/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx b/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsxindex 19dd6a1a52..472346b50e 100644--- a/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx+++ b/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx@@ -39,6 +39,7 @@ export interface ReviewToolStepProps<TParams = unknown> {title?: string;onFileClick?: (file: File) => void;onUndo?: () => void;+ notice?: React.ReactNode;isCollapsed?: boolean;onCollapsedClick?: () => void;}@@ -47,10 +48,12 @@ function ReviewStepContent<TParams = unknown>({operation,onFileClick,onUndo,+ notice,}: {operation: ToolOperationHook<TParams>;onFileClick?: (file: File) => void;onUndo?: () => void;+ notice?: React.ReactNode;}) {const { t } = useTranslation();const terminology = useFileActionTerminology();@@ -139,6 +142,8 @@ function ReviewStepContent<TParams = unknown>({onClose={operation.clearError}/>+ {notice}+{previewFiles.length > 0 && (<ResultsPreviewfiles={previewFiles}@@ -210,6 +215,7 @@ export function createReviewToolStep<TParams = unknown>(operation={props.operation}onFileClick={props.onFileClick}onUndo={props.onUndo}+ notice={props.notice}/>,);}diff --git a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsxindex fd025cf503..2437673dfd 100644--- a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx+++ b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx@@ -75,6 +75,8 @@ export interface ReviewStepConfig<TParams = unknown> {title: string;onFileClick?: (file: File) => void;onUndo?: () => void;+ /** Rendered above the results, for an outcome the files alone do not explain. */+ notice?: React.ReactNode;testId?: string;}@@ -200,6 +202,7 @@ export function createToolFlow<TParams = unknown>(title: config.review.title,onFileClick: config.review.onFileClick,onUndo: config.review.onUndo,+ notice: config.review.notice,})}</ToolStepProvider></Stack>diff --git a/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.test.ts b/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.test.tsindex eb03607d54..640ee2f0aa 100644--- a/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.test.ts+++ b/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.test.ts@@ -1,6 +1,11 @@import { describe, expect, test } from "vitest";import { renderHook, act } from "@testing-library/react";-import { useCompressParameters } from "@app/hooks/tools/compress/useCompressParameters";+import {+ defaultParameters,+ MAX_COMPRESSION_LEVEL,+ useCompressParameters,+ usedStrongestCompression,+} from "@app/hooks/tools/compress/useCompressParameters";describe("useCompressParameters", () => {test("defaults (quality mode) validate", () => {@@ -40,3 +45,30 @@ describe("useCompressParameters", () => {expect(result.current.validateParameters()).toBe(true);});});++describe("usedStrongestCompression", () => {+ test("is false below the top quality level", () => {+ expect(+ usedStrongestCompression({ ...defaultParameters, compressionLevel: 8 }),+ ).toBe(false);+ });++ test("is true at the top quality level", () => {+ expect(+ usedStrongestCompression({+ ...defaultParameters,+ compressionLevel: MAX_COMPRESSION_LEVEL,+ }),+ ).toBe(true);+ });++ test("is true in file-size mode, which escalates the level itself", () => {+ expect(+ usedStrongestCompression({+ ...defaultParameters,+ compressionMethod: "filesize",+ compressionLevel: 1,+ }),+ ).toBe(true);+ });+});diff --git a/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.ts b/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.tsindex b27a9e97cc..4c4ce66d23 100644--- a/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.ts+++ b/frontend/editor/src/core/hooks/tools/compress/useCompressParameters.ts@@ -17,6 +17,9 @@ export interface CompressParameters extends BaseParameters {linearize: boolean;}+export const MIN_COMPRESSION_LEVEL = 1;+export const MAX_COMPRESSION_LEVEL = 9;+export const defaultParameters: CompressParameters = {compressionLevel: 5,grayscale: false,@@ -30,6 +33,18 @@ export const defaultParameters: CompressParameters = {linearize: false,};+/**+ * Whether a run with these parameters already used the strongest compression. File-size+ * mode counts: the backend raises the level itself until it meets the target or hits the+ * maximum, so a run that missed has already been through every level.+ */+export function usedStrongestCompression(params: CompressParameters): boolean {+ return (+ params.compressionMethod === "filesize" ||+ params.compressionLevel >= MAX_COMPRESSION_LEVEL+ );+}+export type CompressParametersHook = BaseParametersHook<CompressParameters>;/** Whether these parameters are complete enough to run. Shared by the tool's settings@@ -37,7 +52,10 @@ export type CompressParametersHook = BaseParametersHook<CompressParameters>;export function validateCompressParameters(params: CompressParameters,): boolean {- if (params.compressionLevel < 1 || params.compressionLevel > 9) {+ if (+ params.compressionLevel < MIN_COMPRESSION_LEVEL ||+ params.compressionLevel > MAX_COMPRESSION_LEVEL+ ) {return false;}// Filesize mode needs a target size; without one the request omitsdiff --git a/frontend/editor/src/core/hooks/tools/compress/useUnreducedOutputs.test.ts b/frontend/editor/src/core/hooks/tools/compress/useUnreducedOutputs.test.tsnew file mode 100644index 0000000000..3adb6bb55d--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/compress/useUnreducedOutputs.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from "vitest";+import { countUnreducedOutputs } from "@app/hooks/tools/compress/useUnreducedOutputs";+import type { FileId, StirlingFileStub } from "@app/types/fileContext";++const id = (value: string) => value as FileId;++const output = (parentFileId: string, size: number): StirlingFileStub =>+ ({+ id: id(`out-${parentFileId}`),+ parentFileId: id(parentFileId),+ size,+ }) as StirlingFileStub;++describe("countUnreducedOutputs", () => {+ const inputSizes = new Map([+ [id("a"), 1000],+ [id("b"), 2000],+ ]);++ test("an output smaller than its input is reduced", () => {+ expect(countUnreducedOutputs(inputSizes, [output("a", 600)])).toEqual({+ unreduced: 0,+ total: 1,+ });+ });++ test("an output the same size or larger than its input is unreduced", () => {+ expect(+ countUnreducedOutputs(inputSizes, [output("a", 1000), output("b", 2500)]),+ ).toEqual({ unreduced: 2, total: 2 });+ });++ test("pairs each output with its own input, not the others", () => {+ expect(+ countUnreducedOutputs(inputSizes, [output("a", 1500), output("b", 1500)]),+ ).toEqual({ unreduced: 1, total: 2 });+ });++ test("outputs with no recorded input are not counted", () => {+ expect(+ countUnreducedOutputs(inputSizes, [output("c", 5000), undefined]),+ ).toEqual({ unreduced: 0, total: 0 });+ });+});diff --git a/frontend/editor/src/core/hooks/tools/compress/useUnreducedOutputs.ts b/frontend/editor/src/core/hooks/tools/compress/useUnreducedOutputs.tsnew file mode 100644index 0000000000..e4dc953246--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/compress/useUnreducedOutputs.ts@@ -0,0 +1,59 @@+import { useCallback, useRef } from "react";+import { useFileSelector } from "@app/contexts/FileContext";+import type {+ FileId,+ StirlingFile,+ StirlingFileStub,+} from "@app/types/fileContext";++export interface UnreducedOutputs {+ unreduced: number;+ total: number;+}++/**+ * Counts outputs that are no smaller than the input they replaced, matching each+ * output to its input through the version chain's parentFileId.+ */+export function countUnreducedOutputs(+ inputSizes: ReadonlyMap<FileId, number>,+ outputs: ReadonlyArray<StirlingFileStub | undefined>,+): UnreducedOutputs {+ let unreduced = 0;+ let total = 0;+ for (const output of outputs) {+ const inputSize = output?.parentFileId+ ? inputSizes.get(output.parentFileId)+ : undefined;+ if (output === undefined || inputSize === undefined) continue;+ total++;+ if (output.size >= inputSize) unreduced++;+ }+ return { unreduced, total };+}++/**+ * Tracks which compress results did not shrink. Call recordInputs with the files+ * about to be compressed: the inputs leave FileContext once their outputs replace+ * them, so their sizes are not recoverable afterwards.+ */+export function useUnreducedOutputs(+ outputFileIds: readonly string[] | null | undefined,+) {+ const inputSizesRef = useRef<ReadonlyMap<FileId, number>>(new Map());++ const recordInputs = useCallback((files: readonly StirlingFile[]) => {+ inputSizesRef.current = new Map(files.map((f) => [f.fileId, f.size]));+ }, []);++ const result = useFileSelector(+ (state) =>+ countUnreducedOutputs(+ inputSizesRef.current,+ (outputFileIds ?? []).map((id) => state.files.byId[id as FileId]),+ ),+ (a, b) => a.unreduced === b.unreduced && a.total === b.total,+ );++ return { ...result, recordInputs };+}diff --git a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx b/frontend/editor/src/core/tests/ToolFileSelection.test.tsxindex 261a1babfe..242b6910fc 100644--- a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx+++ b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx@@ -13,6 +13,7 @@ import type { ToolAutomationSettingsProps } from "@app/hooks/tools/shared/toolOpimport {createNewStirlingFileStub,createStirlingFile,+ type FileContextState,type StirlingFile,type StirlingFileStub,} from "@app/types/fileContext";@@ -85,6 +86,8 @@ vi.mock("@app/contexts/FileContext", () => ({}),useFileContext: () => ({ selectors, actions: {} }),useFileSelectors: () => selectors,+ useFileSelector: <T,>(select: (state: FileContextState) => T) =>+ select({ files: { ids: [], byId: {} } } as unknown as FileContextState),useFileActions: () => ({ actions: {} }),useFileSelection: () => ({ setSelectedFiles: vi.fn() }),useFileManagement: () => ({ reorderFiles: vi.fn() }),diff --git a/frontend/editor/src/core/tests/stubbed/compress-tool.spec.ts b/frontend/editor/src/core/tests/stubbed/compress-tool.spec.tsindex 9b12d5346a..1d29791278 100644--- a/frontend/editor/src/core/tests/stubbed/compress-tool.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/compress-tool.spec.ts@@ -1,4 +1,47 @@+import type { Page } from "@playwright/test";+import path from "path";+import fs from "fs";import { test, expect } from "@app/tests/helpers/stub-test-base";+import {+ uploadFiles,+ switchToEditorIfViewerMode,+ runToolAndWaitForReview,+} from "@app/tests/helpers/ui-helpers";++const FIXTURES_DIR = path.join(import.meta.dirname, "../test-fixtures");+const SAMPLE_PDF = path.join(FIXTURES_DIR, "sample.pdf");+const SAMPLE_PDF_BYTES = fs.readFileSync(SAMPLE_PDF);+const SMALLER_PDF_BYTES = fs.readFileSync(+ path.join(FIXTURES_DIR, "cropbox-control.pdf"),+);+const NO_REDUCTION_NOTICE =+ /can't be compressed any further|made no improvement/i;++async function stubCompressResponse(page: Page, body: Buffer) {+ await page.route("**/api/v1/misc/compress-pdf", (route) =>+ route.fulfill({+ status: 200,+ contentType: "application/pdf",+ headers: {+ "Content-Disposition": 'attachment; filename="sample_Optimized.pdf"',+ },+ body,+ }),+ );+}++async function compressSample(page: Page, level?: number) {+ await uploadFiles(page, SAMPLE_PDF);+ await switchToEditorIfViewerMode(page);+ if (level !== undefined) {+ const levelInput = page.getByRole("textbox", {+ name: "Quality Adjustment",+ });+ await levelInput.fill(String(level));+ await levelInput.blur();+ }+ await runToolAndWaitForReview(page);+}test.describe("8. Compress Tool", () => {test.beforeEach(async ({ page }) => {@@ -25,4 +68,36 @@ test.describe("8. Compress Tool", () => {await expect(page.getByText(/upload/i).first()).toBeVisible();});});++ test.describe("8.2 Compress - No size reduction", () => {+ test("below the top level, suggests a higher level", async ({ page }) => {+ await stubCompressResponse(page, SAMPLE_PDF_BYTES);+ await compressSample(page);++ await expect(+ page.getByText(/at this level made no improvement/i),+ ).toBeVisible();+ });++ test("at the top level, says the file can't go any smaller", async ({+ page,+ }) => {+ await stubCompressResponse(page, SAMPLE_PDF_BYTES);+ await compressSample(page, 9);++ await expect(+ page.getByText(/can't be compressed any further/i),+ ).toBeVisible();+ });++ test("stays quiet when the result is smaller", async ({ page }) => {+ await stubCompressResponse(page, SMALLER_PDF_BYTES);+ await compressSample(page);++ await expect(+ page.locator('[data-testid="review-panel-container"]'),+ ).toBeVisible();+ await expect(page.getByText(NO_REDUCTION_NOTICE)).toHaveCount(0);+ });+ });});diff --git a/frontend/editor/src/core/tools/Compress.tsx b/frontend/editor/src/core/tools/Compress.tsxindex 7befcb8b6c..7ef2316152 100644--- a/frontend/editor/src/core/tools/Compress.tsx+++ b/frontend/editor/src/core/tools/Compress.tsx@@ -1,11 +1,16 @@import { useTranslation } from "react-i18next";import { createToolFlow } from "@app/components/tools/shared/createToolFlow";import CompressSettings from "@app/components/tools/compress/CompressSettings";-import { useCompressParameters } from "@app/hooks/tools/compress/useCompressParameters";+import {+ useCompressParameters,+ usedStrongestCompression,+} from "@app/hooks/tools/compress/useCompressParameters";import { useCompressOperation } from "@app/hooks/tools/compress/useCompressOperation";import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";import { BaseToolProps, ToolComponent } from "@app/types/tool";import { useCompressTips } from "@app/components/tooltips/useCompressTips";+import { useUnreducedOutputs } from "@app/hooks/tools/compress/useUnreducedOutputs";+import { NoReductionNotice } from "@app/components/tools/compress/NoReductionNotice";const Compress = (props: BaseToolProps) => {const { t } = useTranslation();@@ -18,6 +23,24 @@ const Compress = (props: BaseToolProps) => {props,);+ const { unreduced, total, recordInputs } = useUnreducedOutputs(+ base.operation.outputFileIds,+ );++ const handleExecute = () => {+ recordInputs(base.selectedFiles);+ return base.handleExecute();+ };++ // Changing a parameter clears the results, so these are the parameters the run used.+ const noReductionNotice = unreduced > 0 && (+ <NoReductionNotice+ unreduced={unreduced}+ total={total}+ atStrongest={usedStrongestCompression(base.params.parameters)}+ />+ );+return createToolFlow({files: {selectedFiles: base.selectedFiles,@@ -44,7 +67,7 @@ const Compress = (props: BaseToolProps) => {text: t("compress.submit", "Compress"),isVisible: !base.hasResults,loadingText: t("loading"),- onClick: base.handleExecute,+ onClick: handleExecute,endpointEnabled: base.endpointEnabled,paramsValid: base.params.validateParameters(),},@@ -54,6 +77,7 @@ const Compress = (props: BaseToolProps) => {title: t("compress.title", "Compression Results"),onFileClick: base.handleThumbnailClick,onUndo: base.handleUndo,+ notice: noReductionNotice,},});};