[Java] Insert Page Break and Section Break in Word Document

Andrew Wilson
2 min readJun 2, 2021

In a Word document, we can use page break to split a page into two pages or use section break to start a new section. This article will demonstrate how to insert page break and section break programatically using Free Spire.Doc for Java.

Installation
Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

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

A screeshot of the input Word document:

Insert page break

The following sample code shows how to insert page break to a Word document by using the appendBreak method in Paragraph class.

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

public class PageBreak {
public static void main(String[] args){
//load Word document
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Moon.docx");

//get the first section
Section section = document.getSections().get(0);
//add page break to paragraph 4
Paragraph paragraph = section.getParagraphs().get(3);
paragraph.appendBreak(BreakType.Page_Break);

//save the document
document.saveToFile("AddPageBreak.docx", FileFormat.Docx_2013);
}
}

Insert Section break

The following sample code shows how to insert section break to a Word document by using the insertSectionBreak method in Paragraph class.

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

public class SectionBreak {
public static void main(String[] args){
//load Word document
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Moon.docx");

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

//add a section break to paragraph 4 and start the new section on the next page
Paragraph paragraph = section.getParagraphs().get(3);
paragraph.insertSectionBreak(SectionBreakType.New_Page);

//save the document
document.saveToFile("AddSectionBreak.docx", FileFormat.Docx_2013);
}
}

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.