Articles in this section
Category / Section

How to replace merge field with HTML string in WinForms DocIO?

7 mins read

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 the 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, Dictionary<int, string>> paraToInsertHTML = new Dictionary<WParagraph, Dictionary<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 Dictionary(Of WParagraph, Dictionary(Of Integer, String)) = New Dictionary(Of WParagraph, Dictionary(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);  
            //Maintain HTML in collection.
            Dictionary<int, string> fieldValues = new Dictionary<int, string>();
            fieldValues.Add(mergeFieldIndex, args.FieldValue.ToString());
            //Maintain paragraph in collection.
            paraToInsertHTML.Add(paragraph, fieldValues);
            //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)
            'Maintain HTML in collection.
            Dim fieldValues As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)
            fieldValues.Add(mergeFieldIndex, args.FieldValue.ToString)
            'Maintain paragraph in collection.
            paraToInsertHTML.Add(paragraph, fieldValues)
            '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 void InsertHtml ()
{
    //Iterates through each item in the dictionary.
    foreach (KeyValuePair<WParagraph, Dictionary<int, string>> dictionaryItems in paraToInsertHTML)
    {
        WParagraph paragraph = dictionaryItems.Key as WParagraph;
        Dictionary<int, string> values = dictionaryItems.Value as Dictionary<int, string>;
        //Iterates through each value in the dictionary.
        foreach (KeyValuePair<int, string> valuePair in values)
        {
            int index = valuePair.Key;
            string fieldValue = valuePair.Value;
            //Inserts an HTML string at the same position of mergefield in a Word document.
            paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index);
        }
    }
    dictionaryObject.Clear();
}

 

VB

Private Sub InsertHtml ()
    'Iterates through each item in the dictionary.
    For Each dictionaryItems As KeyValuePair(Of WParagraph, Dictionary(Of Integer, String)) In paraToInsertHTML
        Dim paragraph As WParagraph = CType(dictionaryItems.Key, WParagraph)
        Dim values As Dictionary(Of Integer, String) = CType(dictionaryItems.Value, Dictionary(Of Integer, String))
        'Iterates through each value in the dictionary.
        For Each valuePair As KeyValuePair(Of Integer, String) In values
            Dim index As Integer = valuePair.Key    
            Dim fieldValue As String = valuePair.Value
            'Inserts an HTML string at the same position of mergefield in a Word document.
            paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index)
        Next
    Next
    dictionaryObject.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 I'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 I'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 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 trail 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 know about its other groundbreaking feature representations. 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 forumsDirect-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)
Please  to leave a comment
Access denied
Access denied