How-to guides/Document Structure

Delete pages from a PDF in Rust

Remove one page, a range of pages, or a custom set of page indices from a PDF. Bookmarks and named destinations are updated automatically.

rust
use pdfluent::PdfDocument;

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

    // Remove page 5 (zero-based index 4)
    doc.delete_page(4)?;

    doc.save("report_trimmed.pdf")?;
    println!("Remaining pages: {}", doc.page_count());
    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 you want to modify.

rust
use pdfluent::PdfDocument;

let mut doc = PdfDocument::open("draft.pdf")?;
println!("Before: {} pages", doc.page_count());
3

Delete a single page

Call delete_page() with the zero-based index of the page to remove. After deletion, indices of subsequent pages shift down by one.

rust
// Remove the last page
let last = doc.page_count() - 1;
doc.delete_page(last)?;

// Remove the first page
doc.delete_page(0)?;
4

Delete a range of pages

delete_page_range(start..end) removes all pages from start (inclusive) to end (exclusive). This is faster than looping with delete_page().

rust
// Remove pages 3 through 6 (indices 2..6, exclusive end)
doc.delete_page_range(2..6)?;
println!("After range delete: {} pages", doc.page_count());
5

Delete non-contiguous pages and save

Pass a Vec or slice of indices to delete_pages(). Provide indices in any order; PDFluent sorts and removes them correctly.

rust
// Remove pages at indices 1, 4, and 7
doc.delete_pages(&[1, 4, 7])?;

doc.save("draft_cleaned.pdf")?;
println!("Final page count: {}", doc.page_count());

Notes and tips

  • After deleting pages, all subsequent page indices decrease. Do not cache page indices across delete calls.
  • Bookmarks pointing to deleted pages are removed from the outline automatically.
  • delete_pages() accepts indices in any order. Duplicates are ignored.
  • Deleting all pages from a document is not allowed. At least one page must remain.

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