Exclude heading from TOC

I’m trying to exclude certain headings from the “table of content”.

Since I did not find another way, I’m trying to set a different style on the paragraph (“Heading 1 no_index”).

Style heading1 = contentDocument.getStyles().get(StyleIdentifier.HEADING_1);
Style noIndex = contentDocument.getStyles().addCopy(heading1);
noIndex.setName("Heading 1 no_index");
System.out.println("Heading 1: " + heading1.isHeading() + " " + heading1.getStyleIdentifier());
System.out.println("Heading 1 no_index: " + noIndex.isHeading() + " " + noIndex.getStyleIdentifier());

This outputs the following (so the new style is no heading anymore):
Heading 1: true 1
Heading 1 no_index: false 4094
On the actual heading paragraph I do the following:

ParagraphFormat paragraphFormat = paragraph.getParagraphFormat();
Style noIndex = parent.getDocument().getStyles().get("Heading 1 no_index");
paragraphFormat.setStyle(noIndex);

In the end the heading is still listed in the “table of content”.
How can I accomplish, keeping the formatting but not listing the title in the TOC?

Hi Peter,

Thanks for your inquiry. Could you please attach your input and expected output Word documents here for our reference? We will then provide you more information on this along with code.

Attached is the input (two entries in the TOC) and the output (one entry in the TOC).

Hi Peter,

Thanks for sharing the detail. Please use following code example to achieve your requirements. Hope this helps you.

Document doc = new Document(MyDir + "input.docx");

Style heading = doc.getStyles().getByStyleIdentifier(StyleIdentifier.HEADING_1);

// Create a paragraph style and specify some formatting for it.
Style style = doc.getStyles().add(StyleType.PARAGRAPH, "MyStyle1");
style.getFont().setSize(heading.getFont().getSize());
style.getFont().setName(heading.getFont().getName());
style.getFont().setColor(heading.getFont().getColor());

Paragraph para = (Paragraph)doc.getFirstSection().getBody().getLastParagraph().getPreviousSibling();
para.getParagraphFormat().setStyle(style);

doc.updateFields();
doc.save(MyDir + "Out v16.7.0.docx");