How-to guides/Optimization

Linearize a PDF for faster web loading in Rust

Restructure a PDF so the first page is available before the full file downloads. Known as "Fast Web View" in Acrobat.

rust
use pdfluent::{PdfDocument, LinearizeOptions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut doc = PdfDocument::open("brochure.pdf")?;

    doc.linearize(LinearizeOptions::default())?;
    doc.save("brochure_linear.pdf")?;

    println!("PDF is now linearized for fast web view");
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Add PDFluent to your project

Add the pdfluent crate to Cargo.toml.

rust
[dependencies]
pdfluent = "0.9"
2

Open the PDF

Load the document. Linearization rearranges the internal file structure.

rust
use pdfluent::PdfDocument;

let mut doc = PdfDocument::open("catalogue.pdf")?;
3

Configure linearization options

LinearizeOptions lets you control hint tables and resource ordering. The defaults work well for most documents.

rust
use pdfluent::LinearizeOptions;

let opts = LinearizeOptions::default()
    .primary_page_hint_stream(true) // helps browsers fetch only page 1 first
    .reorder_resources_by_page(true);
4

Apply linearization

Call linearize() on the document. The internal structure is rearranged so the first page and its resources appear at the beginning of the file.

rust
doc.linearize(opts)?;

// Verify the result
println!("Linearized: {}", doc.is_linearized());
5

Save the linearized PDF

Write to a new file. Serve this file from your web server with byte-range request support enabled.

rust
doc.save("catalogue_linear.pdf")?;
println!("Ready to serve via HTTP with Range support");

Notes and tips

  • Linearization is only effective when the file is served over HTTP with byte-range requests enabled (Accept-Ranges: bytes).
  • Any modification after linearization (adding pages, annotations, etc.) removes the linearization. Re-linearize before re-serving.
  • Linearization increases file size by a few percent due to added hint tables. The trade-off is faster first-page display.
  • Use is_linearized() to check whether a PDF is already linearized before processing it again.

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