Table of Contents (TOC) in a Word document gives you an overview of the content of the document. Very often, it is considered a necessary part of the documents. While generating Word documents programmatically, you may need to manipulate the table of contents, i.e. add or update TOC. For such cases, this article provides an easy, high-quality, and high-speed method to create and manipulate table of contents in Word documents in Java.
- Java API to Create and Update Table of Contents in Word Documents
- Add Table of Contents in a Word Document in Java
- Update Table of Contents in a Word Document in Java
Java API to Create Table of Contents in Word Documents
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>
Create Table of Contents in a Word Document in Java
The following are the steps to create a table of contents in 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 create a table of contents in a Word document in Java.
Java: Update Table of Contents in a Word Document
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.
Create MS Word Table of Contents with Free License
You can get a free temporary license to create and manipulate table of contents in Word documents 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 in 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.