Skip to Content
NexPDF

Compare and optimise

Compare two PDF versions page by page, make files smaller by pruning objects and subsetting fonts, save for Fast Web View and control memory with NexPDF for Rust.

English

License module

Comparing documents, linearized saving and the memory calls work without a key. optimize and subset_fonts need the editor module (Startup tier and above).

Compare two versions

compare_json(other, dpi) compares two documents page by page: whether the text changed and how much of the rendered page differs. compare_overlay_png(other, page_index, dpi) draws the differences of one page as a PNG.

use nexpdf_sdk::Document;

fn main() -> nexpdf_sdk::Result<()> {
    let a = Document::open("v1.pdf")?;
    let b = Document::open("v2.pdf")?;
    let diff = a.compare_json_value(&b, 72.0)?;              // `serde` feature
    println!("{} pages before, {} after", diff["pages_a"], diff["pages_b"]);

    for page in diff["pages"].as_array().into_iter().flatten() {
        let index = page["page"].as_u64().unwrap_or(0) as usize;
        let visual = page["visual_diff"].as_f64().unwrap_or(0.0);
        if page["text_changed"].as_bool() == Some(true) || visual > 0.001 {
            println!("page {}: {:.2}% of the pixels changed", index + 1, visual * 100.0);
            std::fs::write(format!("diff-{}.png", index + 1), a.compare_overlay_png(&b, index, 110.0)?)?;
        }
    }
    Ok(())
}

To see which words changed (inserted, deleted, replaced and moved text, and an annotated PDF of the changes), use Word-level comparison.

visual_diff is the share of differing pixels, from 0 to 1. A low resolution (72 dpi) is enough to find changed pages; the overlay resolution is clamped to 18-300 dpi.

Make files smaller

optimize() compresses uncompressed streams and removes objects nothing refers to. subset_fonts() replaces embedded TrueType, OpenType and CFF fonts with subsets of the glyphs the document uses. Both take &mut self and return a JSON report as a String; save afterwards.

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut doc = nexpdf_sdk::Document::open("large.pdf")?;
    let r: serde_json::Value = serde_json::from_str(&doc.optimize()?)?;
    println!(
        "{} streams compressed, {} objects pruned, {} bytes saved",
        r["streams_compressed"], r["objects_pruned"], r["bytes_saved"]
    );

    let f: serde_json::Value = serde_json::from_str(&doc.subset_fonts()?)?;
    println!("{} fonts subset: {} -> {} bytes", f["fonts_subset"], f["bytes_before"], f["bytes_after"]);

    doc.save("small.pdf")?;
    Ok(())
}

Fonts that may still be needed for new text are left whole and counted in fonts_skipped.

Fast Web View

Linearized files let a browser show the first page before the rest downloads:

doc.save_linearized_to("web.pdf")?;

Memory

memory_usage_bytes() estimates the memory a document uses. trim_memory() compacts its internal buffers and drops objects nothing refers to any more, and returns the bytes reclaimed. Both return a usize directly. Call trim_memory on long-running servers after large edits or batch work:

println!("{} KiB", doc.memory_usage_bytes() / 1024);
let freed = doc.trim_memory();

The document stays fully usable. Dropping it frees everything. See Platform notes for threading and memory.

On this page