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

Audit a PDF First, Optimize Only If It Is Worth It

See more PDF Optimization Examples

Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.

Chilkat Rust Downloads

Rust

// 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 watersense_accomplishments.pdf

let pdf = chilkat::Pdf::new();
if pdf.load_file("qa_data/pdf/watersense_accomplishments.pdf").is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();
if pdf.optimize("audit", &json, &json_out).is_err() {
    println!("{}", pdf.last_error_text());
    return;
}

let file_size = json_out.int_of("fileSize");
let estimated = json_out.int_of("estimatedSavings.total");
println!("fileSize:  {}", file_size);
println!("estimated: {}", estimated);

// Only bother when at least a tenth of the file would go.
if estimated > (file_size / 10) {
    println!("Worth optimizing.");
    if pdf.optimize("optimize", &json, &json_out).is_err() {
        println!("{}", pdf.last_error_text());
        return;
    }

    if pdf.write_file("qa_output/watersense_optimized.pdf").is_err() {
        println!("{}", pdf.last_error_text());
        return;
    }

    println!("bytesSaved: {}", json_out.int_of("bytesSaved"));
} else {
    println!("Already small enough; left as it is.");
}