Generating a navigable table of contents is essential when creating large Word reports or manuals that users need to skim quickly. Conholdate.Total for Java provides a robust SDK that simplifies working with DOCX files directly from Java applications. In this step‑by‑step guide you will learn how to add a table of contents to a Word document in Java, covering setup, code explanation, and best practices.
Full Working Example for Adding Table of Contents to Word Document in Java
The following example demonstrates how to insert a table of contents into a DOCX file using Conholdate.Total for Java.
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.StyleIdentifier;
public class AddTableOfContentsExample {
public static void main(String[] args) throws Exception {
// Directory where the output document will be saved
String dataDir = "output/";
// Create a new document and a builder to work with it
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents field at the current cursor position.
// "\o \"1-3\" \h \z \u" includes heading levels 1-3, makes entries
// clickable hyperlinks, hides tab leaders in Web layout, and uses
// outline levels applied to non-heading styles.
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.insertBreak(BreakType.PAGE_BREAK);
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.writeln("Heading 1");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
builder.writeln("Heading 1.1");
builder.writeln("Heading 1.2");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.writeln("Heading 2");
builder.writeln("Heading 3");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
builder.writeln("Heading 3.1");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3);
builder.writeln("Heading 3.1.1");
builder.writeln("Heading 3.1.2");
builder.writeln("Heading 3.1.3");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
builder.writeln("Heading 3.2");
builder.writeln("Heading 3.3");
// The newly inserted table of contents is initially empty.
// It needs to be populated by updating the fields in the document.
doc.updateFields();
doc.save(dataDir + "TableOfContents.docx");
}
}
Note: This code example demonstrates the core functionality. Before using it in your project, make sure to update the output directory (
dataDir) to match your actual file location, verify that all required dependencies are properly installed, and test thoroughly in your development environment. If you encounter any issues, please refer to the official documentation or reach out to the support team for assistance.
Understanding the Add Table of Contents to Word Document in Java Code
Below is a breakdown of the main steps performed by the sample code:
Create the document and a builder -
Documentrepresents the in-memory Word file, andDocumentBuildergives you methods to insert content and fields into it.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc);Insert the TOC field -
insertTableOfContentswrites a TOC field at the cursor position. The switch string controls its behavior:\o "1-3"includes heading levels 1 to 3,\hmakes entries clickable hyperlinks,\zhides tab leaders and page numbers in Web layout view, and\uuses the outline level applied to paragraphs.builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");Start content on a new page -
insertBreak(BreakType.PAGE_BREAK)pushes the actual document body onto the page after the TOC, so the table of contents has its own page.builder.insertBreak(BreakType.PAGE_BREAK);Add heading-styled content - Setting
setStyleIdentifieron the builder’s paragraph format toHEADING_1,HEADING_2, orHEADING_3before callingwritelnproduces paragraphs styled with the corresponding built-in heading style, which the TOC field scans for entries.builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1); builder.writeln("Heading 1");Detailed API reference is available at the API Reference page.
Update fields and save -
doc.updateFields()populates the TOC with entries and page numbers now that the headings exist, anddoc.savewrites the document to disk.doc.updateFields(); doc.save(dataDir + "TableOfContents.docx");
Installing and Configuring Conholdate.Total for Java
Add the Conholdate Maven repository and the SDK dependency to your pom.xml:
<repositories>
<repository>
<id>conholdate-repo</id>
<name>Conholdate Maven Repository</name>
<url>https://repository.conholdate.com/repo/</url>
</repository>
</repositories>
<dependency>
<groupId>com.conholdate</groupId>
<artifactId>conholdate-total</artifactId>
<version>24.9</version>
<type>pom</type>
</dependency>
Download the latest SDK package from the download page. The SDK requires Java 8 or higher and runs on any standard JVM. No additional runtime components are needed.
Best Practices for Generating Word TOC with Java
- Use consistent heading styles - The TOC picks up paragraphs styled with built‑in heading levels (Heading 1, Heading 2, etc.). Ensure your source document uses these styles for reliable entry generation.
- Limit heading depth - Including too many levels can make the TOC unwieldy. Typical reports use levels 1‑3, as shown in the example’s
\o "1-3"switch. - Enable hyperlinks - Including the
\hswitch creates clickable entries, improving navigation in the final document. - Always call updateFields after insertion - A newly inserted TOC field is empty until
doc.updateFields()runs, so call it after all heading content has been added. - Validate after insertion - Open the generated DOCX and update fields (Ctrl +A, F9) to confirm page numbers are correct, especially after further edits.
- Reuse the switch string - If you generate multiple documents in a batch, build the switch string once and reuse it across calls to keep formatting consistent.
Conclusion
Adding a table of contents to a Word document in Java becomes straightforward with Conholdate.Total for Java. By creating a document, inserting a TOC field with the appropriate switches, adding heading-styled content, and calling updateFields, you can automate the creation of professional reports and manuals. Remember to install the SDK, follow the best‑practice recommendations, and test the generated TOC in your target environment. For production deployments you’ll need a licensed copy; pricing details are available on the pricing page and a temporary license can be obtained from the temporary license page.
FAQs
What is the simplest way to add a table of contents to a Word document in Java? Call
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"), add heading-styled paragraphs, then calldoc.updateFields()before saving, as demonstrated in the code example.How can I control which heading levels appear in the TOC? Change the level range inside the
\oswitch of the string passed toinsertTableOfContents, for example\o "1-2"to include only levels 1 and 2.Is it possible to generate a TOC for a Word template that will be filled later? Yes. Insert the TOC field into the template file before populating dynamic content; calling
updateFields()after the headings are added will populate the TOC automatically.Do I need an internet connection to use this SDK? No. Conholdate.Total for Java is a local library that runs on your server or desktop without any external service calls.
