Create Table of Contents in Word Using Java

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);




Sharing Java Code

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Thinking about a career in Software Engineering?

Google Summer of Code 2021: Sympy (Week-1)

Build an App Without Writing a Single Line of Code

Reflection 04: Problems

My Android Diary

Bullying and Coding “ Tech Ed 4 Kids

Stateful Application as a Service

Creating your first gRPC .NET Core Client and Server App using Visual Studio or Visual Studio Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andrew Wilson

Andrew Wilson

Sharing Java Code

More from Medium

Spring Annotations — 1 — @Autowired, @Qualifier

Basic concepts of OOP!

OOP Pillars

Inheritance In Java -10 Program