How to Add Sections, Headers and Footers to a Word Document in Java
Aspose.Words FOSS for Java splits a Word document into sections with DocumentBuilder.insertBreak and writes a header and a footer for each section with moveToHeaderFooter. This guide builds a two-section document with different headers and reads them back after saving, 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: Insert the Section Breaks
Call insertBreak(BreakType.SECTION_BREAK_NEW_PAGE) or insertBreak(BreakType.SECTION_BREAK_CONTINUOUS) where a section ends. After saving and reloading, the example printed 3 sections; the sections that followed the two breaks read back as new page and continuous.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Introduction");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.writeln("Main part");
builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
builder.writeln("Appendix");
doc.save("sections.docx");
Document reloaded = new Document("sections.docx");
SectionCollection sections = reloaded.getSections();
System.out.println("Sections: " + sections.getCount());
for (int i = 0; i < sections.getCount(); i++) {
Section section = sections.get(i);
boolean continuous = section.getPageSetup().getSectionStart() == SectionStart.CONTINUOUS;
System.out.println("Section " + (i + 1) + ": " + (continuous ? "continuous" : "new page")
+ ", text: " + section.getBody().getText().trim());
}The program printed:
Sections: 3
Section 1: new page, text: Introduction
Section 2: new page, text: Main part
Section 3: continuous, text: AppendixStep 4: Write a Header and a Footer for Each Section
Call moveToSection for the section, then moveToHeaderFooter with a HeaderFooterType constant such as HEADER_PRIMARY, FOOTER_PRIMARY or HEADER_FIRST, then write. A PAGE field can be added to a footer with insertField.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Chapter 1");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.writeln("Chapter 2");
builder.moveToSection(0);
builder.getPageSetup().setDifferentFirstPageHeaderFooter(true);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST);
builder.write("Annual report");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Annual report - chapter 1");
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.write("Page ");
builder.insertField("PAGE", "");
builder.moveToSection(1);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Annual report - chapter 2");
doc.save("report.docx");
Document reloaded = new Document("report.docx");
int[] types = {HeaderFooterType.HEADER_FIRST, HeaderFooterType.HEADER_PRIMARY, HeaderFooterType.FOOTER_PRIMARY};
String[] names = {"first-page header", "header", "footer"};
for (int s = 0; s < reloaded.getSections().getCount(); s++) {
Section section = reloaded.getSections().get(s);
System.out.println("Section " + (s + 1) + ": different first page = "
+ section.getPageSetup().getDifferentFirstPageHeaderFooter());
for (int t = 0; t < types.length; t++) {
HeaderFooter part = section.getHeadersFooters().getByHeaderFooterType(types[t]);
if (part == null) {
System.out.println(" " + names[t] + ": none");
} else {
System.out.println(" " + names[t] + ": " + part.getText().trim() + " (fields: " + part.getRange().getFields().getCount() + ")");
}
}
}The program printed:
Section 1: different first page = true
first-page header: Annual report (fields: 0)
header: Annual report - chapter 1 (fields: 0)
footer: Page PAGE (fields: 1)
Section 2: different first page = false
first-page header: none
header: Annual report - chapter 2 (fields: 0)
footer: noneStep 5: Read Them Back After Reloading
section.getHeadersFooters().getByHeaderFooterType(type) returns the part or null. In the example the first section had 3 parts, the second section only its own header, and the footer of the second section read back as null. The footer with the field printed as Page PAGE.
Common Issues and Fixes
getByHeaderFooterType returns null. The section has no header or footer of that type in the saved file. In a test on Java 8, 17 and 21 a section in which moveToHeaderFooter was never called had none. Test for null, or write the part for that section.
moveToHeaderFooter throws IllegalStateException: Unknown header or footer type. The value is not one of the HeaderFooterType constants (the test passed 99).
The new header of a later section is empty. moveToHeaderFooter creates an empty header in that section. Write the text you want, or call isLinkedToPrevious(true) on it to link it to the previous section.
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
Does a page break create a section?
No. A document with BreakType.PAGE_BREAK had 1 section in a test on Java 8, 17 and 21.
How do I make a section start on a new page?
Call getPageSetup().setSectionStart(SectionStart.NEW_PAGE) on the section, as the Sections guide shows.