Sunday, 27 March 2022

Change the Page Size and Page Orientation of a Word Document in Java

Most pages of Word documents are standard paper-size, but you can change the paper size or the page orientation (portrait or landscape) at any time to make the document look the way you want. This article will show you how to programmatically change the page size and page orientation of a Word document using Java codes.

DEPENDENCY

First of all, you need to download the package of a free third-party library called FreeSpire.Doc for Java from this link, and then add Spire.Doc.jar to your Java program. Or if you use Maven, just type the following code in the pom.xml file to easily import the JAR file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>

USING THE CODE

 Free Spire.Doc for Java supports changing the default page size using the Section.getPageSetup().setPageSize() method and the default page orientation using Section.getPageSetup().setOrientation() method. Detailed steps are as follows.

l  Create a Document instance.

l  Load a Word sample document using Document.loadFromFile() method.

l  Get the first section of the document using Document.getSections().get() method.

l  Change the default page size using Section.getPageSetup().setPageSize() method.

l  Change the default page orientation using Section.getPageSetup().setOrientation() method.

l  Save the document to another file using Document.saveToFile() method.

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class WordPageSetup {
public static void main(String[] args) {
//Create a Document instance
Document doc= new Document();

//Load a Word sample document
doc.loadFromFile("sample.docx");

//Get the first section
Section section = doc.getSections().get(0);

//Change the page size to A3
section.getPageSetup().setPageSize(PageSize.A3);

//Change the page orientation to Landscape
section.getPageSetup().setOrientation(PageOrientation.Landscape);

//Save the document to another file
doc.saveToFile("output/PageSetup.docx",FileFormat.Docx_2013);
}
}



No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...