How to replace merge fields with markdown content in a 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 merge fields with markdown content in a Word document using C#.
Steps to replace merge fields with markdown content 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 store paragraphs and corresponding merge field positions with Markdown content in dictionary.
C#
// Dictionary to store paragraphs and corresponding merge field positions with Markdown content.
static Dictionary<WParagraph, Dictionary<int, string>> paraToInsertMarkdown = new Dictionary<WParagraph, Dictionary<int, string>>();
- Use the following code example to perform mail merge.
C#
// Open the template document.
using (FileStream inputFileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (WordDocument document = new WordDocument(inputFileStream, FormatType.Automatic))
{
// Attach mail merge event handler to replace merge field with Markdown.
document.MailMerge.MergeField += MergeFieldEvent;
// Retrieve data for mail merge.
DataTable table = GetDataTable();
// Perform mail merge.
document.MailMerge.Execute(table);
// Insert the Markdown content at the specified positions.
InsertMarkdown();
// Detach mail merge event handler.
document.MailMerge.MergeField -= MergeFieldEvent;
// Save the updated document.
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
document.Save(outputFileStream, FormatType.Docx);
}
// Close the document.
document.Close();
}
}
- Use the following code example to get the paragraph containing merge field and its position.
C#
private static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
{
if (args.TableName == "Markdown" && args.FieldName == "ProductList")
{
// Get the paragraph containing the merge field.
WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
// Get the merge field position in the paragraph.
int mergeFieldIndex = paragraph.ChildEntities.IndexOf(args.CurrentMergeField);
// Store the Markdown content along with its position in the paragraph.
if (!paraToInsertMarkdown.ContainsKey(paragraph))
{
paraToInsertMarkdown[paragraph] = new Dictionary<int, string>();
}
paraToInsertMarkdown[paragraph][mergeFieldIndex] = args.FieldValue.ToString();
// Set the field value as empty to remove the original merge field.
args.Text = string.Empty;
}
}
- Use the following code example to get the data required for the mail merge.
C#
private static DataTable GetDataTable()
{
DataTable dataTable = new DataTable("Markdown");
dataTable.Columns.Add("CustomerName");
dataTable.Columns.Add("Address");
dataTable.Columns.Add("Phone");
dataTable.Columns.Add("ProductList");
DataRow dataRow = dataTable.NewRow();
dataRow["CustomerName"] = "Nancy Davolio";
dataRow["Address"] = "59 rue de I'Abbaye, Reims 51100, France";
dataRow["Phone"] = "1-888-936-8638";
// Markdown content.
dataRow["ProductList"] = "# Hello Markdown!\nThis is some **bold** text.";
dataTable.Rows.Add(dataRow);
return dataTable;
}
- Use the following code example to inserts Markdown content at the correct positions in the Word document.
C#
private static void InsertMarkdown()
{
foreach (var paragraphEntry in paraToInsertMarkdown)
{
WParagraph paragraph = paragraphEntry.Key;
Dictionary<int, string> fieldValues = paragraphEntry.Value;
foreach (var fieldValueEntry in fieldValues)
{
int index = fieldValueEntry.Key;
string markdownContent = fieldValueEntry.Value;
// Convert Markdown content to bytes and create a stream.
byte[] contentBytes = Encoding.UTF8.GetBytes(markdownContent);
using (MemoryStream memoryStream = new MemoryStream(contentBytes))
{
using (WordDocument markdownDoc = new WordDocument(memoryStream, FormatType.Markdown))
{
// Prepare to insert the Markdown content at the correct location.
TextBodyPart bodyPart = new TextBodyPart(paragraph.OwnerTextBody.Document);
BodyItemCollection bodyItems = bodyPart.BodyItems;
// Copy and paste the markdown at the same position of mergefield in Word document.
foreach (Entity entity in markdownDoc.LastSection.Body.ChildEntities)
{
bodyItems.Add(entity.Clone());
}
bodyPart.PasteAt(paragraph.OwnerTextBody, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index);
}
}
}
}
// Clear the dictionary after processing.
paraToInsertMarkdown.Clear();
}
You can download a complete working sample to replace merge fields with markdown content in a Word document from the GitHub.
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 fields with markdown content in a Word document in .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!