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.

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.


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
//set the space after the paragraph

//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

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

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

//update Table of Contents

//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.