Skip to content

PDF Compress — Kotlin source

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

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

// pdf-compress — two-pass PDF compression with Apache PDFBox. Kotlin 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.
import java.io.ByteArrayOutputStream
import org.apache.pdfbox.Loader
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDDocumentInformation
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException

/** Load failure kind: "encrypted" (password-protected) or "invalid"
 *  (unparseable) — the Kotlin twin of the TS PdfToolError.code. */
class PdfToolError(val code: String, message: String) : RuntimeException(message)

/** 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. */
fun classifyLoadError(msg: String?): String =
    if (msg != null && Regex("encrypt|password", RegexOption.IGNORE_CASE).containsMatchIn(msg))
        "encrypted"
    else "invalid"

/** Map a thrown load/parse error to a user-facing PdfToolError. */
private fun mapError(e: Exception): PdfToolError {
    val kind = classifyLoadError(e.message)
    return PdfToolError(
        kind,
        if (kind == "encrypted") "This PDF is password-protected. Unlock it first."
        else "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"). */
data class ImageAccounting(
    val index: Int,
    val before: Int,
    val after: Int?,
    val skipped: String?,
)

/** 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. */
fun chooseImageAction(filter: String): String =
    if (filter == "DCTDecode") "recompress" else "skip"

/** Lossless metadata strip — the Info dict entries the TS pass-1 floor
 *  blanks via setTitle('')/setAuthor('')/.... */
private fun stripMetadata(doc: PDDocument) {
    val info: PDDocumentInformation = doc.documentInformation
    info.title = ""
    info.author = ""
    info.subject = ""
    info.keywords = ""
    info.creator = ""
    info.producer = ""
}

/** Pass 1 always runs (the lossless floor). Pass 2, only when quality < 1,
 *  would walk doc.pages -> page.resources -> xObjects and re-encode every
 *  /Image whose filter list is exactly [DCTDecode] at `quality` — 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). */
fun compressPdf(bytes: ByteArray, quality: Double): ByteArray {
    val images = mutableListOf<ImageAccounting>() // pass 2 not wired
    return try {
        Loader.loadPDF(bytes).use { doc ->
            stripMetadata(doc)
            val out = ByteArrayOutputStream()
            doc.save(out)
            check(quality >= 1 || images.isEmpty()) { "unreachable: pass 2 display stub" }
            out.toByteArray()
        }
    } catch (e: InvalidPasswordException) {
        throw PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
    } catch (e: Exception) {
        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 →