After the mail merge Table of contents is broken in word document

In my word document I have added the table of contents. During the mail merge I am replacing the some tags data after that I am expecting that table of content will get auto adjusted but it is not doing it. But instead it is breaking it with the below error.

In the code I am already calling the below two lines of code.

doc.UpdateFields();
doc.UpdatePageLayout();

My aspose version is – 25.9.0.0.
Can you please advise how to fix this issue?

@srinicasepoint

It appears that after performing a mail merge in your Word document, the Table of Contents (TOC) is not updating correctly. The methods you are using, doc.UpdateFields(); and doc.UpdatePageLayout();, are appropriate for refreshing the document after changes.

If the TOC is still not functioning as expected, consider the following troubleshooting steps:

  1. Verify Tag Replacement: Ensure that the tags you are replacing during the mail merge are correctly formatted and do not disrupt the document’s structure.

  2. Rebuild the TOC: After updating the fields, you may need to manually rebuild the TOC in the Word document. Check that the TOC is set to update automatically or perform a manual update.

  3. Inspect for Document Errors: Hidden formatting issues can sometimes cause problems. Open the document in Word and look for any errors or warnings that may indicate the source of the issue.

  4. Upgrade Aspose Version: Your current version (25.9.0.0) is outdated. Consider upgrading to a newer version of Aspose.Words, as there may have been bug fixes or enhancements related to TOC handling in subsequent releases.

  5. Test with a Simple Document: Create a basic document with a TOC and perform a mail merge to see if the issue persists. This can help identify whether the problem lies with the specific document or the mail merge process itself.

If the issue continues, you may want to seek further assistance from the Aspose community or documentation for more tailored guidance related to your version and the specific nature of the error.

@srinicasepoint Could you please attach your problematic input and output documents along with simple code that will allow us to reproduce the problem? We will check the issue and provide you more information.

Hi @alexey.noskov ,
Please find the requested sample documents original and after mail merge. The following is the code which I am using it for the mail merge. Please check and let me know.

private void MergeFields()
{
    doc.MailMerge.FieldMergingCallback = new HandleMergeField();

    doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveUnusedRegions | MailMergeCleanupOptions.RemoveUnusedFields | MailMergeCleanupOptions.RemoveStaticFields | MailMergeCleanupOptions.RemoveEmptyParagraphs;
    doc.MailMerge.Execute(mergeData.Keys.ToArray(), mergeData.Values.ToArray());

    doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveUnusedRegions;
    doc.MailMerge.ExecuteWithRegions(mvalDataSet);

    doc.UpdateFields();

    doc.UpdatePageLayout();

    int i = 0;
    foreach (var sectionIndex in sectionsIndicesToHide)
    {
        if (sectionIndex - i < doc.Sections.Count)
        {
            doc.Sections.RemoveAt(sectionIndex - i);
            i++;
        }
    }
    doc.Save(ms, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(SaveFormat.Docx));
}

Original Document.docx (1.3 MB)

After Merge Field Replacement.docx (1.3 MB)

Thanks.

@srinicasepoint Thank you for additional information. As I can see TOC looks correct in both attached documents. The screenshot provided in the initial post it pixelated too much, so I cannot read the error message shown by MS Word on your side.

@alexey.noskov , Please open the After Merge Field Replacement.docx and click here. Please check the attached image for the error.
Thanks,
BVS Rao.

@srinicasepoint Thank you for additional information. I see the problem in your attached document now, but I cannot reproduce the problem on my side. Could you please create a simple console application that will allow us to reproduce the problematic output document on our side?

Hi @alexey.noskov , Please find the requested sample project with issue.
Thanks.
TableOfContentIssue.zip (1.4 MB)

@srinicasepoint
We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.

Issue ID(s): WORDSNET-28765

You can obtain Paid Support Services if you need support on a priority basis, along with the direct access to our Paid Support management team.

@alexey.noskov ,
Thanks for update. Do you know when can I expect the fix for this issue?
Thanks.

@srinicasepoint The issue is currently in the queue for analysis. once analysis is do we will be able to provide you more information or a fix.

It looks like the reason of the problem is MailMergeCleanupOptions.RemoveStaticFields. As a temporary workaround, you can exclude this MailMergeCleanupOptions.

Hi @alexey.noskov ,
As per your suggestion I made the above temporary workaround and it worked. But what are the implications of this change? Please let me know.
Thanks.

@srinicasepoint This options specifies whether static fields should be removed from the document. Static fields are fields, which results remain the same upon any document change. So there should not be any side effects if you remove this cleanup option.

@srinicasepoint We have completed analyzing the issue. The TOC field is not broken - it’s removed (the field code itself, but not the result) from the source document according to the MailMergeCleanupOptions.RemoveStaticFields option. The “broken” leftover is a special textbox (SDT) wrapper for the TOC field, which includes an extra Update Table command that updates the first nested table of contents.
However, the SDT is not part of the field itself. So, both Aspose.Words and MS Word do not remove it from the document during mail merge. So the issue is considered as not a bug.

You may use the following code snippet to remove these “broken” textboxes (special table of contents SDTs without an actual TOC field) from the document after mail merge:

var sdts = document.Range.StructuredDocumentTags
    .OfType<StructuredDocumentTag>()
    .Where(p => p.SdtType == SdtType.DocPartObj || p.SdtType == SdtType.BuildingBlockGallery)
    .Where(p => p.BuildingBlockGallery == "Table of Contents")
    .Where(p => !p.Range.Fields.OfType<FieldToc>().Any())
    .ToList();

foreach (var sdt in sdts)
    sdt.RemoveSelfOnly();

Meanwhile, Aspose.Words updates this TOC field with extra invalid entry. This issue will be fixed as per separate task.

@srinicasepoint
We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.

Issue ID(s): WORDSNET-28790

You can obtain Paid Support Services if you need support on a priority basis, along with the direct access to our Paid Support management team.