We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Change Font Formatting Name Size of Table of Content (TOC) Field Text in Word Document using Java

I generated the directory through the following code, but I cannot change the font and font size of the directory content.
the following is my code:

	builder.getCurrentParagraph().getParagraphFormat().clearFormatting();
	builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
	builder.setBold(false);
	builder.getFont().setName("Times New Roman");
	builder.writeln("Contents");
	builder.getFont().setSize(10d);

	// 清清除所有样式设置
	// builder.getParagraphFormat().clearFormatting();
	// 目录居左
	builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
	builder.getFont().setSize(10d);
	builder.setBold(false);
	builder.insertTableOfContents("\\o \"1-3</span>\" \\h \\z \\u");
	builder.insertBreak(BreakType.PAGE_BREAK);
	doc.updateFields();

contents.png (41.5 KB)

I want to set the font to “Times New Roman” and the font size to 10, but it is still the default font and size

@guanvo,

Please ZIP and upload Aspose.Words generated DOCX file showing the undesired behavior here for testing. We will then investigate the scenario on our end and provide you Java code to change font name and font size of Table of Content (TOC) field.

Epure International.zip (318.0 KB)
I want to set the font of Table of Content (TOC) field to “Times New Roman” and the font size to 10, but it is still the default font and size

@guanvo,

The following Java code will change the Font formatting of Table of Content (TOC) field Text in Word document.

Document doc = new Document("E:\\Temp\\Epure International\\Epure International.doc");

for (FieldStart field : (Iterable<FieldStart>) doc.getChildNodes(NodeType.FIELD_START, true)) {
    if (field.getFieldType() == (FieldType.FIELD_HYPERLINK)) {
        FieldHyperlink hyperlink = (FieldHyperlink) field.getField();
        if (hyperlink.getSubAddress() != null && hyperlink.getSubAddress().startsWith("_Toc")) {
            Paragraph tocItem = (Paragraph) field.getAncestor(NodeType.PARAGRAPH);
            if (tocItem != null) {
                tocItem.getParagraphBreakFont().setName("Times New Roman");
                tocItem.getParagraphBreakFont().setSize(10);
                for (Run run : (Iterable<Run>) tocItem.getChildNodes(NodeType.RUN, true)) {
                    run.getFont().setName("Times New Roman");
                    run.getFont().setSize(10);
                }
            }
        }
    }
}

doc.save("E:\\Temp\\Epure International\\awjava-20.7.docx");