Flatten PDF form fields in Rust

Convert interactive form fields into static page content. Flattening bakes the current field values into the page so they cannot be edited.

rust
use pdfluent::PdfDocument;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut doc = PdfDocument::open("filled_form.pdf")?;
    doc.flatten_form()?;
    doc.save("flattened.pdf")?;
    println!("Form fields removed, values baked into page content.");
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Open the filled form PDF

Open the document that has form fields with values already set. Flattening works on whatever values are currently in the fields.

rust
use pdfluent::PdfDocument;

let mut doc = PdfDocument::open("filled_application.pdf")?;
2

Flatten all form fields

Call flatten_form() to convert every field into static page content. The AcroForm dictionary is removed from the document.

rust
doc.flatten_form()?;
3

Flatten only specific fields

To flatten a subset of fields while leaving others editable, use flatten_fields() with a list of field names.

rust
doc.flatten_fields(&["first_name", "last_name", "date_signed"])?;
4

Verify the form is gone

After flattening, doc.has_form() returns false and the page text includes the values that were in the fields.

rust
assert!(!doc.has_form());
let text = doc.page(0)?.extract_text()?;
assert!(text.contains("Jane Smith"));
5

Save the flattened document

Save to a new file to keep the original editable version intact.

rust
doc.save("application_final.pdf")?;

Notes and tips

  • Flattening is irreversible. Keep the original filled-form PDF if you might need to re-extract the field values later.
  • Invisible fields (fields with no value and no visible appearance) are simply removed, not rendered.
  • Some complex field appearances use JavaScript to generate their display. PDFluent renders the last known appearance stream, not the JS output.

Why PDFluent for this

Pure Rust

No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.

Memory safe

Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.

Runs anywhere

Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.

Frequently asked questions