Create Table of Contents in Word Using Java

Andrew Wilson
2 min readAug 30, 2021

--

The table of contents is usually an indispensable part of a long document. It enables readers to understand what is in the document and how to find the specific content easily. In this article, I will introduce how to create table of contents in a Word document programmatically using Free Spire.Doc for Java.

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

Method 2: Directly 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>

The following example shows how to create a table of contents with default appearance that includes all text formatted with built-in styles Heading 1, Heading 2, Heading 3, and page numbers right-aligned with tab leaders.

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

import java.awt.*;

public class TableofContents {
public static void main(String[] args){
//instantiate a Document object
Document doc = new Document();
//add a section
Section section = doc.addSection();

//add a paragraph
Paragraph para = section.addParagraph();
TextRange tr = para.appendText("Table of Contents");
//set font size and text color
tr.getCharacterFormat().setFontSize(11);
tr.getCharacterFormat().setTextColor(Color.blue);
//set the space after the paragraph
para.getFormat().setAfterSpacing(10);

//add a paragraph
para = section.addParagraph();
//add a table of contents with default appearance by specifying lower heading level and upper heading level. The heading level range must be from 1 to 9.
para.appendTOC(1, 3);

//add a new section
section = doc.addSection();
//add a paragraph
para = section.addParagraph();
para.appendText("Heading 1");
//apply Heading 1 style to the paragraph
para.applyStyle(BuiltinStyle.Heading_1);
section.addParagraph();

//add a paragraph
para = section.addParagraph();
para.appendText("Heading 2");
//apply Heading 2 style to the paragraph
para.applyStyle(BuiltinStyle.Heading_2);
section.addParagraph();

//add a paragraph
para = section.addParagraph();
para.appendText("Heading 3");
//apply Heading 3 style to the paragraph
para.applyStyle(BuiltinStyle.Heading_3);
section.addParagraph();

//update Table of Contents
doc.updateTableOfContents();

//save the resultant document
doc.saveToFile("createTableOfContents.docx", FileFormat.Docx);
}
}

--

--

Andrew Wilson

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