PDF Merge — Swift source
Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-merge — merge many PDFs into one with PDFKit (PDFDocument).
//
// Language: Swift (5.9+), PDFKit for the PDF I/O (system framework).
// 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. Every
// page of every input is inserted, in order, into one fresh PDFDocument.
import Foundation
import PDFKit
/// Load failure kind: encrypted (password-protected) or invalid (unparseable).
enum ErrorKind {
case encrypted
case invalid
}
/// The Swift twin of the TS PdfToolError class.
struct PdfToolError: Error {
let kind: ErrorKind
let message: String
}
/// Pure classifier — encrypted vs invalid, from the raw error message.
/// Same /encrypt|password/i heuristic the TS lib applies.
func classifyLoadError(_ msg: String?) -> ErrorKind {
guard let msg else { return .invalid }
let lower = msg.lowercased()
return lower.contains("encrypt") || lower.contains("password") ? .encrypted : .invalid
}
/// Map a thrown load/parse error to a user-facing PdfToolError (the Swift
/// twin of the TS `e instanceof Error ? e.message : String(e)` unwrap).
func mapError(_ e: Error) -> PdfToolError {
let raw: String? = (e as? PdfToolError)?.message ?? e.localizedDescription
let kind = classifyLoadError(raw)
return PdfToolError(
kind: kind,
message: kind == .encrypted
? "This PDF is password-protected. Unlock it first."
: "Not a readable PDF file.")
}
/// The merge outcome: output bytes plus the page count for UI display.
struct MergeResult {
let bytes: Data
let pageCount: Int
}
/// Copy every page of every input, in order, into one fresh PDFDocument.
func mergePdfs(_ docs: [Data]) throws -> MergeResult {
if docs.isEmpty {
throw PdfToolError(kind: .invalid, message: "Nothing to merge.")
}
do {
let out = PDFDocument()
for bytes in docs {
guard let src = PDFDocument(data: bytes) else {
throw PdfToolError(kind: .invalid, message: "Not a readable PDF file.")
}
// the TS ignoreEncryption: false path, explicit in PDFKit
if src.isEncrypted {
throw PdfToolError(
kind: .encrypted, message: "This PDF is password-protected. Unlock it first.")
}
for i in 0..<src.pageCount {
out.insert(src.page(at: i)!, at: out.pageCount)
}
}
guard let bytes = out.dataRepresentation() else {
throw PdfToolError(kind: .invalid, message: "Not a readable PDF file.")
}
return MergeResult(bytes: bytes, pageCount: out.pageCount)
} catch let e as PdfToolError {
throw e // classification failures surface as themselves
} catch {
// parse failures -> the shared error mapping (PDFKit's "encrypted"
// errors carry the keyword in their description)
throw mapError(error)
}
}
/// Page count for UI display — the tool's only other PDFKit need.
func countPages(_ bytes: Data) throws -> Int {
guard let doc = PDFDocument(data: bytes) else {
throw PdfToolError(kind: .invalid, message: "Not a readable PDF file.")
}
if doc.isEncrypted {
throw PdfToolError(
kind: .encrypted, message: "This PDF is password-protected. Unlock it first.")
}
return doc.pageCount
}
// ---- driver (exercises the pure helpers only) ----------------------------
// classifyLoadError — the src/lib/pdf-merge.test.ts vectors.
let classifyCases: [(String?, String)] = [
("Input document to PDFDocument.load is encrypted", "encrypted"),
("wrong password for this document", "password"),
("Failed to parse PDF", "parse"),
(nil, "null"),
]
for (msg, label) in classifyCases {
let kind = classifyLoadError(msg) == .encrypted ? "encrypted" : "invalid"
print("\(label)-msg -> \(kind)")
}
// empty input throws invalid
do {
_ = try mergePdfs([])
} catch let e as PdfToolError {
let kind = e.kind == .encrypted ? "encrypted" : "invalid"
print("empty-input -> \(kind): \(e.message)")
} catch {
// unreachable — mergePdfs only ever throws PdfToolError
}
// mapError — encrypted classification propagates, message per kind
let enc = mapError(PdfToolError(kind: .invalid, message: "Input document to PDFDocument.load is encrypted"))
let encKind = enc.kind == .encrypted ? "encrypted" : "invalid"
print("map-encrypted -> \(encKind): \(enc.message)")
let inv = mapError(PdfToolError(kind: .invalid, message: "Failed to parse PDF"))
let invKind = inv.kind == .encrypted ? "encrypted" : "invalid"
print("map-invalid -> \(invKind): \(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 →