Scanned contracts, invoices, and automatically generated reports often contain more whitespace than necessary. Sometimes the actual content occupies only part of the page, leaving large margins around it.
Cropping a few PDF pages manually is easy enough. But if you're building a document management system or processing hundreds of scanned files, you'll probably want to automate the process.
Instead of converting PDF pages to images and cropping the resulting bitmaps, you can modify the visible page boundaries directly in Java. This preserves the original text and vector graphics while hiding unwanted areas.
In this tutorial, we'll look at how to:
- Crop an individual PDF page.
- Trim margins from all pages in a PDF document.
- Crop a specific PDF region and export it as a PNG image.
We'll also cover how PDF cropping works and why it shouldn't be confused with permanently removing content.
Understanding PDF Cropping: MediaBox vs. CropBox
Before writing any code, it helps to understand two page boundaries defined by the PDF format.
| Page Box | Description |
|---|---|
| MediaBox | Defines the full physical boundaries of a PDF page. |
| CropBox | Defines the region of the page that is visible when displayed or printed. |
Suppose you have a PDF page measuring approximately 595 × 842 points (A4 portrait), with 40 points of unwanted whitespace on each side.
By setting the CropBox to a smaller rectangle, you can reduce the visible page area to 515 × 762 points without modifying the original page content.
This is different from resizing a page or converting it into an image. The content retains its original scale, and text within the visible area generally remains selectable and searchable.
One important detail: cropping a PDF hides content outside the selected region; it does not permanently delete it. We'll return to this distinction later.
Getting Started
You'll need a Java PDF library that supports reading and modifying page boundaries, as well as rendering PDF pages to images.
The examples below use a free library and can run without Adobe Acrobat or other PDF editing software installed.
If you're using Maven, add the following repository and dependency to your project's pom.xml file:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>9.13.0</version>
</dependency>
</dependencies>
The free edition supports saving up to 10 pages per PDF document and converting the first three pages to other formats. Use small PDF files when testing the examples.
The cropping examples assume that the input pages are unrotated, have a standard zero-origin coordinate system, and have no existing crop that needs to be preserved.
1. Crop an Individual PDF Page in Java
Let's start with a PDF report whose first page contains unnecessary margins.
To crop the page, we can use the PdfPageBase.setCropBox() method. It accepts a Rectangle2D object that describes the region we want to keep.
The rectangle is defined using four parameters:
Rectangle2D.Float(x, y, width, height)
| Parameter | Meaning |
|---|---|
x |
Horizontal position of the crop rectangle |
y |
Vertical position of the crop rectangle |
width |
Width of the retained area |
height |
Height of the retained area |
PDF coordinates are typically measured in points, where 72 points equal one inch.
Rather than hardcoding the page dimensions, we can retrieve them from the MediaBox and calculate the crop rectangle based on the desired margins.
The following example removes 40 points from each side of the first page.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import java.awt.geom.Rectangle2D;
public class CropPdfPage {
public static void main(String[] args) {
PdfDocument pdf = new PdfDocument();
try {
// Load the PDF document
pdf.loadFromFile("sales_report.pdf");
// Get the first page (zero-based index)
PdfPageBase page = pdf.getPages().get(0);
// Get the original page boundaries
Rectangle2D mediaBox = page.getMediaBox();
float width = (float) mediaBox.getWidth();
float height = (float) mediaBox.getHeight();
// Define the margin to trim, in points
float margin = 40f;
// Calculate the dimensions of the retained area
float cropWidth = width - 2 * margin;
float cropHeight = height - 2 * margin;
// Make sure the crop rectangle is valid
if (cropWidth <= 0 || cropHeight <= 0) {
throw new IllegalArgumentException(
"The crop margins exceed the page dimensions."
);
}
// Define the crop rectangle
Rectangle2D cropBox = new Rectangle2D.Float(
margin,
margin,
cropWidth,
cropHeight
);
// Apply the crop rectangle
page.setCropBox(cropBox);
// Save the modified PDF
pdf.saveToFile("sales_report_cropped.pdf");
} finally {
pdf.close();
}
}
}
Open the resulting PDF, and you'll see that the outer margins of the first page are no longer visible. The remaining pages are unaffected.
For an original page measuring 595 × 842 points, the new visible area measures approximately 515 × 762 points.
Because the crop dimensions are calculated from the original page size, the same approach works with different paper sizes under the coordinate assumptions described above.
Keep in mind that this is fixed-margin cropping, not automatic whitespace detection. If any text or graphics extend into the outer 40 points of the page, they will also be hidden.
2. Trim Margins from All PDF Pages in Java
When processing scanned documents or reports, you'll often need to apply the same margin adjustments to every page.
A common mistake is to calculate a crop rectangle using the first page's dimensions and reuse it for the entire document. This can produce incorrect results if the PDF contains a mixture of portrait and landscape pages or different paper sizes.
Instead, retrieve each page's dimensions individually and calculate its crop rectangle inside a loop.
The following example trims 30 points from all four sides of every page.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import java.awt.geom.Rectangle2D;
public class CropAllPdfPages {
public static void main(String[] args) {
PdfDocument pdf = new PdfDocument();
try {
// Load a multi-page PDF
pdf.loadFromFile("scanned_report.pdf");
float margin = 30f;
// Process each page independently
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
// Get the current page boundaries
Rectangle2D mediaBox = page.getMediaBox();
float width = (float) mediaBox.getWidth();
float height = (float) mediaBox.getHeight();
// Calculate the new visible dimensions
float cropWidth = width - 2 * margin;
float cropHeight = height - 2 * margin;
// Skip pages that are too small
if (cropWidth <= 0 || cropHeight <= 0) {
System.out.println(
"Skipping page " + (i + 1)
+ ": invalid crop dimensions."
);
continue;
}
// Create the crop rectangle
Rectangle2D cropBox = new Rectangle2D.Float(
margin,
margin,
cropWidth,
cropHeight
);
// Apply the crop to the current page
page.setCropBox(cropBox);
// Print the original and cropped dimensions
System.out.printf(
"Page %d: %.2f x %.2f pt -> %.2f x %.2f pt%n",
i + 1,
width,
height,
cropWidth,
cropHeight
);
}
// Save the cropped document
pdf.saveToFile("scanned_report_cropped.pdf");
} finally {
pdf.close();
}
}
}
For a document containing pages of different sizes, the console output might look like this:
Page 1: 595.00 x 842.00 pt -> 535.00 x 782.00 pt
Page 2: 612.00 x 792.00 pt -> 552.00 x 732.00 pt
Page 3: 842.00 x 595.00 pt -> 782.00 x 535.00 pt
Each page retains its original content scale while its visible boundaries are adjusted according to its own dimensions.
This approach is particularly useful for scanned documents produced using consistent scanning settings or reports generated from a standard template.
However, if the content position varies significantly from page to page, a uniform margin may not be appropriate. In that case, you'll need page-specific crop coordinates or a separate content-boundary detection step.
Also, these examples calculate the crop rectangle from the MediaBox. If your document already has a CropBox and you want to trim the currently visible area further, use getCropBox() to obtain the existing boundaries instead.
3. Crop a PDF Region and Export It as a PNG Image
Sometimes you don't need a cropped PDF at all. You only want an image of a particular area within a page.
For example, you might want to:
- Extract a chart from a financial report.
- Capture the totals section of an invoice.
- Prepare a specific document region for OCR.
- Generate a preview image for a web application.
One approach is to render the entire PDF page as an image and then crop the bitmap. However, this requires mapping PDF coordinates to image pixels, taking the rendering resolution into account.
Alternatively, you can set the page's CropBox first and then render the cropped page directly.
Suppose the first page of monthly_sales_report.pdf contains a chart. We know the approximate coordinates of the chart and want to export that region as a PNG file.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImageType;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ExportPdfRegionAsImage {
public static void main(String[] args) throws IOException {
PdfDocument pdf = new PdfDocument();
try {
// Load the PDF document
pdf.loadFromFile("monthly_sales_report.pdf");
// Get the first page
PdfPageBase page = pdf.getPages().get(0);
// Define the region to export
Rectangle2D cropBox = new Rectangle2D.Float(
80f,
200f,
430f,
260f
);
// Apply the crop rectangle
page.setCropBox(cropBox);
// Render the cropped page as an image
BufferedImage image = pdf.saveAsImage(
0,
PdfImageType.Bitmap
);
// Export the image as a PNG file
ImageIO.write(
image,
"PNG",
new File("monthly_sales_chart.png")
);
} finally {
pdf.close();
}
}
}
The resulting PNG contains the selected region rather than the entire PDF page.
You'll need to adjust the rectangle coordinates and dimensions to match the actual location of the content in your document. Make sure the rectangle stays within the page boundaries.
Notice that the code doesn't call saveToFile(). The crop is applied to the document in memory, and only the resulting image is saved. The original PDF file remains unchanged.
This is useful when your application needs a visual representation of a specific document region but doesn't need to produce another PDF.
Unlike a cropped PDF, however, the exported PNG contains rasterized pixels rather than selectable text or vector graphics.
Common Pitfalls When Cropping PDFs
PDF cropping is relatively straightforward for standard documents, but there are a few details worth considering before using it in a production workflow.
Cropping Does Not Automatically Reduce File Size
Changing the CropBox adjusts the visible page boundaries, but the original content streams, embedded images, and fonts can remain in the file.
As a result, a cropped PDF may be roughly the same size as the original.
If reducing file size is your main goal, consider PDF compression or image optimization instead.
Cropping Does Not Turn Scanned Text into Searchable Text
Since adjusting the CropBox doesn't rasterize the PDF, existing text generally remains searchable and selectable.
However, if the original document consists entirely of scanned images, cropping won't make the text searchable. You'll still need OCR to recognize the text.
Cropping Is Not a Substitute for Redaction
This is especially important when working with contracts, financial documents, or personal information.
Suppose you crop out a section containing a customer's bank account number. Although the number may no longer be visible in a PDF viewer, the underlying data may still exist in the file and could be recovered using other tools.
If you need to permanently remove sensitive information, use proper PDF redaction and verify that the sensitive content has actually been removed.
Rotated Pages May Require Coordinate Transformations
Not every PDF page uses the same coordinate system.
Some pages have rotation metadata, non-zero coordinate origins, or previously defined crop boundaries. The location you see in a PDF viewer may not directly correspond to the coordinates used by the underlying PDF page.
For these documents, inspect the MediaBox, existing CropBox, and page rotation before calculating a new crop rectangle. You may need to transform the coordinates to account for the page's orientation.
Final Thoughts
If you're processing PDFs in Java, adjusting the CropBox is a practical way to trim unnecessary margins without rebuilding the document or converting every page into an image.
For documents with consistent layouts, calculating the crop rectangle from each page's dimensions makes it easy to automate the process across multiple pages. When you need an image of a specific region, you can apply the crop before rendering the page.
Just remember that cropping changes what's visible, not necessarily what's stored in the PDF. That distinction becomes particularly important when dealing with sensitive documents, file size requirements, or pages with unusual coordinate systems.
Top comments (0)