How-to guides/Document Info

Get the page count of a PDF in Rust

Read the total number of pages from a PDF file. PDFluent reads the page count from the document catalog without loading every page into memory.

rust
use pdfluent::PdfDocument;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let doc = PdfDocument::open("report.pdf")?;
    println!("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 and call page_count()

page_count() reads the /Count entry in the PDF page tree. This is an O(1) operation on well-formed PDFs.

rust
use pdfluent::PdfDocument;

let doc = PdfDocument::open("invoice.pdf")?;
let count = doc.page_count();
println!("This PDF has {} page(s)", count);
3

Get page count from bytes

If the PDF is already in memory (from a network response or database blob), use from_bytes() instead of open().

rust
let pdf_bytes: Vec<u8> = fetch_pdf_from_database()?;
let doc = PdfDocument::from_bytes(&pdf_bytes)?;
println!("Pages: {}", doc.page_count());
4

Get page count without loading the full document

For a fast page count check without retaining the document, use the PdfInfo helper. It parses only the document catalog.

rust
use pdfluent::PdfInfo;

let info = PdfInfo::from_file("large_archive.pdf")?;
println!("Pages: {}", info.page_count);
// info is dropped here - no PdfDocument held in memory
5

Batch page counts for a directory of PDFs

Loop over files and collect counts. PdfInfo keeps allocations low when processing many files.

rust
use pdfluent::PdfInfo;
use std::fs;

let dir = fs::read_dir("./invoices")?;
for entry in dir {
    let path = entry?.path();
    if path.extension().map(|e| e == "pdf").unwrap_or(false) {
        match PdfInfo::from_file(&path) {
            Ok(info) => println!("{}: {} pages", path.display(), info.page_count),
            Err(e) => eprintln!("{}: error - {}", path.display(), e),
        }
    }
}

Notes and tips

  • PdfInfo::from_file() is faster than opening a full PdfDocument when you only need basic metadata.
  • page_count() returns a usize. A valid PDF always has at least 1 page.
  • Encrypted PDFs require decryption before the page count is accessible. Use open_with_password().
  • Some malformed PDFs have an incorrect /Count entry. Call doc.pages().count() to walk the actual page tree if you need an accurate value.

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