How-to guides/Document Structure

Change the page order of a PDF in Rust

Rearrange, reverse, or interleave pages in a PDF document using a page index map.

rust
use pdfluent::Document;

fn main() -> pdfluent::Result<()> {
    let mut doc = Document::open("input.pdf")?;

    // Move the last page to the front
    let count = doc.page_count();
    let mut order: Vec<usize> = (0..count).collect();
    order.rotate_right(1);

    doc.reorder_pages(&order)?;
    doc.save("reordered.pdf")?;
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Open the PDF

Load the document and check the page count so you can build the index map.

rust
let mut doc = Document::open("input.pdf")?;
let count = doc.page_count();
2

Build a new page order

Create a Vec<usize> where each element is the zero-based index of the original page you want at that position. The vec must contain every index exactly once.

rust
// Reverse all pages
let order: Vec<usize> = (0..count).rev().collect();
3

Apply the new order

Call reorder_pages with the index slice. PDFluent rewrites the /Pages tree; no content streams are copied or duplicated.

rust
doc.reorder_pages(&order)?;
4

Move a specific page to a new position

Remove a page index from its current position and insert it at the target position.

rust
let mut order: Vec<usize> = (0..count).collect();
// Move page at index 4 to position 1
let page = order.remove(4);
order.insert(1, page);
doc.reorder_pages(&order)?;
5

Save the result

Write the reordered document to a file.

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

Notes and tips

  • The order slice must have exactly page_count() elements. Missing or duplicate indices return an error.
  • Bookmarks (outlines) that reference page destinations are updated automatically when page order changes.
  • Named destinations are also remapped so internal links continue to resolve correctly.
  • If you need to interleave two documents, use Document::merge first, then reorder.

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