I actually create a Word document with an Apache POI, and I need to automatically create a Table of Contents (TOC) that links to paragraphs with their page.
This is the code I use (I omit the premises and internal methods):
XWPFDocument doc = new XWPFDocument(OPCPackage.openOrCreate(new File(document)));
String strStyleId = "Index Style";
addCustomHeadingStyle(doc, strStyleId, 1);
XWPFParagraph documentControlHeading = doc.createParagraph();
changeText(documentControlHeading, "First try");
documentControlHeading.setAlignment(ParagraphAlignment.LEFT);
documentControlHeading.setPageBreak(true);
documentControlHeading.setStyle(strStyleId);
XWPFParagraph documentControlHeading1 = doc.createParagraph();
changeText(documentControlHeading1, "Second try");
documentControlHeading1.setAlignment(ParagraphAlignment.LEFT);
documentControlHeading1.setPageBreak(true);
documentControlHeading1.setStyle(strStyleId);
doc.createTOC();
When I open the resulting document, I get this result (see blue squares):

On the left side, I see the generated TOC. So far, so good. However, in the body of the document, I can simply see the static text "Contents" without any indication (neither paragraphs, nor pages). I can’t even interact with him.
If I click on the "Table of Contents" menu item (red square in the upper left corner), then the "real" table of contents that I want is created (follow the arrow, of course ..).
: ( TOC) ?
.
: doc.enforceUpdateFields(); doc.createTOC();, TOC , .
@Sucy, , . , , :
private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) {
CTStyle ctStyle = CTStyle.Factory.newInstance();
ctStyle.setStyleId(strStyleId);
CTString styleName = CTString.Factory.newInstance();
styleName.setVal(strStyleId);
ctStyle.setName(styleName);
CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
indentNumber.setVal(BigInteger.valueOf(headingLevel));
ctStyle.setUiPriority(indentNumber);
CTOnOff onoffnull = CTOnOff.Factory.newInstance();
ctStyle.setUnhideWhenUsed(onoffnull);
ctStyle.setQFormat(onoffnull);
CTPPr ppr = CTPPr.Factory.newInstance();
ppr.setOutlineLvl(indentNumber);
ctStyle.setPPr(ppr);
XWPFStyle style = new XWPFStyle(ctStyle);
XWPFStyles styles = docxDocument.createStyles();
style.setType(STStyleType.PARAGRAPH);
styles.addStyle(style);
}
public static void changeText(XWPFParagraph p, String newText) {
if (p != null) {
List<XWPFRun> runs = p.getRuns();
for (int i = runs.size() - 1; i >= 0; i--) {
p.removeRun(i);
}
if (runs.size() == 0) {
p.createRun();
}
XWPFRun run = runs.get(0);
run.setText(newText, 0);
}
}