Extract table of contents from Microsoft Office Word documents

To extract table of contents from Microsoft Office Word document getToc method is used. Table of contents is generated by paragraphs with H1-H9 build-in styles.

Warning
getToc method returns null value if table of contents extraction isn’t supported for the document. For example, table of contents extraction isn’t supported for TXT files. Therefore, for TXT file getToc method returns null. If Microsoft Office Word document has no table of contents, getToc method returns an empty collection.

getToc method returns a collection of TocItem objects. extractText method returns a text from the chapter to which table of contents item refers (without sub-chapters). For example, “Heading 1.2” from the page

returns the following text:

“Heading 2” from the page:

returns the following text:

Warning
java.lang.UnsupportedOperationException is thrown if getPageIndex() is null.

Here are the steps to extract a text by an item of table of contents:

  • Instantiate Parser object for the initial document;
  • Call getToc method and obtain the collection of TocItem objects;
  • Iterate through the collection and extract a text.

The following example shows how to extract a text by an item of table of contents:

// Create an instance of Parser class
try (Parser parser = new Parser(Constants.SampleDocxWithToc)) {
    // Get table of contents
    Iterable<TocItem> tocItems = parser.getToc();
    // Iterate over items
    for (TocItem tocItem : tocItems) {
        // Print the text of the chapter
        try (TextReader reader = tocItem.extractText()) {
            System.out.println("----");
            System.out.println(reader.readToEnd());
        }
    }
}

More resources

GitHub examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free online document parser App

Along with full featured .NET library we provide simple, but powerful free Apps.

You are welcome to parse documents and extract data from PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX, Emails and more with our free online Free Online Document Parser App.