Rust Requires Chilkat v11.7.0+
Rust
Password-Protect a PDF with AES-256 Encryption
See more PDF Protection Examples
Demonstrates the simplest way to encrypt a PDF so that it needs a password to open. The passwords come from the UserPassword and OwnerPassword properties, and Protection with the encrypt operation and an empty JSON uses the defaults: AES-256, everything encrypted, every permission granted. Protection only records the security the PDF will be saved with. Nothing is encrypted until WriteFile is called.Chilkat Rust Downloads
// 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 two_page_memo.pdf
let pdf = chilkat::Pdf::new();
if pdf.load_file("qa_data/pdf/two_page_memo.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
// The passwords are taken from these two properties at the time Protection is called.
// The user password opens the PDF. The owner password opens it too, and is the one needed
// later to change or remove the protection.
pdf.set_user_password("user-secret");
pdf.set_owner_password("owner-secret");
// An empty JSON asks for the defaults: AES-256, everything encrypted, every permission granted.
let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();
if pdf.protection("encrypt", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
// Nothing has been encrypted yet. "pending" describes the security the PDF will be saved with.
println!("algorithm: {}", json_out.string_of("pending.algorithm").unwrap_or_default());
println!("PDF version: {}", json_out.string_of("pending.pdfVersion").unwrap_or_default());
println!("password needed to open: {}", json_out.bool_of("pending.userPasswordRequired"));
// Writing the file applies it.
if pdf.write_file("qa_output/memo_encrypted.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
// PreLoadCheck reports a file's encryption without loading it, and needs no password.
let checker = chilkat::Pdf::new();
let info = chilkat::JsonObject::new();
if checker.pre_load_check("qa_output/memo_encrypted.pdf", &info).is_err() {
println!("{}", checker.last_error_text());
return;
}
println!("encrypted: {}", info.bool_of("encrypted"));
println!("openPasswordRequired: {}", info.bool_of("openPasswordRequired"));
// With the password, the PDF opens normally.
let reader = chilkat::Pdf::new();
reader.set_user_password("user-secret");
if reader.load_file("qa_output/memo_encrypted.pdf").is_err() {
println!("{}", reader.last_error_text());
return;
}
println!("pages: {}", reader.num_pages());
// Sample output:
// algorithm: aes-256
// PDF version: 1.7
// password needed to open: True
// encrypted: True
// openPasswordRequired: True
// pages: 2