Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.7.0+

Optimizing a Signed PDF (PreserveSignatures)

See more PDF Optimization Examples

Demonstrates what happens when a signed PDF is optimized. Optimizing rewrites the document, and a rewrite breaks every existing digital signature, so with PreserveSignatures true (the default) Optimize refuses and LastErrorText says why. Setting PreserveSignatures to false allows it, and the signature that was in the file no longer verifies afterwards. "audit" is always allowed, because it changes nothing.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    //  The PDF used in this example is available at invoice_signed.pdf

    let pdf = CkoPdf()!
    success = pdf.loadFile(filePath: "qa_data/pdf/invoice_signed.pdf")
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    print("signatures: \(pdf.numSignatures.intValue)")

    let json = CkoJsonObject()!
    let jsonOut = CkoJsonObject()!

    //  An audit changes nothing, so it is allowed on a signed PDF.
    success = pdf.optimize(op: "audit", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    print("audit ok, estimated savings: \(jsonOut.int(of: "estimatedSavings.total").intValue)")

    //  Optimizing is refused while PreserveSignatures is true.
    success = pdf.optimize(op: "optimize", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("Refused while PreserveSignatures is true.")
    }

    //  Allow the rewrite.  Do this only when the signatures no longer matter -- an invoice being
    //  archived, say, where the signed original is kept elsewhere.
    pdf.preserveSignatures = false
    success = pdf.optimize(op: "optimize", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    success = pdf.writeFile(path: "qa_output/invoice_optimized.pdf")
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    print("optimized, bytesSaved: \(jsonOut.int(of: "bytesSaved").intValue)")

    //  The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
    let pdf2 = CkoPdf()!
    success = pdf2.loadFile(filePath: "qa_output/invoice_optimized.pdf")
    if success == false {
        print("\(pdf2.lastErrorText!)")
        return
    }

    print("signatures after: \(pdf2.numSignatures.intValue)")

    let sigInfo = CkoJsonObject()!
    var verified: Bool = pdf2.verifySignature(index: 0, sigInfo: sigInfo)
    print("verifies after optimizing: \(verified)")

}