Skip to content

PDF Compress — Swift source

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

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

// pdf-compress — two-pass PDF compression with PDFKit (Apple frameworks).
// Swift 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. PDFKit exposes pages but not raw image
// streams, so pass 2 stays a documented extension point behind the verbatim
// chooseImageAction decision.
import Foundation
import PDFKit

/// Load failure kind: "encrypted" (password-protected) or "invalid"
/// (unparseable) — the Swift twin of the TS PdfToolError.code.
enum PdfToolErrorKind: String {
    case encrypted
    case invalid
}

struct PdfToolError: Error {
    let kind: PdfToolErrorKind
    let message: String
}

/// Per-image outcome: before/after stream sizes, or why the original
/// stayed (after == nil, skipped = "grew" | "not-jpeg" | "decode-failed").
struct ImageAccounting {
    let index: Int
    let before: Int
    let after: Int?
    let skipped: String?
}

/// Pure classifier — encrypted vs invalid, from the raw error message.
/// Mirrors classifyLoadError() in src/lib/pdf-errors.ts; nil (the TS
/// undefined) classifies as invalid.
func classifyLoadError(_ msg: String?) -> String {
    guard let msg,
          msg.range(of: "encrypt", options: .caseInsensitive) != nil
              || msg.range(of: "password", options: .caseInsensitive) != nil
    else { return "invalid" }
    return "encrypted"
}

/// Map a thrown load/parse error to a user-facing PdfToolError.
private func mapError(_ msg: String?) -> PdfToolError {
    let kind = classifyLoadError(msg)
    return PdfToolError(
        kind: PdfToolErrorKind(rawValue: kind)!,
        message: kind == "encrypted"
            ? "This PDF is password-protected. Unlock it first."
            : "Not a readable PDF file."
    )
}

/// 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.
func chooseImageAction(_ filter: String) -> String {
    filter == "DCTDecode" ? "recompress" : "skip"
}

/// Pass 1 always runs (the lossless floor). Pass 2, only when quality < 1,
/// would walk doc.pageCount -> doc.page(at:) -> page.pageRef and re-encode
/// every /Image XObject filtered exactly /DCTDecode at `quality` — PDFKit
/// exposes no raw image streams, so this port ships the floor plus the
/// decision helper above. PDFDocument(data:) + isEncrypted refuse encrypted
/// inputs the same way the TS load does (ignoreEncryption: false).
func compressPdf(_ data: Data, quality: Double) throws -> Data {
    guard let doc = PDFDocument(data: data) else {
        throw mapError(nil)
    }
    if doc.isEncrypted {
        throw PdfToolError(kind: .encrypted,
                           message: "This PDF is password-protected. Unlock it first.")
    }
    var attrs = doc.documentAttributes ?? [:]
    attrs[PDFDocumentAttribute.titleAttribute] = ""
    attrs[PDFDocumentAttribute.authorAttribute] = ""
    attrs[PDFDocumentAttribute.subjectAttribute] = ""
    attrs[PDFDocumentAttribute.keywordsAttribute] = []
    attrs[PDFDocumentAttribute.creatorAttribute] = ""
    attrs[PDFDocumentAttribute.producerAttribute] = ""
    doc.documentAttributes = attrs
    let images: [ImageAccounting] = [] // pass 2 not wired
    if quality < 1 && !images.isEmpty {
        fatalError("unreachable: pass 2 display stub")
    }
    return doc.dataRepresentation() ?? data
}

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 →