Table of Contents (TOC) in a Word document gives you an overview of the content of the document. Also, it allows you to navigate to a particular section of the document. In this article, you will learn how to work with the table of contents in Word documents programmatically. Particularly, the article covers how to add or update a table of contents in Word documents using Java.
- Java API to Work with TOC in Word Documents
- Add Table of Contents in a Word Document
- Update Table of Contents in a Word Document
Java API to Work with TOC in Word Documents
In order to work with the table of contents in Word documents, we will use Aspose.Words for Java. It is a powerful word processing API that lets you create, modify or convert Word documents. You can either download the API or install it using the following Maven configurations.
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>21.6</version>
<type>pom</type>
</dependency>
Add Table of Contents in a Word Document using Java
The following are the steps to add a table of contents to a Word document using Java.
- Create an instance of the Document class (in case of loading an existing Word document, provide the file’s path in the constructor).
- Create an instance of DocumentBuilder class and initialize it with the Document object created earlier.
- Insert table of contents using DocumentBuilder.insertTableOfContents(“\\o \”1-3\” \\h \\z \\u”) method.
- Update the fields using Document.updateFields() method.
- Save the Word document using Document.save(String) method.
The following code sample shows how to add a table of contents to a Word document.
Update TOC in a Word Document using Java
The following are the steps to update the table of contents in a Word document using Java.
- Create an instance of the Document class to load the Word document.
- Update the fields using Document.updateFields() method.
- Save the Word document using Document.save(String) method.
The following code sample shows how to update the table of contents in a Word document.
Get a Free API License
You can get a temporary license in order to use the API without evaluation limitations.
Conclusion
In this article, you have learned how to work with the table of contents in Word documents programmatically. The steps and code samples have shown how to add or update the table of contents in a Word document using Java. You can learn more about the Java word processing API using the documentation. In case you would have any questions, feel free to let us know via our forum.