Set the CropBox on any page to define the visible area without removing content from the file.
use pdfluent::{Document, Rect};
fn main() -> pdfluent::Result<()> {
let mut doc = Document::open("input.pdf")?;
// Crop the first page to a 400x500 pt region starting at (50, 100)
let crop_box = Rect::new(50.0, 100.0, 450.0, 600.0);
doc.page_mut(0)?.set_crop_box(crop_box);
doc.save("cropped.pdf")?;
Ok(())
}Load the file into a mutable Document. The document must be opened with write access so you can modify page boxes.
let mut doc = Document::open("input.pdf")?;PDF coordinates start at the bottom-left corner of the page. A Rect is defined as (x_min, y_min, x_max, y_max) in points (1 pt = 1/72 inch). A standard A4 page is 595 x 842 pt.
// A4 page: bottom-left (0,0), top-right (595, 842)
// This rect keeps a 20 pt margin on all sides:
let rect = Rect::new(20.0, 20.0, 575.0, 822.0);The CropBox controls what viewers display. Content outside the CropBox is hidden but not deleted. You can remove the CropBox later to restore the full page.
let crop_box = Rect::new(50.0, 100.0, 450.0, 600.0);
doc.page_mut(0)?.set_crop_box(crop_box);Iterate over all pages and set the same CropBox, or compute a per-page crop based on the MediaBox dimensions.
let page_count = doc.page_count();
for i in 0..page_count {
let page = doc.page_mut(i)?;
let media = page.media_box();
// Remove a 30 pt border on all sides
let crop = Rect::new(
media.x_min + 30.0,
media.y_min + 30.0,
media.x_max - 30.0,
media.y_max - 30.0,
);
page.set_crop_box(crop);
}Write the result to a new file. The original content is preserved inside the file; only the CropBox annotation changes.
doc.save("cropped.pdf")?;No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.
Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.
Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.