Skip to content

PDF Split — Kotlin source

Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.

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

// pdf-split — split one PDF into many by page plan with Apache PDFBox.
//
// Language: Kotlin (1.9+), Apache PDFBox (display-only — the PDFBox API is
// called the way a real build would link it; this snippet is never compiled
// against the jar here)
// CosmoDev polyglot showcase port of the `pdf-split` tool.
// Ported from src/lib/pdf-split.ts — display source, part of CosmoDev's
// polyglot tool pages.

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

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

/** Split output: the planned file name, its bytes, and its page count. */
data class SplitOutput(val name: String, val bytes: ByteArray, val pageCount: Int)

private val chunkRe = Regex("^(\\d+)/chunk$")
private val singleRe = Regex("^\\d+$")
private val spanRe = Regex("^(\\d+)-(\\d+)$")

/** Pure classifier — encrypted vs invalid, from the raw error message. */
fun classifyLoadError(message: String?): String =
    if (message != null && message.lowercase().contains(Regex("encrypt|password"))) "encrypted"
    else "invalid"

/** Map a thrown load failure to a user-facing PdfToolError. */
private fun mapError(e: Exception): PdfToolError =
    if (classifyLoadError(e.message) == "encrypted") {
        PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
    } else {
        PdfToolError("invalid", "Not a readable PDF file.")
    }

/** The inclusive 1-based range [a..b] (the TS range() helper). */
private fun spanRange(a: Int, b: Int): List<Int> = (a..b).toList()

/**
 * Pure planner — no PDFBox on this path. Grammar (mirrors parsePageRanges in
 * src/lib/pdf-split.ts):
 *   'all'       -> [[1], [2], .., [pageCount]]
 *   'N/chunk'   -> groups of N pages in order (last group may be short)
 *   'a-b,c-d,e' -> [[a..b], [c..d], [e]] (1-based, inclusive)
 *
 * @throws PdfToolError code "invalid" on empty specs, unparseable tokens,
 *   descending ranges, and any page outside 1..pageCount.
 */
fun parsePageRanges(spec: String, pageCount: Int): List<List<Int>> {
    val trimmed = spec.trim()
    if (trimmed.isEmpty()) throw PdfToolError("invalid", "Enter a page range first.")

    if (trimmed == "all") return (1..pageCount).map { listOf(it) }

    chunkRe.matchEntire(trimmed)?.let { chunk ->
        val size = chunk.groupValues[1].toInt()
        if (size < 1 || size > pageCount) {
            throw PdfToolError("invalid", "Chunk size must be between 1 and $pageCount.")
        }
        return (1..pageCount step size).map { start ->
            spanRange(start, minOf(start + size - 1, pageCount))
        }
    }

    return trimmed.split(",").map { token ->
        val t = token.trim()
        if (singleRe.matches(t)) {
            val page = t.toInt()
            if (page < 1 || page > pageCount) {
                throw PdfToolError("invalid", "Page $page is out of range (1–$pageCount).")
            }
            listOf(page)
        } else spanRe.matchEntire(t)?.destructured?.let { (a, b) ->
            val lo = a.toInt()
            val hi = b.toInt()
            if (hi < lo) {
                throw PdfToolError("invalid", "Range $lo-$hi descends — use a-b with a ≤ b.")
            }
            if (lo < 1 || hi > pageCount) {
                throw PdfToolError("invalid", "Range $lo-$hi is out of range (1–$pageCount).")
            }
            spanRange(lo, hi)
        } ?: throw PdfToolError("invalid", "\"$t\" is not a page, a-b range, \"all\", or \"N/chunk\".")
    }
}

/**
 * Chunk-shaped = partition of 1..n into equal runs of >=2 pages (last may be
 * short). Size-1 "chunks" are indistinguishable from 'all' — those stay
 * page-N.
 */
private fun chunkShaped(groups: List<List<Int>>): Boolean {
    if (groups.size < 2) return false
    val size = groups[0].size
    if (size < 2) return false
    var next = 1
    groups.forEachIndexed { i, g ->
        if (g.first() != next) return false
        next = g.last() + 1
        if (i < groups.size - 1 && g.size != size) return false
        if (i == groups.size - 1 && g.size > size) return false
    }
    return true
}

/**
 * Pure naming pass: single page -> 'page-N.pdf'; chunk-shaped plan ->
 * 'chunk-K.pdf'; contiguous group -> 'pages-A-B.pdf'; else 'pages-A,B.pdf'.
 */
fun planNames(groups: List<List<Int>>): List<String> {
    val chunk = chunkShaped(groups)
    return groups.mapIndexed { i, g ->
        when {
            chunk -> "chunk-${i + 1}.pdf"
            g.size == 1 -> "page-${g[0]}.pdf"
            g.last() - g.first() + 1 == g.size -> "pages-${g.first()}-${g.last()}.pdf"
            else -> "pages-" + g.joinToString(",") + ".pdf"
        }
    }
}

/**
 * One output PDF per group: the source is loaded once with PDFBox's Loader,
 * then each planned page is imported into a fresh PDDocument and saved (the
 * PDFBox analogue of pdf-lib's copyPages). Mirrors splitPdf() in
 * src/lib/pdf-split.ts.
 */
fun splitPdf(pdf: ByteArray, groups: List<List<Int>>): List<SplitOutput> {
    if (groups.isEmpty()) {
        throw PdfToolError("invalid", "Nothing to split — plan at least one page.")
    }
    return Loader.loadPDF(pdf).use { src ->
        if (src.isEncrypted) {
            throw PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
        }
        val total = src.numberOfPages
        val names = planNames(groups)
        groups.mapIndexed { i, group ->
            group.forEach { page ->
                if (page < 1 || page > total) {
                    throw PdfToolError("invalid", "Page $page is out of range (1–$total).")
                }
            }
            val out = PDDocument()
            group.forEach { page ->
                // importPage deep-copies the page and appends it to out.
                out.importPage(src.getPage(page - 1))
            }
            val outPages = out.numberOfPages
            val buffer = ByteArrayOutputStream()
            out.save(buffer)
            out.close()
            SplitOutput(names[i], buffer.toByteArray(), outPages)
        }
    }
}

/** Page count for UI display — the Kotlin twin of the TS countPages() helper. */
fun countPages(pdf: ByteArray): Int =
    try {
        Loader.loadPDF(pdf).use { doc ->
            if (doc.isEncrypted) {
                throw PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
            }
            doc.numberOfPages
        }
    } catch (e: PdfToolError) {
        throw e
    } 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 →