Problems with table of contents heading and insertTableOfContents method

I need to include a table of contents with the text "Table Of Contents" before it in my document.

Here's my code:

DocumentBuilder builder = new DocumentBuilder(document);

builder.moveToDocumentEnd();

builder.getParagraphFormat().setStyleName(STYLE_TOC_HEADING);

builder.write("Table Of Contents");

builder.insertTableOfContents("String");

The table of contents is only a few lines long, but it appears that the insertTableOfContents method reserves the entire page for it. When I include the "Table Of Contents" heading, another page is added so I end up with a blank page before the document body.

I'm attaching the created document.

Any suggestions?

Thanks

In your document there is a continuous section break right after TOC. Normally, if the section break is continuous, it does not cause a page break, but in your case headers/footers defined for the second section are different and it causes the page break to appear in the document. This section break does not appear as the result of the code you have given above. So please check your template or the remaining code (if any).

Also "String" that you pass as a parameter to insertTableOfContents method does not have any meaning. The parameter string should contain TOC switches, defining TOC appearance and behavior. For example,

builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");

Hope this helps,