Swift Requires Chilkat v11.7.0+
Swift
Extract Text from a Password-Protected PDF
See more PDF Text Extraction Examples
Demonstrates extracting text from a PDF that requires a password to open. The PDF loads without the password (its structure can be read), but the "text" operation fails because the content cannot be decrypted; "assess" reports that a password is required. With the UserPassword property set before loading, extraction works normally.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 (user password: secret) is available at encrypted_user_password.pdf
let pdf = CkoPdf()!
let json = CkoJsonObject()!
let jsonOut = CkoJsonObject()!
// The PDF loads without its password: the file's structure is readable, so properties such as
// NumPages and the security settings are available...
success = pdf.loadFile(filePath: "qa_data/pdf/encrypted_user_password.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
// ...but the content cannot be decrypted, so extracting text fails.
success = pdf.extractText(op: "text", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("Cannot extract: \(pdf.lastErrorText!)")
}
// "assess" still works: it reports that a password is required and nothing else.
success = pdf.extractText(op: "assess", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("passwordRequired: \(jsonOut.bool(of: "quality.passwordRequired"))")
print("rating: \(jsonOut.string(of: "quality.rating")!)")
// Set the password and load again.
pdf.userPassword = "secret"
success = pdf.loadFile(filePath: "qa_data/pdf/encrypted_user_password.pdf")
if success == false {
print("\(pdf.lastErrorText!)")
return
}
success = pdf.extractText(op: "text", jsonIn: json, jsonOut: jsonOut)
if success == false {
print("\(pdf.lastErrorText!)")
return
}
print("\(jsonOut.string(of: "text")!)")
// Sample output:
// Cannot extract: ChilkatLog:
// ExtractText:
// ...
// The PDF is encrypted and could not be opened (wrong or missing password); its text cannot be read.
// ...
// passwordRequired: true
// rating: none
// Board Minutes (Confidential)
//
// The board met on 3 November 2026. Present: the chair, the treasurer and four members. The treasurer reported that spending for the season came in under budget.
//
// The meeting closed at 8.45 p.m.
}