Articles in this section
Category / Section

How to replace merge field with an HTML string in ASP.NET Core Word?

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can replace merge field with an HTML string in a Word document using C#.

Merge fields at the end of the document may not execute correctly during mail merge when replaced with an HTML string. This occurs because HTML content contains multiple paragraphs, disrupting the merge process if executed multiple times.

To prevent this, first complete the mail merge without inserting HTML. Store merge field locations and their HTML content in a dictionary. After merging, insert the HTML into the stored locations.

Steps to replace merge field with an HTML string in a Word document:

  1. Create a new .NET Core console application project. Create console application in Visual Studio
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
    Add DocIO NuGet package reference to the project

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without the trial message.

  1. Include the following namespaces in the Program.cs file.
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. Use the following dictionary to store paragraphs along with their corresponding HTML content.
    C#
static Dictionary<WParagraph, List<KeyValuePair<int, string>>> paraToInsertHTML = new Dictionary<WParagraph, List<KeyValuePair<int, string>>>();
  1. Use the following code example to perform mail merge.
    C#
// Open the template Word document.
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
   using (WordDocument document = new WordDocument(fileStream, FormatType.Docx))
   {
       //Creates mail merge events handler to replace merge field with HTML.
       document.MailMerge.MergeField += new MergeFieldEventHandler(MergeFieldEvent);
       //Gets data to perform mail merge.
       DataTable table = GetDataTable();
       //Performs the mail merge.
       document.MailMerge.Execute(table);
       //Append HTML to paragraph.
       InsertHtml();
       //Removes mail merge events handler.
       document.MailMerge.MergeField -= new MergeFieldEventHandler(MergeFieldEvent);
       // Save the modified document.
       using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
       {
           document.Save(outputStream, FormatType.Docx);
       }
   }
} 
  1. Use the following code example to replace merge fields with an HTML string by using MergeFieldEventHandler.
    C#
public static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
{
   if (args.TableName.Equals("HTML"))
   {
       if (args.FieldName.Equals("ProductList"))
       {
           //Gets the current merge field owner paragraph.
           WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
           //Gets the current merge field index in the current paragraph.
           int mergeFieldIndex = paragraph.ChildEntities.IndexOf(args.CurrentMergeField);
           // Check if this paragraph already has an entry in the dictionary.
           // If not, create a new list to store field index and value pairs.
           if (!paraToInsertHTML.TryGetValue(paragraph, out var fields))
           {
               fields = new List<KeyValuePair<int, string>>();
               paraToInsertHTML[paragraph] = fields;
           }
           // Add the current merge field's index and its value to the list
           fields.Add(new KeyValuePair<int, string>(mergeFieldIndex, args.FieldValue.ToString()));
           //Set field value as empty.
           args.Text = string.Empty;
       }
   }
}
  1. Use the following code example to get the data to perform mail merge.
    C#
/// <summary>
/// Gets the data to perform mail merge.
/// </summary>
/// <returns></returns>
private static DataTable GetDataTable()
{
   DataTable dataTable = new DataTable("HTML");
   dataTable.Columns.Add("CustomerName");
   dataTable.Columns.Add("Address");
   dataTable.Columns.Add("Phone");
   dataTable.Columns.Add("ProductList");
   DataRow datarow = dataTable.NewRow();
   dataTable.Rows.Add(datarow);
   datarow["CustomerName"] = "Nancy Davolio";
   datarow["Address"] = "59 rue de I'Abbaye, Reims 51100, France";
   datarow["Phone"] = "1-888-936-8638";
   //Reads HTML string from the file.
   string htmlString = File.ReadAllText(Path.GetFullPath(@"Data/File.html"));
   datarow["ProductList"] = htmlString;
   return dataTable;
} 
  1. Use the following code example to append HTML to a paragraph after mail merge.
    C#
private static void InsertHtml()
{
   //Iterates through each item in the dictionary.
   foreach (KeyValuePair<WParagraph, List<KeyValuePair<int, string>>> dictionaryItems in paraToInsertHTML)
   {
       // Get the paragraph where HTML needs to be inserted.
       WParagraph paragraph = dictionaryItems.Key;
       // Get the list of (index, HTML string) pairs for this paragraph.
       List<KeyValuePair<int, string>> values = dictionaryItems.Value;
       // Iterate through the list in reverse order
       for (int i = values.Count - 1; i >= 0; i--)
       {
           // Get the index of the merge field within the paragraph.
           int index = values[i].Key;
           // Get the HTML content to insert.
           string fieldValue = values[i].Value;
           // Get paragraph position.
           int paragraphIndex = paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph);
           //Inserts HTML string at the same position of mergefield in Word document.
           paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraphIndex, index);
       }

   }
   paraToInsertHTML.Clear();
}

You can download a complete working sample to a replace merge field with an HTML string in a Word document from GitHub.

Output Word document

Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion

I hope you enjoyed learning about how to replace merge field with an HTML string in an ASP.NET Core Word.

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied