How to Replace a Merge Field in a .NET Core Word Document?
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 a merge field with an image from an HTML string in a Word document using C#.
To achieve this, follow the steps below:
- Retrieve the data for the mail merge operation.
- Execute the mail merge process with a MergeField event handler.
- Within the MergeField event handler, identify the paragraph where the merge field will be replaced with an HTML string.
- After completing the mail merge, insert the HTML content into the corresponding paragraph using the ImageNodeVisited event handler.
- In the ImageNodeVisited event handler, read and insert the image from the specified path while importing the HTML.
Steps to replace a merge field with an image from an HTML string in a Word document:
- Create a new .NET Core console application project.
- Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
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 trail message.
- Include the following namespaces in Program.cs file
C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
- Use the following code example to replace a merge field with an image from an HTML string in a Word document.
C#
//Dictionary to maintain paragraph and corresponding merge field index with HTML content.
Dictionary<WParagraph, Dictionary<int, string>> paraToInsertHTML = new Dictionary<WParagraph, Dictionary<int, string>>();
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
//Opens the template Word document.
using (WordDocument document = new WordDocument(fileStream, FormatType.Automatic))
{
//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);
using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
//Saves the Modified Word document.
document.Save(outputStream, FormatType.Docx);
}
}
}
- Use the following helper method to get data to perform the mail merge.
C#
/// <summary>
/// Get a data table for the mail merge operation.
/// </summary>
DataTable GetDataTable()
{
DataTable dataTable = new DataTable("HTML");
dataTable.Columns.Add("CustomerName");
dataTable.Columns.Add("Address");
dataTable.Columns.Add("Phone");
dataTable.Columns.Add("Logo");
//Adds sample data to the DataTable.
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["Logo"] = htmlString;
return dataTable;
}
- Use the following helper method to get the paragraph where to replace merge field with HTML string by using MergeFieldEventHandler.
C#
/// <summary>
/// Handles the MergeField event to replace the merge field with HTML content.
/// </summary>
void MergeFieldEvent(object sender, MergeFieldEventArgs args)
{
if (args.FieldName.Equals("Logo"))
{
//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;
}
}
- Use the following helper method to insert the HTML content into a paragraph.
C#
/// <summary>
/// Inserts HTML content into the specified paragraphs and positions within the Word document.
/// </summary>
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;
//Hook the ImageNodeVisited event to resolve images within HTML content.
paragraph.Document.HTMLImportSettings.ImageNodeVisited += OpenImage;
//Inserts an HTML string at the same position of mergefield in a Word document.
paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index);
//Unhook the ImageNodeVisited event after processing.
paragraph.Document.HTMLImportSettings.ImageNodeVisited -= OpenImage;
}
}
//Clears the dictionary after inserting HTML content.
paraToInsertHTML.Clear();
}
- Use the following helper method to read the image from the specified path when importing the HTML file.
C#
/// <summary>
/// Opens images referenced within HTML content.
/// </summary>
void OpenImage(object sender, ImageNodeVisitedEventArgs args)
{
//Reads the image from the specified URI path and assigns it to the image stream.
args.ImageStream = File.OpenRead(args.Uri);
}
You can download a complete working sample to replace a merge field with an image from an HTML string in a Word document from the GitHub.
By executing the program, you will get the Word document as follows.
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 how to replace a merge field in a .NET Core Word Document.
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!