How-to guides/Document Structure

Crop a PDF page by setting the crop box in Rust

Set the CropBox on any page to define the visible area without removing content from the file.

rust
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(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Open the PDF document

Load the file into a mutable Document. The document must be opened with write access so you can modify page boxes.

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

Understand coordinate space

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.

rust
// 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);
3

Set the CropBox on the target page

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.

rust
let crop_box = Rect::new(50.0, 100.0, 450.0, 600.0);
doc.page_mut(0)?.set_crop_box(crop_box);
4

Apply the same crop to multiple pages

Iterate over all pages and set the same CropBox, or compute a per-page crop based on the MediaBox dimensions.

rust
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);
}
5

Save the modified document

Write the result to a new file. The original content is preserved inside the file; only the CropBox annotation changes.

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

Notes and tips

  • Setting a CropBox does not delete page content. Viewers that ignore the CropBox will still show the full page.
  • The CropBox must be contained within the MediaBox. Passing a larger rect is technically invalid and may cause viewer warnings.
  • BleedBox, TrimBox, and ArtBox are separate boxes that can coexist with the CropBox. Use set_trim_box() for print workflows.
  • To remove a crop, call page.clear_crop_box() to reset the visible area to the full MediaBox.

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