How to Set Page Size, Orientation and Margins in a Word Document in Java
Aspose.Words FOSS for Java sets the page size, orientation and margins of a Word document through the PageSetup of a section. This guide makes the first section landscape A4 with 54 point side margins and reads the values back, with the library from Maven Central.
Step-by-Step Guide
Step 1: Install the Package
Add the package to your build. The library needs Java 8 or later.
<dependency>
<groupId>org.aspose</groupId>
<artifactId>aspose-words-foss</artifactId>
<version>26.3.0</version>
</dependency>Step 2: Import the Classes
All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.
Step 3: Get the Page Setup
doc.getFirstSection().getPageSetup() returns the PageSetup of the first section.
Step 4: Set and Save
Call setOrientation(Orientation.LANDSCAPE), setPaperSize(PaperSize.A4), setLeftMargin and setRightMargin, then save the document.
import com.aspose.words.*;
Document doc = new Document();
new DocumentBuilder(doc).writeln("Landscape page");
Section section = doc.getFirstSection();
PageSetup pageSetup = section.getPageSetup();
pageSetup.setOrientation(Orientation.LANDSCAPE);
pageSetup.setPaperSize(PaperSize.A4);
pageSetup.setLeftMargin(54); // points
pageSetup.setRightMargin(54);
doc.save("landscape.docx");
Document reloaded = new Document("landscape.docx");
Section savedSection = reloaded.getFirstSection();
PageSetup saved = savedSection.getPageSetup();
System.out.println("Landscape: " + (saved.getOrientation() == Orientation.LANDSCAPE));
System.out.println("Width x height (points): " + Math.round(saved.getPageWidth()) + " x " + Math.round(saved.getPageHeight()));
System.out.println("Left margin: " + saved.getLeftMargin());The program printed:
Landscape: true
Width x height (points): 842 x 595
Left margin: 54.0Step 5: Read the Values Back
The reloaded document printed Landscape: true, 842 x 595 points and a left margin of 54.0.
Common Issues and Fixes
The values read back differ from what I expected. Lengths are in points. A4 landscape is 842 by 595 points, as printed by the example.
The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.
Frequently Asked Questions
Can I get the number of pages?
No. Document has no page count method in this edition.
Is the setup per document or per section?
Per section: Section.getPageSetup returns the setup of that section.