Skip to content

PDF Compress — Java source

Shrink PDF file sizes in your browser — lossless optimization plus a JPEG quality slider for embedded images. Nothing uploads.

This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// pdf-compress — two-pass PDF compression with Apache PDFBox. Java port
// (canonical TS: src/lib/pdf-compress.ts; Go twin: cli/pdf-compress):
// pass 1 strips document metadata and re-saves (the lossless floor); pass 2
// would walk every page's image XObjects and re-encode baseline JPEGs
// (/Filter /DCTDecode) at a lower quality at identical pixel dimensions.
// Package-private: display snippets keep the repo filename (pdf-compress
// .java), which need not match the class name.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;

final class PdfCompress {

    /** Load failure kind: "encrypted" (password-protected) or "invalid"
     *  (unparseable) — the Java twin of the TS PdfToolError.code. */
    static final class PdfToolError extends RuntimeException {
        final String code;
        PdfToolError(String code, String message) {
            super(message);
            this.code = code;
        }
    }

    private static final Pattern ENCRYPT_OR_PASSWORD = Pattern.compile("encrypt|password",
            Pattern.CASE_INSENSITIVE);

    /** Pure classifier — encrypted vs invalid, from the raw error message.
     *  Mirrors classifyLoadError() in src/lib/pdf-errors.ts; null (the TS
     *  undefined) classifies as invalid. */
    static String classifyLoadError(String msg) {
        return msg != null && ENCRYPT_OR_PASSWORD.matcher(msg).find() ? "encrypted" : "invalid";
    }

    /** Map a thrown load/parse error to a user-facing PdfToolError. */
    private static PdfToolError mapError(Exception e) {
        String kind = classifyLoadError(e.getMessage());
        return new PdfToolError(kind, kind.equals("encrypted")
                ? "This PDF is password-protected. Unlock it first."
                : "Not a readable PDF file.");
    }

    /** Per-image outcome: before/after stream sizes, or why the original
     *  stayed (after == null, skipped = "grew" | "not-jpeg" |
     *  "decode-failed"). */
    record ImageAccounting(int index, int before, Integer after, String skipped) {}

    /** Pure decision: only baseline single-stream JPEGs (/Filter
     *  /DCTDecode) are recompressible — anything else (Flate, multi-filter
     *  chains, no filter) stays byte-for-byte intact. Ported verbatim from
     *  chooseImageAction() in src/lib/pdf-compress.ts. */
    static String chooseImageAction(String filter) {
        return "DCTDecode".equals(filter) ? "recompress" : "skip";
    }

    /** Lossless metadata strip — the Info dict entries the TS pass-1 floor
     *  blanks via setTitle('')/setAuthor('')/.... */
    private static void stripMetadata(PDDocument doc) {
        PDDocumentInformation info = doc.getDocumentInformation();
        info.setTitle("");
        info.setAuthor("");
        info.setSubject("");
        info.setKeywords("");
        info.setCreator("");
        info.setProducer("");
    }

    /** Pass 1 always runs (the lossless floor). Pass 2, only when
     *  quality < 1, would walk doc.getPages() -> page.getResources()
     *  -> getXObjects() and re-encode every /Image whose filter list is
     *  exactly [DCTDecode] at `quality`, pushing the replacement back via
     *  PDImageXObject — the decode/re-encode half needs a rasterizer
     *  binding, so this port ships the floor plus the decision helper
     *  above. Loader.loadPDF refuses encrypted inputs the same way the TS
     *  load does (ignoreEncryption: false). */
    static byte[] compressPdf(byte[] bytes, double quality) throws IOException {
        try (PDDocument doc = Loader.loadPDF(bytes)) {
            stripMetadata(doc);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            doc.save(out);
            List<ImageAccounting> images = new ArrayList<>(); // pass 2 not wired
            if (quality < 1 && !images.isEmpty()) {
                throw new IllegalStateException("unreachable: pass 2 display stub");
            }
            return out.toByteArray();
        } catch (InvalidPasswordException e) {
            throw new PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.");
        } catch (IOException e) {
            throw mapError(e);
        }
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →