Change PDF Page Size in Java
Contents
[
Hide
]
Aspose.PDF for Java can both report page dimensions and update them.
Change the page size
Use this example when you need to resize an existing page and inspect the page boxes before and after the change.
- Open the source PDF Document.
- Get the target Page and print its current box values.
- Set the new page size and save the document.
public static void setPageSize(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
printBoxes("Before set", page);
page.setPageSize(597.6, 842.4);
printBoxes("After set", page);
document.save(outputFile.toString());
}
}
Get the page size
Use this example when you need to read the visible dimensions of a page.
- Open the source PDF Document.
- Get the page rectangle with rotation handling enabled.
- Output the page width and height.
public static void getPageSize(Path inputFile) {
try (Document document = new Document(inputFile.toString())) {
Rectangle rectangle = document.getPages().get_Item(1).getPageRect(true);
System.out.println(rectangle.getWidth() + " : " + rectangle.getHeight());
}
}
Get the page size with rotation applied
Use this example when you need to compare page dimensions before and after accounting for rotation.
- Open the source PDF Document.
- Rotate the target Page.
- Read the page rectangle with and without rotation handling and output both values.
public static void getPageSizeRotation(Path inputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
page.setRotate(Rotation.on90);
Rectangle rectangle = page.getPageRect(false);
System.out.println(rectangle.getWidth() + " : " + rectangle.getHeight());
rectangle = page.getPageRect(true);
System.out.println(rectangle.getWidth() + " : " + rectangle.getHeight());
}
}