Swift Requires Chilkat v11.7.0+
Swift
Change the Passwords of an Encrypted PDF
See more PDF Protection Examples
Demonstrates the changePasswords operation, which gives an encrypted PDF new user and owner passwords and keeps its algorithm and permissions. The PDF is loaded with its current passwords, the two properties are then set to the new ones, and Protection reads them at the time of the call. Both passwords are replaced, so set both: a property left empty becomes an empty password.Chilkat Swift Downloads
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()!
// Load with the current passwords.
pdf.userPassword = "secret"
pdf.ownerPassword = "owner-secret"
success = pdf.loadFile(filePath: "qa_data/pdf/encrypted_user_password.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
// The new passwords. Protection reads the properties as they are when it is called.
pdf.userPassword = "new-user-secret"
pdf.ownerPassword = "new-owner-secret"
let json = CkoJsonObject()!
let jsonOut = CkoJsonObject()!
success = pdf.protection(op: "changePasswords", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
// The algorithm and the permissions are kept.
print("algorithm: \(jsonOut.string(of: "pending.algorithm")!)")
print("password needed to open: \(jsonOut.bool(of: "pending.userPasswordRequired"))")
success = pdf.writeFile(path: "qa_output/minutes_new_passwords.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
// The new user password opens the result.
let reader = CkoPdf()!
reader.userPassword = "new-user-secret"
success = reader.loadFile(filePath: "qa_output/minutes_new_passwords.pdf")
if success == false {
print("\(reader.lastErrorText!)")
return
}
success = reader.protection(op: "getInfo", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(reader.lastErrorText!)")
return
}
print("with the new user password, opened with: \(jsonOut.string(of: "loaded.openedWith")!)")
// And so does the new owner password.
let owner = CkoPdf()!
owner.ownerPassword = "new-owner-secret"
success = owner.loadFile(filePath: "qa_output/minutes_new_passwords.pdf")
if success == false {
print("\(owner.lastErrorText!)")
return
}
success = owner.protection(op: "getInfo", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(owner.lastErrorText!)")
return
}
print("with the new owner password, opened with: \(jsonOut.string(of: "loaded.openedWith")!)")
// Sample output:
// algorithm: rc4-128
// password needed to open: True
// with the new user password, opened with: user
// with the new owner password, opened with: owner
}