Skip to content

(Feature) Ability to specify target file size for PDF compression #704

@user1823

Description

@user1823

Feature Description

While compressing PDFs, an option to specify the target file size.

Use Case

The Problem
I had a 1.1 MB PDF file. I had to compress it to a size below 200 KB for uploading somewhere. With BentoPDF's aggressive mode, I got a 380 KB file (which was larger than I needed) and with extreme mode, I got an 82 KB file (which had a very low quality and consequently, it was not usable).

The Solution
BentoPDF can expose a target file size option, similar to several other online PDF compression websites.

Examples

An open-source alternative: https://github.com/Stirling-Tools/Stirling-PDF

(Stirling PDF)

You may want to refer to its source code to see how Stirling PDF implements this feature:

CompressController.java#L973-L976:

            if (autoMode) {
                double sizeReductionRatio = expectedOutputSize / (double) inputFileSize;
                optimizeLevel = determineOptimizeLevel(sizeReductionRatio);
            }

CompressController.java#L1064-L1082:

                // Check if target size reached or not in auto mode
                long outputFileSize = Files.size(currentFile);
                if (outputFileSize <= expectedOutputSize || !autoMode) {
                    sizeMet = true;
                } else {
                    int newOptimizeLevel =
                            incrementOptimizeLevel(
                                    optimizeLevel, outputFileSize, expectedOutputSize);


                    // Check if we can't increase the level further
                    if (newOptimizeLevel == optimizeLevel) {
                        log.info("Maximum optimization level reached without meeting target size.");
                        sizeMet = true;
                    } else {
                        // Reset flags for next iteration with higher optimization level
                        imageCompressionApplied = false;
                        optimizeLevel = newOptimizeLevel;
                    }
                }

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions