News Category

Java: Change Page Size and Page Orientation in Word

2022-01-28 06:42:00 Written by  support iceblue
Rate this item
(3 votes)

Normally, the default page size of a Word document is “Letter” (8.5 x 11 inches), and the default page orientation is “Portrait”. In most cases, the general page setup can meet the needs of most users, but sometimes you may also need to adjust the page size and orientation to design a different document such as an application form, certificate, or brochure. In this article, you will learn how to programmatically change the page size and page orientation in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml 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</artifactId>
        <version>12.4.6</version>
    </dependency>
</dependencies>
    

Change Page Size and Page Orientation in Word

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Change the default page size using Section.getPageSetup().setPageSize() method.
  • Change the default page orientation using Section.getPageSetup().setOrientation() method.
  • Save the document to file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;

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

        //Load a sample Word 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 file
        doc.saveToFile("Result.docx",FileFormat.Docx_2013);
    }
}

Java: Change Page Size and Page Orientation in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Monday, 12 June 2023 02:18