Update Table option in MS Word is removing the TOC styling set by Aspose

Hello Team,

We have been using Aspose Words Java to create our documents. However, we have noticed that when we use the “Update Table” option in MS Word, it removes the Table of Contents styling set by Aspose.

As shown in the image below, the styling is correct before the “Update Table” option is used.

However, after deleting Section 2 and updating the table of contents using the “Update Table” option, the styling is removed.

Input Document:

Table of Contents.docx (16.0 KB)

Output Document:

Aspose Output.docx (20.8 KB)

Code:
AsposeTable.zip (914 Bytes)

@Yashwanth14 In your code you update dirrect fotmatting of runs in the TOC. But TOC items formatting in MS Word is defined in the built-in TOC1…TOCN styles. So after updating TOC, the explicitly set formatting is overridden by the styles. You should simply change formatting of the certain TOC styles in your code. For example:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Modify TOC styles.
doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_1).getFont().setBold(true);

doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_2).getFont().setColor(Color.RED);

doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_3).getFont().setColor(Color.GREEN);
doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_3).getFont().setItalic(true);

// Put some dummy TOC
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");
builder.writeln();
builder.insertBreak(BreakType.PAGE_BREAK);
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.writeln("Heading 1 will be shown as bold in the TOC");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
builder.writeln("Heading 2 will be red in the TOC");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3);
builder.writeln("Heading 3 will be green and italic in the TOC");

doc.updateFields();
doc.updatePageLayout();

doc.save("C:\\Temp\\out.docx");

How to identify and target these items style identifier?

Is this the correct way? I don’t understand why its style name is coming as TOC 2 instead of TOC_2?

@Yashwanth14 You d not need to get the field and change it. You should simply change the styles and update TOC field. Just like shown in the code example above.

@alexey.noskov Thanks a lot! It is working now. How can I set the line spacing?

@Yashwanth14 The same way as the font. Please see the following code:

doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_1).getParagraphFormat().setLineSpacing(16);

Got it, thanks!

1 Like