It depends whether you want a complete generated TOC, or just the TOC field code (which means using Word to generate the TOC from the field code: either by pressing Ctrl-F9, or using a macro to automate that, or printing).
The TOC field code is simple enough; its just:
- Code: Select all
<w:p>
<w:r>
<w:fldChar w:fldCharType="begin"/>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> TOC \o "1-3" \h \z \u </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
If you have that (and a Styles part), Word will generate a TOC for you (I think .. I think it will create the bookmarks as well) when you tell it to update the field codes. Without a styles part, things styled H1 to H3 aren't detected as such.
But if you need Word to generate the TOC from the field code, you may as well use Word to insert the field code as well (ie don't use docx4j to do any of the TOC work). That is, unless the user will print the document, which will update the TOC automatically.
To generate a complete TOC using docx4j, you need to create the actual TOC entries. Boiled down to their bare essence, these look like:
- Code: Select all
<w:p>
<w:hyperlink w:anchor="_Toc236597049" w:history="1">
<w:r>
<w:t>TOC entry text</w:t>
</w:r>
<w:r>
<w:tab/>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin"/>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> PAGEREF _Toc236597049 \h </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:t>page #</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:hyperlink>
</w:p>
You also need to include in the document, corresponding bookmarks around each heading:
- Code: Select all
<w:p>
<w:pPr>
<w:pStyle w:val="Heading1"/>
</w:pPr>
<w:bookmarkStart w:id="1" w:name="_Toc236597049"/>
<w:r>
<w:t>H2</w:t>
</w:r>
<w:bookmarkEnd w:id="1"/>
</w:p>
Page numbers ... Word will update these before printing (if Word is so configured).
If you intend to print direct from docx4j (ie via PDF), you should consider generating the TOC only at the PDF stage (unless you need to save the intermediate Word document).
Word 2007 includes its TOC bookmarks in an SDT, but I expect the SDT can be safely omitted.