Table of Content printing correctly for PDF but not for RTF

731 views Asked by At

I am working on a project where I need to create a PDF file and a RTF file, with a Table Of Content. I am doing this using MigraDoc + PdfSharp library for C#.

The code for Table of content for both the files is :

public static void DefineTableOfContents(Document document)
    {
        Section section = document.LastSection;

        section.AddPageBreak();
        Paragraph paragraph = section.AddParagraph("Table of Contents");
        paragraph.Format.Font.Size = 14;
        paragraph.Format.Font.Bold = true;
        paragraph.Format.SpaceAfter = 24;
        paragraph.Format.OutlineLevel = OutlineLevel.Level1;

        paragraph = section.AddParagraph(); 
        paragraph.Style = "TOC";
        Hyperlink hyperlink = paragraph.AddHyperlink("ParaBookmark");
        hyperlink.AddText("Paragraphs\t");
        hyperlink.AddPageRefField("ParaBookmark");

        paragraph = section.AddParagraph();
        paragraph.Style = "TOC";
        hyperlink = paragraph.AddHyperlink("AJBookmark");
        hyperlink.AddText("AJ\t");
        hyperlink.AddPageRefField("AJBookmark");

        paragraph = section.AddParagraph();
        paragraph.Style = "TOC";
        hyperlink = paragraph.AddHyperlink("TablesBookmark");
        hyperlink.AddText("Tables\t");
        hyperlink.AddPageRefField("TablesBookmark");

        paragraph = section.AddParagraph();
        paragraph.Style = "TOC";
        hyperlink = paragraph.AddHyperlink("ChartsBookmark"); 
        hyperlink.AddText("Charts\t");
        hyperlink.AddPageRefField("ChartsBookmark"); 
    }

For Pdf, the code is working fine with all the page numbers appearing properly, but for the RTF file, we get an output like :

Table of Contents
Paragraphs............................. < Please update this field. >
AJ..................................... < Please update this field. >
Tables................................. < Please update this field. >
Charts................................. < Please update this field. >

After googling I came to understand that for the RTF's page numbers to appear on the TOC, we would have to update the whole document manually in MS Word, by using ctrl+A and then F9.

Is there any programmatic way so that I could get the correct table of content with page numbers for RTF, so that we don't need to update the document manually?

1

There are 1 answers

0
I liked the old Stack Overflow On BEST ANSWER

Probably there are several ways, like VBA for Word or a Word Add-In that does it. MigraDoc cannot fill those fields.

According to this thread there is no way to have the fields being updated automatically when Word opens the RTF. So this would be an extra step between RTF file creation and sending it to the customer.