Sections, Headers and Footers

Sections, Headers and Footers

Overview

This guide shows how to split a Word document into sections with section breaks, edit or remove a section, and write a separate header and footer for each section in Java with Aspose.Words FOSS for Java. A Word document is made of one or more sections, and each section has its own body and its own headers and footers. DocumentBuilder.insertBreak with a section break type from BreakType ends the current section and starts a new one, Document.getSections returns the SectionCollection, and DocumentBuilder.moveToHeaderFooter takes a HeaderFooterType and moves the cursor into the header or footer of the current section, where write adds the text. This page inserts section breaks and reads the sections back, edits and removes a section, and writes a different header and footer for each section. The examples were compiled and run against the published package on Java 8, 17 and 21 and printed the same output on all three. This edition does no page layout, so the examples report what the saved file stores, not how pages look. The page size and margins of each section are covered in the Page Setup guide.


Prerequisites

RequirementDetail
Java8 or later
DependencyThe package from Installation
Importimport com.aspose.words.*;
CodeThe examples are statements. Put them in a method that declares throws Exception.

Insert Section Breaks and Read the Sections

Write text with a DocumentBuilder and call insertBreak(BreakType.SECTION_BREAK_NEW_PAGE) or insertBreak(BreakType.SECTION_BREAK_CONTINUOUS) where a section ends. The example saves the document, reloads it and prints the sections. It found 3 sections. The type of the break is read back as getPageSetup().getSectionStart() of the section that follows the break: the second section, created by the new-page break, printed as new page and the third, created by the continuous break, printed as continuous. The first section printed as new page. insertBreak(BreakType.PAGE_BREAK) does not add a section: in a test on Java 8, 17 and 21 a document with one page break still had 1 section.

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: Appendix

Edit and Remove Sections

moveToSection moves the cursor to the beginning of the body of the section with the given index, so the next writeln writes at the start of that section. PageSetup.setSectionStart changes how a section starts, and remove on a section from getSections().get(index) takes it out of the document. The example writes a title page line into the first section, makes the third section start on a new page, removes the second and saves. After reloading it printed 2 sections: the first with the text Title page | Introduction and the second, Appendix, starting on a new page.

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("Draft notes");
builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
builder.writeln("Appendix");

// Write at the start of the first section.
builder.moveToSection(0);
builder.writeln("Title page");

// Make the last section start on a new page, then remove the second section.
doc.getSections().get(2).getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
doc.getSections().get(1).remove();
doc.save("edited.docx");

Document reloaded = new Document("edited.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 newPage = section.getPageSetup().getSectionStart() == SectionStart.NEW_PAGE;
    System.out.println("Section " + (i + 1) + ": starts on a new page = " + newPage
            + ", text: " + section.getBody().getText().trim().replace("\r", " | "));
}

The program printed:

Sections: 2
Section 1: starts on a new page = true, text: Title page | Introduction
Section 2: starts on a new page = true, text: Appendix

Write a Header and a Footer for Each Section

moveToSection first, then moveToHeaderFooter with HeaderFooterType.HEADER_PRIMARY, HeaderFooterType.FOOTER_PRIMARY or HeaderFooterType.HEADER_FIRST, then write. The example gives the first section a different first page (getPageSetup().setDifferentFirstPageHeaderFooter(true)), a first-page header, a primary header and a footer with a PAGE field inserted by insertField, and gives the second section its own primary header. After reloading, getHeadersFooters().getByHeaderFooterType returned the first section’s three parts and the second section’s header, and it returned null for the second section’s footer and first-page header, which were never written. The footer text printed as Page PAGE: in the test the text of a footer holds the instruction of the field, and the saved footer part contains a field with the instruction PAGE. The second section printed none for its footer and for its first-page header: the saved file has no header or footer reference for a part that was not written.

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: none

Tips and Best Practices

  • Call moveToSection before moveToHeaderFooter: the header or footer is that of the current section, so without it the text goes to the section the cursor is in.
  • Choose the break type for the section that follows the break, and check it afterwards with getPageSetup().getSectionStart(); SectionStart has CONTINUOUS, NEW_COLUMN, NEW_PAGE, EVEN_PAGE and ODD_PAGE.
  • Pass the HeaderFooterType constants and test the result of getByHeaderFooterType for null before you read its text.

Common Issues

IssueCauseFix
The compiler reports cannot find symbol for Document.The com.aspose.words package is not imported.Add import com.aspose.words.*;.
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.
getSections().get(index) returns null.The index is past the last section. In a test on Java 8, 17 and 21 get(5) on a document with 2 sections returned null and did not throw.Compare the index with getSections().getCount(), and test the result for null. A negative index did not return null in the test: get(-1) on a document with 2 sections returned the last section.
getByHeaderFooterType returns null for a section after reloading.The section has no header or footer of that type in the saved file. A part exists only for sections in which it was written; in a test the saved file had no header reference for a section where moveToHeaderFooter was never called.Test for null, or call moveToSection and moveToHeaderFooter for that section and write the text.
A header is empty after moveToHeaderFooter in a later section.moveToHeaderFooter creates an empty header for that section. In a test the new header was not linked to the previous one (isLinkedToPrevious returned false) and its text was empty.Write the text you want, or call isLinkedToPrevious(true) on the part to link it to the previous section: in a test the saved file then had no header reference for that section.
moveToHeaderFooter throws IllegalStateException with the message Unknown header or footer type.The value passed is not one of the HeaderFooterType constants (the test passed 99).Pass a constant such as HeaderFooterType.HEADER_PRIMARY.

FAQ

How do I count the sections of a document?

Document.getSections returns a SectionCollection; its getCount returned 3 for the document in the first example.

Does a page break start a new section?

No. In a test on Java 8, 17 and 21 a document with BreakType.PAGE_BREAK had 1 section; only the section break types add a section.

How do I use a different header on the first page?

Call getPageSetup().setDifferentFirstPageHeaderFooter(true) on the section and write the first-page header with HeaderFooterType.HEADER_FIRST. After a save and reload getDifferentFirstPageHeaderFooter returned true for that section and the first-page header read back.

Can each section have its own page size and margins?

Each section has its own PageSetup (Section.getPageSetup); the Page Setup guide shows the orientation, paper size and margins.


API Reference Summary

Class / MethodDescription
SectionRepresents a single section in a document.
SectionCollectionA collection of Section objects in the document.
Document.getSections()Returns a collection that represents all sections in the document.
HeaderFooterRepresents a container for the header or footer text of a section.
HeaderFooterCollectionProvides typed access to HeaderFooter nodes of a Section.
HeaderFooterTypeIdentifies the type of header or footer found in a Word file.
DocumentBuilder.moveToHeaderFooter(type)Moves the cursor to the beginning of a header or footer in the current section.
DocumentBuilder.moveToSection(index)Moves the cursor to the beginning of the body in a specified section.
BreakTypeSpecifies type of a break inside a document.
DocumentBuilder.insertBreak(type)Inserts a break of the specified type into the document.
SectionStartThe type of break at the beginning of the section.
HeaderFooter.isLinkedToPrevious()True if this header or footer is linked to the corresponding header or footer in the previous section.

Related Guides

See Also