Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Mon Mar 11, 2019 10:29 am

Hello,

How to set table of content (TOC) text font as bold & italic.


regards,
Rakesh

test@zerozone.com
 
Posts: 4
Joined: Thu Oct 11, 2018 9:26 am

Tue Mar 12, 2019 6:02 am

Hello,

Thanks for your post and there are two scenarios for your reference.
1. If you want to set TOC text font as bold & italic when creating a Word document, you could refer to the following sample code.
Code: Select all
Document doc = new Document();
Section section = doc.AddSection();
//create a paragrah for adding TOC
Paragraph para = section.AddParagraph();
TableOfContent toc = para.AppendTOC(1, 2);
Paragraph para1 = section.AddParagraph();
para1.AppendText("Heading1");
para1.ApplyStyle(BuiltinStyle.Heading1);
Paragraph para2 = section.AddParagraph();
para2.AppendText("Heading2");
para2.ApplyStyle(BuiltinStyle.Heading1);
doc.UpdateTableOfContents();
//create a style
ParagraphStyle style = new ParagraphStyle(doc);
style.Name = "MyStyle";
style.CharacterFormat.Bold = true;
style.CharacterFormat.Italic = true;
doc.Styles.Add(style);
//apply the style for heading1
section.Paragraphs[0].ApplyStyle("MyStyle");
//apply the style for heading2
section.Paragraphs[1].ApplyStyle("MyStyle");
doc.SaveToFile("CreatedTocFile.docx", Spire.Doc.FileFormat.Docx);

2. If you want to set this for an existing Word document that already contains TOC, you could refer to the following sample code.
Code: Select all
Document doc = new Document(@"TOCsample.docx");
foreach (Section section in doc.Sections)
{
    foreach (DocumentObject obj in section.Body.ChildObjects)
    {
        FieldCollection field = doc.Fields;
        foreach (Field fd in field)
        {
            if (obj.ChildObjects.Contains(fd))
            {
                Paragraph para = obj as Paragraph;
                foreach (TextRange textRange in para.ChildObjects.OfType<TextRange>())
                {
                    //set text font of TOC paragraph
                    textRange.CharacterFormat.Italic = true;
                    textRange.CharacterFormat.Bold = true;
                }
            }
        }
    }
}
doc.SaveToFile("res2.docx", Spire.Doc.FileFormat.Docx2013);

If there is any question, please tell us your scenario and provide your Word document (if any) to help us do a further investigation. You could send them to us via email (support@e-iceblue.com).

Sincerely,
Lisa
E-iceblue support team
User avatar

Lisa.Li
 
Posts: 1261
Joined: Wed Apr 25, 2018 3:20 am

Thu Mar 14, 2019 9:00 am

Hello,

Greetings from E-iceblue.
Did my code help you? Thanks in advance for your feedback and time.

Sincerely,
Lisa
E-iceblue support team
User avatar

Lisa.Li
 
Posts: 1261
Joined: Wed Apr 25, 2018 3:20 am

Return to Spire.Doc