Merge, split, edit, and inspect PDFs
On this page
- Merge PDFs in Rust
- Merge PDFs and generate a table of contents in Rust
- Split a PDF by page range in Rust
- Split a PDF at each top-level bookmark
- Extract specific pages from a PDF in Rust
- Drop pages from a PDF in Rust
- Insert blank or existing pages into a PDF in Rust
- Change the page order of a PDF in Rust
- Rotate one or all pages of a PDF in Rust
- Get the page count of a PDF in Rust
- Get page width, height, and media box in Rust
Add PDFluent to your project
[dependencies]
pdfluent = "1.5.0"Merge PDFs in Rust
use pdfluent::prelude::*;
fn main() -> Result<()> {
let merged = PdfMerger::new()
.add(PdfDocument::open("part1.pdf")?)
.add(PdfDocument::open("part2.pdf")?)
.add(PdfDocument::open("part3.pdf")?)
.build()?;
merged.save("combined.pdf")?;
println!("Merged {} pages into combined.pdf", merged.page_count());
Ok(())
}Complete program, compiled against the published crate: Code on GitHub →
The same code, typed and run on screen. Watch on YouTube
- Step 1
Open each input document
Open every source PDF with PdfDocument::open. The merger takes full PdfDocument values by move, so consume each input once.
rustuse pdfluent::prelude::*; let a = PdfDocument::open("invoice_jan.pdf")?; let b = PdfDocument::open("invoice_feb.pdf")?; let c = PdfDocument::open("invoice_mar.pdf")?; - Step 2
Build a PdfMerger and add inputs
Create a PdfMerger, chain .add() for each document. Inputs are appended in the order they are added.
rustlet merger = PdfMerger::new() .add(a) .add(b) .add(c); - Step 3
Configure bookmark handling
Choose a BookmarkMergeStrategy. Concat (the default) groups each source's bookmarks under a top-level entry; FlattenAll sequences them; Discard drops all bookmarks. In 1.0 Concat has dedicated treatment; FlattenAll and Discard fall back to the underlying concatenation.
rustlet merger = merger .with_bookmarks(BookmarkMergeStrategy::Concat) .with_page_labels(true); // 1.0: accepted but currently a no-op - Step 4
Build and save
Call .build() to produce a merged PdfDocument, then save or serialise it. build() is the terminating step and consumes the merger.
rustlet merged = merger.build()?; merged.save("annual_report.pdf")?; println!("Total pages: {}", merged.page_count());
- Named destinations from each input file are remapped so they remain valid in the merged document.
- Page labels from source files are treated on a best-effort basis in 1.0; full preservation lands in 1.1.
- Encrypted PDFs must be decrypted before merging — open them with OpenOptions::new().with_password("...") or call doc.decrypt("...") first.
- The merger processes inputs in the order they were added. Page numbering in the output starts at 1 and increases sequentially.
- Input bytes: open from memory with PdfDocument::from_bytes(&bytes) before adding to the merger — there is no separate add_bytes entry point.
- Does merging preserve interactive form fields?
- Form fields from each input survive in the merged document. Field name collisions between inputs are resolved with a best-effort strategy on the underlying pdf-manip merger. Inspect the merged field set via merged.form_fields().
- Can I merge more than 100 files at once?
- There is no hard file limit. Memory usage scales with total uncompressed page content. For very large batches, open and add in a loop; the merger keeps each input as a PdfDocument until build() runs.
- How do I control the page order?
- Documents are appended in the order .add is called. Call .add in the order you want pages to appear in the output.
- Does PDFluent merge XFA forms?
- The 1.0 merger handles AcroForm content. XFA data streams don't combine across documents — flatten XFA forms upstream or drop the XFA layer before merging.
Merge PDFs and generate a table of contents in Rust
use pdfluent::{PdfDocument, PdfMerger, BookmarkMergeStrategy};
fn main() -> pdfluent::Result<()> {
let merged = PdfMerger::new()
.add(PdfDocument::open("intro.pdf")?)
.add(PdfDocument::open("body.pdf")?)
.with_bookmarks(BookmarkMergeStrategy::Concat)
.with_page_labels(true)
.build()?;
merged.save("merged.pdf")?;
Ok(())
}- Step 1
Prepare MergeInput entries
Each MergeInput specifies a source file and an optional title used for the TOC entry and bookmark.
rustuse pdfluent::{PdfDocument, PdfMerger, BookmarkMergeStrategy}; let merger = PdfMerger::new() .add(PdfDocument::open("section1.pdf")?) .add(PdfDocument::open("section2.pdf")?) .add(PdfDocument::open("appendix.pdf")?); - Step 2
Configure merge options
Enable TOC generation and optionally configure the TOC page style, font, and bookmark depth.
rust// Concatenate each source's bookmarks under a top-level entry (navigation TOC). // Page labels preserve each section's original numbering. let merger = merger .with_bookmarks(BookmarkMergeStrategy::Concat) .with_page_labels(true); - Step 3
Merge and get the document
Document::merge_with_options returns a new Document. The TOC page is inserted at the position specified in the options.
rustlet merged = merger.build()?; - Step 4
Inspect the generated outlines
The merge operation adds bookmark entries that match the TOC. Verify they are present.
rustfor bookmark in merged.outlines()? { println!("'{}' -> page {:?}", bookmark.title, bookmark.page); } - Step 5
Save the merged document
Write the final merged file.
rustmerged.save("merged_with_toc.pdf")?;
- The TOC page is generated using the page dimensions of the first page in the merge list. Override with MergeOptions::toc_page_size(PageSize::A4).
- Existing bookmarks from each source document are preserved and nested under the top-level chapter bookmark.
- If a source document is encrypted, decrypt it before passing to MergeInput or pass the password with MergeInput::with_password(pw).
- Named destinations from each source document are re-scoped with a per-document prefix to avoid collisions.
- Can I merge more than two PDFs at once?
- Yes. The inputs Vec can contain any number of MergeInput entries. They are merged in the order provided.
- How do I merge specific page ranges from each file?
- Use MergeInput::from_file("file.pdf").pages(2..=5) to include only pages 3-6 (zero-indexed) from that file.
- Can I merge documents with different page sizes?
- Yes. Each page retains its original size. The TOC page uses a configurable size. Use resize_to_match_first(true) if you want all pages normalized to one size.
- How are form fields handled when merging?
- AcroForm fields are merged into a single form dictionary. Fields with duplicate names are renamed with a suffix. XFA forms are not merged; the XFA stream from the last document wins.
Split a PDF by page range in Rust
use pdfluent::PdfDocument;
fn main() -> pdfluent::Result<()> {
let doc = PdfDocument::open("report.pdf")?;
for (i, page) in doc.split_pages()?.into_iter().enumerate() {
page.save(format!("page-{}.pdf", i + 1))?;
}
Ok(())
}- Step 1
Open the source document
Load the PDF you want to split. PDFluent reads the file lazily, so opening a 500-page document uses minimal memory until pages are accessed.
rustuse pdfluent::PdfDocument; let doc = PdfDocument::open("quarterly_report.pdf")?; println!("Source has {} pages", doc.page_count()); - Step 2
Define page ranges
Create PageRange values for each segment. Pages are 1-indexed. Ranges can overlap if you need the same page in multiple output files.
rust// Ranges to extract (0-based, end-exclusive) let ranges = [0..5usize, 5..18, 18..22]; - Step 3
Split and write to separate files
Pass the ranges to split_by_ranges(). Use {n} in the output pattern for the range index, or provide a Vec of explicit output paths.
rustfor (i, range) in ranges.iter().enumerate() { doc.extract_pages(range.clone())?.save(format!("segment_{}.pdf", i + 1))?; } // Produces: segment_1.pdf, segment_2.pdf, segment_3.pdf - Step 4
Use explicit output names
When you need specific filenames, pass a slice of paths with the same length as the ranges slice.
rustlet names = ["cover.pdf", "body.pdf", "appendix.pdf"]; for (range, name) in ranges.iter().zip(names) { doc.extract_pages(range.clone())?.save(name)?; } - Step 5
Split into in-memory buffers
If you need to serve the split files over HTTP without touching disk, use to_bytes_vec() instead.
rustfor (i, range) in ranges.iter().enumerate() { let bytes = doc.extract_pages(range.clone())?.to_bytes()?; println!("Segment {}: {} bytes", i + 1, bytes.len()); }
- Page indices are 1-based. Passing 0 returns an error.
- Ranges that extend past the last page are clamped to the last page automatically.
- Bookmarks pointing to pages outside a range are dropped in that output file.
- AcroForm fields on pages that fall within a range are included in the corresponding output file.
- Can I split a single-page PDF?
- Yes, but the result is one output file identical to the input. There is no minimum page count requirement.
- What happens if ranges overlap?
- Each range is extracted independently. A page that appears in two ranges will appear in both output files. The source document is not modified.
- Does the split preserve hyperlinks on the extracted pages?
- Internal links pointing to pages within the same range are preserved. Links pointing outside the range are converted to plain text annotations with the destination URI where available.
- How do I split every page into its own file?
- Build a Vec<PageRange> with one entry per page using a loop: (1..=doc.page_count()).map(|n| PageRange::new(n, n)).collect(). Then pass that to split_by_ranges().
Split a PDF at each top-level bookmark
use pdfluent::PdfDocument;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let doc = PdfDocument::open("manual.pdf")?;
let results = doc
.split_by_top_level_bookmarks()
.write_files("{title}.pdf")?;
for r in &results {
println!("{} -> {} pages", r.filename, r.page_count);
}
Ok(())
}- Step 1
Open the PDF and inspect its outline
Check that the document has top-level bookmarks before splitting. PDFluent exposes the full outline tree via outline().
rustuse pdfluent::PdfDocument; let doc = PdfDocument::open("manual.pdf")?; let outline = doc.outline()?; println!("Top-level sections: {}", outline.len()); for item in &outline { println!(" {} -> page {}", item.title, item.destination_page); } - Step 2
Split at top-level bookmarks
split_by_top_level_bookmarks() computes the page range for each bookmark automatically. The range ends where the next bookmark starts.
rustlet splitter = doc.split_by_top_level_bookmarks(); - Step 3
Write output files using the bookmark title as filename
Use {title} in the pattern to name each file after its bookmark. PDFluent sanitises the title to produce a valid filename.
rustsplitter.write_files("{title}.pdf")?; // "Introduction.pdf", "Chapter 1.pdf", "Chapter 2.pdf", ... - Step 4
Split by a specific outline depth
To split at second-level bookmarks instead of the top level, set the depth parameter.
rustuse pdfluent::SplitDepth; doc.split_by_bookmarks(SplitDepth::Level(2)) .write_files("section_{n}.pdf")?; - Step 5
Collect results for further processing
If you need the split data in memory, use to_vec() to get a Vec of SplitSegment values without writing to disk.
rustlet segments = doc .split_by_top_level_bookmarks() .to_vec()?; for seg in segments { println!("{}: {} bytes", seg.title, seg.data.len()); // upload seg.data to S3, etc. }
- If the last bookmark has no following bookmark, its range extends to the last page of the document.
- Bookmarks that point to the same page as the next bookmark produce a zero-page segment. PDFluent skips these by default.
- Child bookmarks are included in the parent segment, not extracted separately, unless you use SplitDepth::Level(n).
- What if the PDF has no bookmarks?
- split_by_top_level_bookmarks() returns an Err with the NoOutline variant. Check for this and fall back to splitting by page range if needed.
- Can I split by second-level bookmarks only?
- Yes. Use split_by_bookmarks(SplitDepth::Level(2)). The splitter walks the outline tree to that depth and uses those items as split points.
- Are child bookmarks included in the split files?
- Yes. The output file for a top-level bookmark contains all pages in that section, including pages referenced by child bookmarks. The child bookmarks themselves are also copied into the output file.
- How does PDFluent handle duplicate bookmark titles?
- Filenames are deduplicated by appending _2, _3, etc. when the sanitised title would collide with an existing filename in the batch.
Extract specific pages from a PDF in Rust
use pdfluent::PdfDocument;
fn main() -> pdfluent::Result<()> {
let doc = PdfDocument::open("report.pdf")?;
let subset = doc.extract_pages(0..3)?;
subset.save("first-three.pdf")?;
Ok(())
}- Step 1
Open the source PDF
Open the document you want to extract pages from. Page count is available immediately after opening.
rustuse pdfluent::PdfDocument; let doc = PdfDocument::open("source.pdf")?; println!("{} pages total", doc.page_count()); - Step 2
Extract by page numbers
Pass a slice of 1-based page numbers. Pages appear in the output in the order given, so you can reorder them freely.
rust// Extract a contiguous page range (0-based, end-exclusive): pages 2-4 let extracted = doc.extract_pages(1..4)?; extracted.save("pages_2_to_4.pdf")?; - Step 3
Extract by page label
If the PDF uses custom page labels such as "i", "ii", "A-1", pass label strings instead of integers.
rust// Split into single-page documents for (i, page) in doc.split_pages()?.into_iter().enumerate() { page.save(format!("page_{}.pdf", i + 1))?; } - Step 4
Extract with a filter predicate
Use extract_pages_where() to filter programmatically. The closure receives a PageInfo struct with page number, label, width, height, and rotation.
rust// Extract a range and read the bytes (e.g. to send over HTTP) let bytes = doc.extract_pages(0..3)?.to_bytes()?; println!("Extracted PDF is {} bytes", bytes.len()); - Step 5
Save or return as bytes
Call save() to write to disk, or to_bytes() to get the PDF data as a Vec<u8> for streaming or further processing.
rust// Extract the final two pages by range and save let n = doc.page_count(); doc.extract_pages(n.saturating_sub(2)..n)?.save("last_pages.pdf")?;
- Pages are extracted in the order of the input slice. Duplicates are allowed and produce repeated pages.
- Annotations and form fields on extracted pages are included.
- If a page number is out of range, extract_pages returns an Err immediately before writing any output.
- Can I extract every other page?
- Yes. Build the page list with a range step: (1..=doc.page_count()).step_by(2).collect::<Vec<_>>(). Pass that to extract_pages().
- Does extracting pages preserve the document outline?
- Bookmarks pointing to extracted pages are kept. Bookmarks pointing to pages that were not extracted are removed from the output outline.
- What is the difference between extract_pages and split_by_ranges?
- extract_pages takes an arbitrary list of individual page numbers and returns one output document. split_by_ranges takes a list of contiguous ranges and returns multiple output documents.
Drop pages from a PDF in Rust
use pdfluent::{PdfDocument, PdfMerger};
fn main() -> pdfluent::Result<()> {
let doc = PdfDocument::open("report.pdf")?;
let total = doc.page_count();
// Keep everything except page 5. Page numbers are 1-based and both ends of
// the range are included -- and a range must not be empty, so the run after
// page 5 is only added when there is one.
let mut merger = PdfMerger::new().add(doc.extract_pages(1..=4)?);
if total > 5 {
merger = merger.add(doc.extract_pages(6..=total)?);
}
let trimmed = merger.build()?;
trimmed.save("report_trimmed.pdf")?;
println!("Remaining pages: {}", trimmed.page_count());
Ok(())
}- Step 1
Open the PDF and count its pages
The count is what the runs you keep are built from, and the source document is never modified.
rustuse pdfluent::{PdfDocument, PdfMerger}; let doc = PdfDocument::open("draft.pdf")?; let total = doc.page_count(); println!("Before: {} pages", total); - Step 2
Drop a page at the edge
Dropping the first or the last page leaves a single run, so no merge is needed. extract_pages returns a new document.
rust// Without the first page. let without_first = doc.extract_pages(2..=total)?; // Without the last page. let without_last = doc.extract_pages(1..=total - 1)?; without_last.save("draft_without_last.pdf")?; - Step 3
Drop a run in the middle
Extract what is on either side of the run and concatenate the two with PdfMerger. Guard the second range the same way: a run that would start past the last page is an error, not an empty document.
rust// Drop pages 3 to 6. let mut merger = PdfMerger::new().add(doc.extract_pages(1..=2)?); if total > 6 { merger = merger.add(doc.extract_pages(7..=total)?); } let trimmed = merger.build()?; println!("After the range: {} pages", trimmed.page_count()); - Step 4
Drop pages that are not next to each other, and save
Walk the page numbers you are dropping in ascending order and add the run that sits before each of them, then whatever is left at the end.
rust// Drop pages 2, 5 and 8. let drop = [2usize, 5, 8]; let mut merger = PdfMerger::new(); let mut start = 1usize; for page in drop { if page > start { merger = merger.add(doc.extract_pages(start..=page - 1)?); } start = page + 1; } if start <= total { merger = merger.add(doc.extract_pages(start..=total)?); } merger.build()?.save("draft_cleaned.pdf")?;
- PDFluent 1.0 has no in-place page removal. Removing a page is expressed as keeping the rest: extract the runs you want and concatenate them.
- Page numbers are 1-based and ranges include both ends, so extract_pages(1..=4) is the first four pages.
- An empty range is an error rather than an empty document, and so is a page number past the end. That is why the edge cases above are one run and not two.
- Nothing is written until you call save on the document the merger built. The document you opened is unchanged on disk and in memory.
- Extract and merge rebuild the page tree, and neither carries an outline or an internal GoTo destination across correctly: bookmarks and links into the document can end up pointing at the wrong page or at nothing. For a document whose navigation matters, check the result before shipping the pipeline.
- Is there a doc.delete_page(index)?
- Not in 1.0. The public API removes pages by keeping the others: extract_pages for each run you keep, PdfMerger to put them back together. A single-call form is a candidate for 1.1.
- How do I keep only a specific set of pages?
- That is the same shape as the last step above, with the runs you want instead of the runs between what you drop. For one contiguous run it is a single extract_pages call.
- Can I undo it?
- There is nothing to undo: the source document is untouched. Only the merged document is written, and only when you save it.
- What happens to a form field on a page I drop?
- Everything that lives on a page travels with that page, so a widget on a dropped page is gone from the result. The document-level form dictionary is carried over by the extract, so a document that is left without any of its fields can still carry an empty AcroForm.
Insert blank or existing pages into a PDF in Rust
use pdfluent::{PdfDocument, PageSize};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut doc = PdfDocument::open("report.pdf")?;
// Insert a blank A4 page after page 2 (at index 2)
doc.insert_blank_page(2, PageSize::A4)?;
doc.save("report_with_divider.pdf")?;
println!("Page inserted. New count: {}", doc.page_count());
Ok(())
}- Step 1
Open the target PDF
Load the document you want to modify.
rustuse pdfluent::PdfDocument; let mut doc = PdfDocument::open("annual_report.pdf")?; println!("Current page count: {}", doc.page_count()); - Step 2
Insert a blank page at a position
insert_blank_page(index, size) inserts a new empty page before the page at that index. Use index = page_count() to append at the end.
rustuse pdfluent::PageSize; // Insert blank A4 page before the third page (index 2) doc.insert_blank_page(2, PageSize::A4)?; // Append a blank Letter page at the end doc.insert_blank_page(doc.page_count(), PageSize::Letter)?; - Step 3
Insert pages from another PDF
Open a second document and copy pages from it into the target at a specific position.
rustlet source = PdfDocument::open("cover_page.pdf")?; // Insert the first page of source before page 0 (prepend) doc.insert_page_from(0, &source, 0)?; // Insert pages 1-3 from source after the current last page for i in 1..=3 { let pos = doc.page_count(); doc.insert_page_from(pos, &source, i)?; } - Step 4
Save the modified document
Write the result to disk.
rustdoc.save("report_expanded.pdf")?; println!("New page count: {}", doc.page_count());
- Insertion indices are zero-based. Inserting at index 0 prepends the page before the current first page.
- insert_page_from() copies the page content, resources, and annotations from the source document.
- Bookmarks from the source document are not automatically carried over. Add them manually if needed.
- PageSize::Custom(width, height) accepts dimensions in points for non-standard page sizes.
- How do I prepend a cover page to an existing PDF?
- Open the cover PDF, then call doc.insert_page_from(0, &cover_doc, 0). This inserts page 0 of the cover before page 0 of the target, making it the new first page.
- Can I insert multiple pages from a source document in one call?
- Use insert_pages_from(position, &source, page_range) where page_range is a Range<usize>. This is more efficient than looping with insert_page_from.
- Does inserting a page update bookmark destinations?
- Yes. PDFluent adjusts page-index-based bookmark destinations automatically. Named destinations are also remapped.
- What page size should I use for a blank divider page?
- Use the same size as the surrounding pages. Read the MediaBox of an adjacent page with doc.page(index).media_box() and pass those dimensions as PageSize::Custom(w, h).
Change the page order of a PDF in Rust
use pdfluent::{PdfDocument, PdfMerger};
fn main() -> pdfluent::Result<()> {
let doc = PdfDocument::open("input.pdf")?;
let count = doc.page_count();
// The page numbers, in the order you want them. Move the last to the front.
let mut order: Vec<usize> = (1..=count).collect();
order.rotate_right(1);
let mut merger = PdfMerger::new();
for page in &order {
merger = merger.add(doc.extract_pages(*page..=*page)?);
}
merger.build()?.save("reordered.pdf")?;
Ok(())
}- Step 1
Open the PDF
Load the document and read the page count; the order you build is a permutation of those page numbers.
rustuse pdfluent::{PdfDocument, PdfMerger}; let doc = PdfDocument::open("input.pdf")?; let count = doc.page_count(); - Step 2
Build the new order
1-based page numbers in the order you want to read them. Every page you want in the result has to appear in it.
rust// Reverse the document. let order = (1..=count).rev().collect::<Vec<usize>>(); - Step 3
Assemble the document in that order and save it
Extract each page on its own and concatenate them. This is what 1.0 offers; there is no call that rewrites the page tree in place. The source file is untouched.
rustuse pdfluent::PdfMerger; let mut merger = PdfMerger::new(); for page in &order { merger = merger.add(doc.extract_pages(*page..=*page)?); } merger.build()?.save("reordered.pdf")?; - Step 4
Move one page to another position
Change the order vector rather than the document: take the page number out and put it back where you want it.
rustlet mut order = (1..=count).collect::<Vec<usize>>(); // Move page 5 to second position. let page = order.remove(4); order.insert(1, page);
- PDFluent 1.0 has no reorder_pages. Reordering is a merge of one-page extracts, in the order you choose.
- OUTLINES AND INTERNAL LINKS DO NOT SURVIVE THIS. Each extract keeps the catalog of the document it was cut from and the merge imports the later pages under new object ids, so bookmarks and GoTo destinations end up pointing at pages that are no longer where they were. For a document whose navigation matters, 1.0 has no shape that reorders it -- that is what the page-order call on the backlog is for.
- Page numbers are 1-based, which is also how they are printed on the page. extract_pages(3..=3) is the third page.
- The order vector does not have to be a permutation of the whole document: leave a page number out and it is not in the result, put one in twice and it is in there twice. That is the one thing this shape does that an in-place reorder cannot.
- One extract per page means one clone of the document per page, so for a document of hundreds of pages this costs real time. Sort out the pages you actually need first.
- Is there a doc.reorder_pages(&order)?
- Not in 1.0. The page order is decided by the order in which you hand documents to PdfMerger. A call that rewrites the page tree in place -- which is also the only way to keep the outline and the internal links correct -- is on the backlog.
- What happens to annotations?
- An annotation is stored on its page, so it travels with the page. A link annotation that points at another page in the same document is a different matter: its destination is not remapped, so it can end up pointing at the wrong page or at nothing.
- Can I duplicate a page this way?
- Yes. Put the same page number in the order vector twice and it is extracted and added twice.
- How do I interleave the two sides of a duplex scan?
- Build the order by alternating the front and back numbers -- [1, n, 2, n-1, ...] -- and hand it to the same loop. A scan has no outline, which is the case this shape suits best.
Rotate one or all pages of a PDF in Rust
use pdfluent::{PdfDocument, Rotation};
fn main() -> pdfluent::Result<()> {
let mut doc = PdfDocument::open("scan.pdf")?;
for page in 1..=doc.page_count() {
doc.rotate_page(page, Rotation::Clockwise90)?;
}
doc.save("rotated.pdf")?;
Ok(())
}- Step 1
Open the PDF
Load the file you want to rotate.
rustuse pdfluent::PdfDocument; let mut doc = PdfDocument::open("scanned_contract.pdf")?; - Step 2
Rotate a single page
Call doc.rotate_page(page, rotation) with a 1-based page number. The Rotation enum has Clockwise90, Clockwise180 and Clockwise270; there is no variant for 0, because rotating by nothing is not an operation.
rustuse pdfluent::Rotation; // Rotate page 3 90 degrees clockwise. Pages are 1-based. doc.rotate_page(3, Rotation::Clockwise90)?; // Rotate page 4 upside-down doc.rotate_page(4, Rotation::Clockwise180)?; - Step 3
Rotate a page range
Loop over a range of page indices to rotate a contiguous section.
rust// Rotate pages 5 through 8 for i in 5..=8 { doc.rotate_page(i, Rotation::Clockwise270)?; } - Step 4
Rotate all pages and save
Iterate over all pages and apply the same rotation, then write the output.
rustlet count = doc.page_count(); for i in 1..=count { doc.rotate_page(i, Rotation::Clockwise90)?; } doc.save("document_rotated.pdf")?; println!("Rotated {} pages", count);
- rotate_page() sets the /Rotate entry in the page dictionary. This is the standard PDF rotation mechanism.
- Rotation is additive if you call it multiple times on the same page. Use Rotation::None to reset to zero degrees.
- Page content streams are not modified. The rotation is stored as metadata and applied by the PDF viewer.
- To get the current rotation before changing it, call page.rotation() which returns a Rotation value.
- What is the difference between Clockwise90 and CounterClockwise90?
- PDF /Rotate values are counter-clockwise by the ISO 32000 spec. Rotation::Clockwise90 in PDFluent writes /Rotate 270 to achieve a 90-degree clockwise visual rotation. PDFluent uses intuitive naming so you get the expected visual result.
- Can I rotate pages to an arbitrary angle like 45 degrees?
- The PDF /Rotate entry only supports multiples of 90 degrees, and rotate_page is a wrapper over that entry. Arbitrary angles mean rewriting the page content stream with a transformation matrix, which PDFluent does not expose.
- Does rotating affect the MediaBox dimensions?
- No. The MediaBox stays unchanged. The rotation flag tells viewers to display the page rotated. If you need the effective width/height after rotation, swap width and height when rotation is 90 or 270.
- How do I detect pages that are already rotated?
- Call page.rotation() which returns the current Rotation value. Pages with no /Rotate entry return Rotation::None (0 degrees).
Get the page count of a PDF in Rust
use pdfluent::PdfDocument;
fn main() -> pdfluent::Result<()> {
let doc = PdfDocument::open("file.pdf")?;
println!("{} pages", doc.page_count());
Ok(())
}Complete program, compiled against the published crate: Code on GitHub →
The same code, typed and run on screen. Watch on YouTube
- Step 1
Open the PDF and call page_count()
page_count() reads the /Count entry in the PDF page tree. It doesn't parse page content streams; for a well-formed PDF the call is effectively O(1).
rustuse pdfluent::prelude::*; let doc = PdfDocument::open("invoice.pdf")?; let count = doc.page_count(); println!("This PDF has {} page(s)", count); - Step 2
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().
rustlet pdf_bytes: Vec<u8> = fetch_pdf_from_database()?; let doc = PdfDocument::from_bytes(&pdf_bytes)?; println!("Pages: {}", doc.page_count()); - Step 3
Walk the page tree when /Count is suspect
Some malformed PDFs have an incorrect /Count entry. If you need a physically-verified count, iterate doc.pages() and count as you go — each iteration step resolves the next page from the tree.
rustlet doc = PdfDocument::open("maybe_corrupt.pdf")?; let physical_count = doc.pages().count(); let declared_count = doc.page_count(); assert_eq!(physical_count, declared_count, "declared /Count != physical pages"); - Step 4
Batch page counts for a directory of PDFs
Loop over files and collect counts. PdfDocument opens in-memory, so drop each doc between iterations to keep allocations bounded.
rustuse pdfluent::prelude::*; use std::fs; for entry in fs::read_dir("./invoices")? { let path = entry?.path(); if path.extension().map(|e| e == "pdf").unwrap_or(false) { match PdfDocument::open(&path) { Ok(doc) => println!("{}: {} pages", path.display(), doc.page_count()), Err(e) => eprintln!("{}: error - {}", path.display(), e), } } }
- page_count() returns a usize. A valid PDF always has at least 1 page.
- Encrypted PDFs require decryption before the page count is accessible. Open them with PdfDocument::open_with(path, OpenOptions::new().with_password("...")).
- If you need a physically-accurate count against a potentially-malformed /Count entry, walk doc.pages().count() as shown in step 4.
- Page indexing in the 1.0 SDK is 1-based throughout (RFC 0001 §1).
- Is page_count() slow for large PDFs?
- No. PDFluent reads the /Count field from the document catalog, which is resolved during the normal open path and cached on the PdfDocument. Subsequent calls are free.
- What if the PDF is password protected?
- Pass the password through OpenOptions: PdfDocument::open_with("file.pdf", OpenOptions::new().with_password("...")). The page count is then readable normally.
- Does page_count include blank pages inserted by a printer driver?
- Yes. Every page in the PDF page tree is counted, including blank pages. There is no distinction between blank and content pages at the page count level.
- How do I get the page count of each file in a ZIP archive of PDFs?
- Use a ZIP crate to extract each file to a byte buffer, then PdfDocument::from_bytes(&buf).map(|d| d.page_count()) for each entry.
Get page width, height, and media box in Rust
use pdfluent::PdfDocument;
fn main() -> pdfluent::Result<()> {
let doc = PdfDocument::open("file.pdf")?;
for i in 1..=doc.page_count() {
let (w, h) = doc.page(i)?.dimensions();
println!("page {}: {} x {} pt", i, w, h);
}
Ok(())
}- Step 1
Open the PDF and access pages
Open the document and iterate or index pages directly.
rustuse pdfluent::PdfDocument; let doc = PdfDocument::open("blueprint.pdf")?; let page = doc.page(1)?; // first page - Step 2
Read the MediaBox
The MediaBox defines the full physical extent of the page in PDF user units (points). 1 point = 1/72 inch.
rustlet (width, height) = page.dimensions(); println!("Width: {:.2} pt", width); println!("Height: {:.2} pt", height); - Step 3
Read CropBox and BleedBox
CropBox is the visible page area. BleedBox is for print bleed. Both fall back to the MediaBox if not set.
rust// PDFluent exposes the effective page size via dimensions() let (width, height) = page.dimensions(); println!("Page: {:.1} x {:.1} pt", width, height); - Step 4
Convert to millimetres and inches
PDF points convert to mm with factor 25.4/72 and to inches with factor 1/72.
rustfn pt_to_mm(pt: f64) -> f64 { pt * 25.4 / 72.0 } fn pt_to_inch(pt: f64) -> f64 { pt / 72.0 } let (w, h) = page.dimensions(); println!( "Page size: {:.1} x {:.1} mm ({:.3} x {:.3} in)", pt_to_mm(w), pt_to_mm(h), pt_to_inch(w), pt_to_inch(h), );
- PDF units are always points (1/72 inch). There is no concept of DPI at the page dimension level.
- A standard A4 page is 595 x 842 pt. Letter is 612 x 792 pt.
- Pages in the same document can have different sizes. Always read dimensions per-page, not once for the document.
- Rotate() entry affects display orientation. Use page.rotation() to read it and adjust width/height for display purposes.
- What is the difference between MediaBox and CropBox?
- MediaBox is the full physical size of the page including printer marks. CropBox is the region shown to the user in a viewer. If CropBox is not set, it defaults to the MediaBox.
- How do I detect if a page is landscape or portrait?
- Compare media_box().width() and media_box().height(). If width > height the page is landscape. Also account for the page rotation with page.rotation().
- Does PDFluent account for page rotation when returning dimensions?
- media_box() returns the raw box values as stored. If you need the effective width and height as displayed, read page.rotation() and swap width/height when rotation is 90 or 270 degrees.
- Can I set the page size programmatically?
- No. Page geometry is readable but not writable: Page::dimensions() reports the effective size, and there is no setter for the MediaBox or the other page boxes.