In a Word document, we can use page break to split a page into two pages, and can also use section break to start a new section. This article will demonstrate how to insert page break and section break into a Word document using Java codes.
Of course, it’s necessary to use a free third-party library called Free Spire.Doc for Java for finishing the operation above. You can download it from the E-iceblue official website or directly refer to the Jar file in the library by using the following Maven configurations.
<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>
Using the code
Insert
Page Break
Free
Spire.Doc for Java provides the appendBreak method to insert page
break into a Word document. Now I use the following codes to add page break to
the paragraph 8 of a Word sample document.
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class InsertPageBreak {
public static void main(String[] args) {
//load Word document
Document document = new Document();
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");
//get the first section
Section section = document.getSections().get(0);
//add page break to paragraph 8
Paragraph paragraph = section.getParagraphs().get(7);
paragraph.appendBreak(BreakType.Page_Break);
//save the resulting document
document.saveToFile("output/AddPageBreak.docx", FileFormat.Docx_2013);
}
}
Output
Insert Section Break
The following codes show how to insert section break to the paragraph 8 of a Word sample document by using the insertSectionBreak
method provided by Free Spire.Doc for Java.
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class InsertSectionBreak {
public static void main(String[] args) {
//load Word document
Document document = new Document();
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");
//get the first section
Section section = document.getSections().get(0);
//add a section break to paragraph 8 and start the new section on the next page
Paragraph paragraph = section.getParagraphs().get(7);
paragraph.insertSectionBreak(SectionBreakType.New_Page);
//save the resultant document
document.saveToFile("output/AddSectionBreak.docx", FileFormat.Docx_2013);
}
}Output
No comments:
Post a Comment