Reputation: 426
I can read or write word document in Java using Apache POI or docx4j. But I cant find any references to create or update table of contents in a Word file. Is there any other API can support TOC in Java? Or, is it possible in Apache POI or docx4j to have options to create or update TOC?
Upvotes: 4
Views: 6494
Reputation: 4115
To create table of contents with apache poi you can just use:
doc.createTOC();
But it seems a bit buggy. The TOC is created but the (MS Office pro 2010) does not seem to recognize it as TOC and the references are not working.
Or you can call:
doc.enforceUpdateFields();
This will create a popup in word document with: "This document contains fields that may refer to other files. Do you want to update the fields in this document?", which looks a bit dodgy if you are opening a new doc :)
Upvotes: 2
Reputation: 21
There's a cleaner way for this too. You just need to open a empty docx which will act as a template. Add some sample text into it with the style that you want to include and then this piece of code will work.
XWPFDocument document = new XWPFDocument(new FileInputStream("template.docx");
paragraph = document.createParagraph();
lastParagraph.setStyle("Heading1");
Upvotes: 1