PDF Split — Swift source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-split — split one PDF into many by page plan with PDFKit (Apple).
//
// Language: Swift (5.9+), PDFKit for the display-only executor
// 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 Foundation
import PDFKit
/// Load failure kind: "encrypted" (password-protected) or "invalid" (unparseable).
struct PdfToolError: Error, Equatable {
let code: String // "encrypted" | "invalid"
let message: String
}
/// Split output: the planned file name, its bytes, and its page count.
struct SplitOutput {
let name: String
let data: Data
let pageCount: Int
}
/// Pure classifier — encrypted vs invalid, from the raw error message.
func classifyLoadError(_ message: String?) -> String {
guard let message, message.range(of: "encrypt|password", options: [.regularExpression, .caseInsensitive]) != nil
else { return "invalid" }
return "encrypted"
}
/// Map a thrown load failure to a user-facing PdfToolError.
private func mapError(_ error: Error) -> PdfToolError {
classifyLoadError(error.localizedDescription) == "encrypted"
? PdfToolError(code: "encrypted", message: "This PDF is password-protected. Unlock it first.")
: PdfToolError(code: "invalid", message: "Not a readable PDF file.")
}
/// The inclusive 1-based range [a..b] (the TS range() helper).
private func spanRange(_ a: Int, _ b: Int) -> [Int] {
Array(a...b)
}
/// Digit-run test + parse (mirrors the anchored TS regexes `^\d+$`).
private func parseNumber(_ s: String) -> Int? {
guard !s.isEmpty, s.allSatisfy({ $0.isNumber }), let n = Int(s) else { return nil }
return n
}
/// Pure planner — no PDFKit 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.
func parsePageRanges(_ spec: String, pageCount: Int) throws -> [[Int]] {
let trimmed = spec.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
throw PdfToolError(code: "invalid", message: "Enter a page range first.")
}
if trimmed == "all" {
guard pageCount >= 1 else { return [] }
return (1...pageCount).map { [$0] }
}
// 'N/chunk' — fixed-size groups in order (last may be short).
if trimmed.hasSuffix("/chunk") {
let prefix = String(trimmed.dropLast("/chunk".count))
if let size = parseNumber(prefix) {
if size < 1 || size > pageCount {
throw PdfToolError(code: "invalid", message: "Chunk size must be between 1 and \(pageCount).")
}
var groups: [[Int]] = []
var start = 1
while start <= pageCount {
groups.append(spanRange(start, min(start + size - 1, pageCount)))
start += size
}
return groups
}
}
var groups: [[Int]] = []
for token in trimmed.split(separator: ",", omittingEmptySubsequences: false) {
let t = token.trimmingCharacters(in: .whitespacesAndNewlines)
if let page = parseNumber(t) {
if page < 1 || page > pageCount {
throw PdfToolError(code: "invalid", message: "Page \(page) is out of range (1–\(pageCount)).")
}
groups.append([page])
continue
}
// Span form: exactly one '-', digits on both sides.
let parts = t.split(separator: "-", omittingEmptySubsequences: false).map(String.init)
if parts.count == 2, let a = parseNumber(parts[0]), let b = parseNumber(parts[1]) {
if b < a {
throw PdfToolError(code: "invalid", message: "Range \(a)-\(b) descends — use a-b with a ≤ b.")
}
if a < 1 || b > pageCount {
throw PdfToolError(code: "invalid", message: "Range \(a)-\(b) is out of range (1–\(pageCount)).")
}
groups.append(spanRange(a, b))
continue
}
throw PdfToolError(code: "invalid", message: "\"\(t)\" is not a page, a-b range, \"all\", or \"N/chunk\".")
}
return groups
}
/// 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 func chunkShaped(_ groups: [[Int]]) -> Bool {
guard groups.count >= 2 else { return false }
let size = groups[0].count
guard size >= 2 else { return false }
var next = 1
for (i, g) in groups.enumerated() {
if g.first != next { return false }
next = g.last! + 1
if i < groups.count - 1 && g.count != size { return false }
if i == groups.count - 1 && g.count > 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'.
func planNames(_ groups: [[Int]]) -> [String] {
let chunk = chunkShaped(groups)
return groups.enumerated().map { i, g in
if chunk {
return "chunk-\(i + 1).pdf"
}
if g.count == 1 {
return "page-\(g[0]).pdf"
}
if g.last! - g[0] + 1 == g.count {
return "pages-\(g[0])-\(g.last!).pdf"
}
return "pages-" + g.map(String.init).joined(separator: ",") + ".pdf"
}
}
/// One output PDF per group: the source is loaded once with PDFKit, then each
/// planned page is inserted into a fresh PDFDocument and serialized (the
/// PDFKit analogue of pdf-lib's copyPages). Mirrors splitPdf() in
/// src/lib/pdf-split.ts.
func splitPdf(_ data: Data, groups: [[Int]]) throws -> [SplitOutput] {
if groups.isEmpty {
throw PdfToolError(code: "invalid", message: "Nothing to split — plan at least one page.")
}
guard let src = PDFDocument(data: data) else {
throw PdfToolError(code: "invalid", message: "Not a readable PDF file.")
}
if src.isEncrypted {
throw PdfToolError(code: "encrypted", message: "This PDF is password-protected. Unlock it first.")
}
let total = src.pageCount
let names = planNames(groups)
return try groups.enumerated().map { i, group in
for page in group where page < 1 || page > total {
throw PdfToolError(code: "invalid", message: "Page \(page) is out of range (1–\(total)).")
}
let out = PDFDocument()
for (index, page) in group.enumerated() {
guard let srcPage = src.page(at: page - 1) else {
throw PdfToolError(code: "invalid", message: "Page \(page) is out of range (1–\(total)).")
}
out.insert(srcPage, at: index)
}
guard let outData = out.dataRepresentation() else {
throw mapError(PdfToolError(code: "invalid", message: "Could not serialize the split output."))
}
return SplitOutput(name: names[i], data: outData, pageCount: out.pageCount)
}
}
/// Page count for UI display — the Swift twin of the TS countPages() helper.
func countPages(_ data: Data) throws -> Int {
guard let doc = PDFDocument(data: data) else {
throw PdfToolError(code: "invalid", message: "Not a readable PDF file.")
}
if doc.isEncrypted {
throw PdfToolError(code: "encrypted", message: "This PDF is password-protected. Unlock it first.")
}
return doc.pageCount
}
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 →