Skip to content

PDF Merge — Kotlin source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

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

// pdf-merge — merge many PDFs into one with Apache PDFBox
// (Loader.loadPDF + PDFMergerUtility, pdfbox.apache.org).
//
// Language: Kotlin (1.9+), Apache PDFBox for the PDF I/O (display-only
// dependency — the pure helpers below compile and run standalone).
// CosmoDev polyglot showcase port of the `pdf-merge` tool.
// Ported from src/lib/pdf-merge.ts — display source, part of CosmoDev's
// polyglot tool pages.
//
// Same contract: empty input rejected, encrypted vs invalid classified from
// the raw load-error message, page count returned for UI display.

import java.io.ByteArrayOutputStream
import org.apache.pdfbox.Loader
import org.apache.pdfbox.multipdf.PDFMergerUtility
import org.apache.pdfbox.pdmodel.PDDocument

/** Load failure kind: ENCRYPTED (password-protected) or INVALID (unparseable). */
enum class ErrorKind { ENCRYPTED, INVALID }

/** The Kotlin twin of the TS PdfToolError class. */
class PdfToolError(val kind: ErrorKind, message: String) : RuntimeException(message)

/** Pure classifier — encrypted vs invalid, from the raw error message.
 *  Same /encrypt|password/i heuristic the TS lib applies. */
fun classifyLoadError(msg: String?): ErrorKind {
    if (msg != null) {
        val lower = msg.lowercase()
        if ("encrypt" in lower || "password" in lower) return ErrorKind.ENCRYPTED
    }
    return ErrorKind.INVALID
}

/** Map a thrown load/parse error to a user-facing PdfToolError. */
fun mapError(e: Exception): PdfToolError = PdfToolError(
    classifyLoadError(e.message),
    if (classifyLoadError(e.message) == ErrorKind.ENCRYPTED)
        "This PDF is password-protected. Unlock it first."
    else
        "Not a readable PDF file.",
)

/** The merge outcome: output bytes plus the page count for UI display. */
data class MergeResult(val bytes: ByteArray, val pageCount: Int)

/** Copy every page of every input, in order, into one fresh PDDocument. */
@Throws(Exception::class)
fun mergePdfs(docs: List<ByteArray>): MergeResult {
    if (docs.isEmpty()) throw PdfToolError(ErrorKind.INVALID, "Nothing to merge.")
    PDDocument().use { out ->
        val merge = PDFMergerUtility()
        try {
            for (bytes in docs) {
                Loader.loadPDF(bytes).use { src ->
                    // the TS ignoreEncryption: false path, explicit in PDFBox
                    if (src.isAllContentEncrypted) {
                        throw PdfToolError(
                            ErrorKind.ENCRYPTED,
                            "This PDF is password-protected. Unlock it first.",
                        )
                    }
                    merge.appendDocument(out, src)
                }
            }
            val baos = ByteArrayOutputStream()
            out.save(baos)
            return MergeResult(baos.toByteArray(), out.numberOfPages)
        } catch (t: PdfToolError) {
            throw t // classification failures surface as themselves
        } catch (e: Exception) {
            // parse failures -> the shared error mapping (PDFBox's
            // InvalidPasswordException carries the keyword in its message)
            throw mapError(e)
        }
    }
}

/** Page count for UI display — the tool's only other PDFBox need. */
@Throws(Exception::class)
fun countPages(bytes: ByteArray): Int {
    try {
        Loader.loadPDF(bytes).use { doc ->
            if (doc.isAllContentEncrypted) {
                throw PdfToolError(
                    ErrorKind.ENCRYPTED,
                    "This PDF is password-protected. Unlock it first.",
                )
            }
            return doc.numberOfPages
        }
    } catch (t: PdfToolError) {
        throw t
    } catch (e: Exception) {
        throw mapError(e)
    }
}

fun main() {
    // classifyLoadError — the src/lib/pdf-merge.test.ts vectors.
    val classifyCases = arrayOf(
        "Input document to PDFDocument.load is encrypted" to "encrypted",
        "wrong password for this document" to "password",
        "Failed to parse PDF" to "parse",
        null to "null",
    )
    for ((msg, label) in classifyCases) {
        println(
            "%s-msg -> %s".format(
                label,
                if (classifyLoadError(msg) == ErrorKind.ENCRYPTED) "encrypted" else "invalid",
            ),
        )
    }

    // empty input throws invalid
    try {
        mergePdfs(emptyList())
    } catch (t: PdfToolError) {
        println(
            "empty-input -> %s: %s".format(
                if (t.kind == ErrorKind.ENCRYPTED) "encrypted" else "invalid",
                t.message,
            ),
        )
    }

    // mapError — encrypted classification propagates, message per kind
    val enc = mapError(Exception("Input document to PDFDocument.load is encrypted"))
    println(
        "map-encrypted -> %s: %s".format(
            if (enc.kind == ErrorKind.ENCRYPTED) "encrypted" else "invalid",
            enc.message,
        ),
    )
    val inv = mapError(Exception("Failed to parse PDF"))
    println(
        "map-invalid -> %s: %s".format(
            if (inv.kind == ErrorKind.ENCRYPTED) "encrypted" else "invalid",
            inv.message,
        ),
    )
}

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 →