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

Optimizing an Encrypted PDF

See more PDF Optimization Examples

Demonstrates optimizing a PDF that is encrypted. Set the password before loading, exactly as for any other operation; the optimized PDF keeps the security it had, so the output still needs the same password. Because Chilkat honours the permissions recorded in the document, optimizing requires owner rights or the "modify" permission: a PDF opened with a user password that forbids modification can be audited but not optimized.

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 encrypted_user_password.pdf

    let pdf = CkoPdf()!

    //  The password must be set before loading.
    pdf.userPassword = "secret"
    success = pdf.loadFile(filePath: "qa_data/pdf/encrypted_user_password.pdf")
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    //  What security does the file have, and may it be modified?
    let json = CkoJsonObject()!
    let jsonOut = CkoJsonObject()!
    success = pdf.protection(op: "getInfo", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    print("encrypted: \(jsonOut.bool(of: "loaded.encrypted"))")
    print("method:    \(jsonOut.string(of: "loaded.method")!)")
    print("openedWith: \(jsonOut.string(of: "loaded.openedWith")!)")
    print("may modify: \(jsonOut.bool(of: "loaded.permissions.modify"))")

    success = pdf.optimize(op: "optimize", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

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

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

    //  The output is still encrypted with the same security: loading it without the password fails.
    let noPassword = CkoPdf()!
    success = noPassword.loadFile(filePath: "qa_output/encrypted_optimized.pdf")
    let q = CkoJsonObject()!
    let qOut = CkoJsonObject()!
    success = noPassword.extractText(op: "assess", jsonIn: q, jsonOut: qOut)
    print("passwordRequired without the password: \(qOut.bool(of: "quality.passwordRequired"))")

    //  With the password it reads normally.
    let withPassword = CkoPdf()!
    withPassword.userPassword = "secret"
    success = withPassword.loadFile(filePath: "qa_output/encrypted_optimized.pdf")
    if success == false {
        print("\(withPassword.lastErrorText!)")
        return
    }

    print("pages: \(withPassword.numPages.intValue)")

}