Rust Requires Chilkat v11.7.0+
Rust
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 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 invoice_signed.pdf
let pdf = chilkat::Pdf::new();
if pdf.load_file("qa_data/pdf/invoice_signed.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("signatures: {}", pdf.num_signatures());
let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();
// An audit changes nothing, so it is allowed on a signed PDF.
if pdf.optimize("audit", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("audit ok, estimated savings: {}", json_out.int_of("estimatedSavings.total"));
// Optimizing is refused while PreserveSignatures is true.
if pdf.optimize("optimize", &json, &json_out).is_err() {
println!("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.set_preserve_signatures(false);
if pdf.optimize("optimize", &json, &json_out).is_err() {
println!("{}", pdf.last_error_text());
return;
}
if pdf.write_file("qa_output/invoice_optimized.pdf").is_err() {
println!("{}", pdf.last_error_text());
return;
}
println!("optimized, bytesSaved: {}", json_out.int_of("bytesSaved"));
// The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
let pdf2 = chilkat::Pdf::new();
if pdf2.load_file("qa_output/invoice_optimized.pdf").is_err() {
println!("{}", pdf2.last_error_text());
return;
}
println!("signatures after: {}", pdf2.num_signatures());
let sig_info = chilkat::JsonObject::new();
let verified = pdf2.verify_signature(0, &sig_info).is_ok();
println!("verifies after optimizing: {}", verified);