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

Deflate Compression Level When Optimizing a PDF

See more PDF Optimization Examples

Demonstrates compressionLevel, which is the deflate level (1 to 9, 9 by default) used for every stream the optimizer re-encodes. Level 9 is the smallest and the slowest; level 1 is the quickest. The difference is usually a percent or two, so level 9 is the right default for a file that will be downloaded many times, and a lower level is worth considering only when a server optimizes PDFs on the fly. A value outside 1 to 9 is an error.

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 fac = chilkat::FileAccess::new();
let json = chilkat::JsonObject::new();
let json_out = chilkat::JsonObject::new();

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

let _ = json.update_int("compressionLevel", 1);
if pdf1.optimize("optimize", &json, &json_out).is_err() {
    println!("{}", pdf1.last_error_text());
    return;
}

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

println!("level 1: {}", fac.file_size("qa_output/watersense_level1.pdf"));

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

let _ = json.update_int("compressionLevel", 9);
if pdf9.optimize("optimize", &json, &json_out).is_err() {
    println!("{}", pdf9.last_error_text());
    return;
}

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

println!("level 9: {}", fac.file_size("qa_output/watersense_level9.pdf"));

// A level outside 1..9 fails, and LastErrorText says why.
let pdf_bad = chilkat::Pdf::new();
if pdf_bad.load_file("qa_data/pdf/watersense_accomplishments.pdf").is_err() {
    println!("{}", pdf_bad.last_error_text());
    return;
}

let _ = json.update_int("compressionLevel", 12);
if pdf_bad.optimize("optimize", &json, &json_out).is_err() {
    println!("compressionLevel 12 was refused, as it should be.");
}