Articles in this section
Category / Section

How to Replace Merge Field with HTML String in WinForms DocIO?

Mail merge is a process of merging data from a data source to a Word template document. Syncfusion Essential DocIO is a .NET Word library used to generate reports like invoices, payroll, letters, and more, by performing a mail merge faster in a batch process without Microsoft Word or interop dependencies. Using this library, you can replace the merge field with an HTML string using Mail merge in C# and VB.NET.


Replace merge field with HTML string using C#:

  1. Create a new C# console application project.

Create Console application in Visual Studio

  1. Install  Syncfusion.DocIO.WinForms NuGet package as a reference to your .NET Framework applications from NuGet.org.

Add DocIO NuGet package reference to the project

  1. Include the following namespace in the Program.cs file.

C#

using Syncfusion.DocIO.DLS;
using System.Data;
using System.IO;

 

VB

Imports System.IO
Imports Syncfusion.DocIO
Imports Syncfusion.DocIO.DLS

 

  1. Use the following code example to replace the merge field in a Word document with an HTML string using Mail merge.

C#

Dictionary<WParagraph, List<KeyValuePair<int, string>>> paraToInsertHTML = new Dictionary<WParagraph, List<KeyValuePair<int, string>>>();
// Opens the template document.
using (WordDocument document = new WordDocument(Path.GetFullPath("Template.docx")))
{
    // Creates the mail merge events handler to replace merge field with HTML.
    document.MailMerge.MergeField += new MergeFieldEventHandler(MergeFieldEvent);
    // Gets data to perform the mail merge.
    DataTable table = GetDataTable();
    // Performs the mail merge.
    document.MailMerge.Execute(table);
    // Append HTML to paragraph.
    InsertHtml();
    // Removes the mail merge events handler.
    document.MailMerge.MergeField -= new MergeFieldEventHandler(MergeFieldEvent);
    // Saves the Word document instance.
    document.Save(Path.GetFullPath("Result.docx"));
}

 

VB

Dim paraToInsertHTML As New Dictionary(Of WParagraph, List(Of KeyValuePair(Of Integer, String)))()
'Opens the template document.
Using document As WordDocument = New WordDocument("Template.docx", FormatType.Docx)
    'Creates the mail merge events handler to replace merge field with HTML.
    AddHandler document.MailMerge.MergeField, AddressOf MergeFieldEvent
    'Gets data to perform the mail merge.
    Dim table As DataTable = GetDataTable()
    'Performs the mail merge.
    document.MailMerge.Execute(table)
    'Append HTML to paragraph.
    InsertHtml()
    'Removes the mail merge events handler.
    RemoveHandler document.MailMerge.MergeField, AddressOf MergeFieldEvent
    'Saves the WordDocument instance.
    document.Save("Result.docx", FormatType.Docx)
End Using

 

  1. Use the following helper method to get the paragraph where to replace merge field with 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;
        }
    }
}

 

VB

Public Sub MergeFieldEvent(ByVal sender As Object, ByVal args As MergeFieldEventArgs)
   
  If args.TableName.Equals("HTML") Then
        If args.FieldName.Equals("ProductList") Then
            'Gets the current merge field owner paragraph.
            Dim paragraph As WParagraph = args.CurrentMergeField.OwnerParagraph
            'Gets the current merge field index in the current paragraph.
            Dim mergeFieldIndex As Integer = 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.
            Dim fields As List(Of KeyValuePair(Of Integer, String)) = Nothing
            If Not paraToInsertHTML.TryGetValue(paragraph, fields) Then
                fields = New List(Of KeyValuePair(Of Integer, String))()
                paraToInsertHTML(paragraph) = fields
            End If

            ' Add the current merge field's index and its value to the list.
            fields.Add(New KeyValuePair(Of Integer, String)(mergeFieldIndex, args.FieldValue.ToString()))
            'Set field value as empty.
            args.Text = String.Empty
        End If
    End If

End Sub

 

  1. Use the following helper method to insert the HTML content into a paragraph.

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();
        }

 

VB

Private Sub InsertHtml ()
   ' Iterate through each item in the dictionary.
    For Each dictionaryItems As KeyValuePair(Of WParagraph, List(Of KeyValuePair(Of Integer, String))) In paraToInsertHTML
        ' Get the paragraph where HTML needs to be inserted.
        Dim paragraph As WParagraph = dictionaryItems.Key
        ' Get the list of (index, HTML string) pairs for this paragraph.
        Dim values As List(Of KeyValuePair(Of Integer, String)) = dictionaryItems.Value
        ' Iterate through the list in reverse order.
        For i As Integer = values.Count - 1 To 0 Step -1
            ' Get the index of the merge field within the paragraph.
            Dim index As Integer = values(i).Key
            ' Get the HTML content to insert.
            Dim fieldValue As String = values(i).Value
            ' Get paragraph position.
            Dim paragraphIndex As Integer = paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph)
            ' Inserts HTML string at the same position of mergefield in Word document.
            paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraphIndex, index)
        Next
    Next
    ' Clear the dictionary after processing.
    paraToInsertHTML.Clear() End Sub

 

  1. Use the following helper method to get data to perform the Mail merge.

C#

private 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 l'Abbaye, Reims 51100, France";
    datarow["Phone"] = "1-888-936-8638";
    // Reads HTML string from the file.
    string htmlString = File.ReadAllText("File.html");
    datarow["ProductList"] = htmlString;
    return dataTable;
}

 

VB

Public Function GetDataTable() As DataTable
    Dim dataTable As DataTable = New DataTable("HTML")
    dataTable.Columns.Add("CustomerName")
    dataTable.Columns.Add("Address")
    dataTable.Columns.Add("Phone")
    dataTable.Columns.Add("ProductList")
    Dim datarow As DataRow = dataTable.NewRow
    dataTable.Rows.Add(datarow)
    datarow("CustomerName") = "Nancy Davolio"
    datarow("Address") = "59 rue de l'Abbaye, Reims 51100, France"
    datarow("Phone") = "1-888-936-8638"
    'Reads HTML string from the file.
    Dim htmlString As String = File.ReadAllText("File.html")
    datarow("ProductList") = htmlString
    Return dataTable
End Function

 

A complete working example to replace the merge field with HTML string through Mail merge using C# can be downloaded from GitHub.

By executing the application, you will get the output Word document as follows. Replace merge field with HTML using mail merge

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

Explore more about the rich set of Syncfusion® Word Framework features.

Note:

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

 

Conclusion


I hope you enjoyed learning about how to replace merge field with HTML string in WinForms DocIO.

You can refer to our WinForms DocIO feature tour page to learn about its other groundbreaking features. You can also explore our WinForms DocIO documentation 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 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