Articles in this section
Category / Section

How to Replace Merge Field with Markdown in .NET Core Word Document?

7 mins read

Syncfusion Essential DocIO is a .NET Core 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 Markdown during mail merge in a Word document using C#.

You can follow the below steps to replace a merge field with Markdown:

  • Utilize the MergeFieldEvent handler to get the markdown content and its corresponding paragraph.
  • Store the markdown content in a dictionary, mapping it to the appropriate paragraph.
  • Convert the stored markdown content into a Word-compatible format using the DocIO library.
  • Replace the original merge field with the converted markdown content in the same paragraph.

Steps to replace a merge field with Markdown during mail merge 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 trail message.

  1. Include the following namespaces in Program.cs file.
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. initializes a static dictionary.
    C#
static Dictionary<WParagraph, Dictionary<int, string>> paraToInsertMarkdown = new Dictionary<WParagraph, Dictionary<int, string>>(); 
  1. Use the following code example to replace a merge field with Markdown during mail merge in a Word document.
    C#
// Open the Word template document as a file stream.
using (FileStream inputFileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
   //Opens an existing document from stream through constructor of `WordDocument` class.
   using (WordDocument document = new WordDocument(inputFileStream, FormatType.Automatic))
   {
       //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 Markdown to paragraph.
       InsertMarkdown();
       //Removes mail merge events handler.
       document.MailMerge.MergeField -= new MergeFieldEventHandler(MergeFieldEvent);
       //Creates file stream.
       using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
       {
           //Saves the Word document to file stream.
           document.Save(outputFileStream, FormatType.Docx);
       }
       //Closes the document.
       document.Close();
   }
}

  1. Use the following code example to replace merge field with Markdown string by using MergeFieldEventHandler.
    C#
public static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
{
   if (args.TableName.Equals("Markdown"))
   {
       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 Markdown in collection.
           Dictionary<int, string> fieldValues = new Dictionary<int, string>();
           fieldValues.Add(mergeFieldIndex, args.FieldValue.ToString());
           //Maintain paragraph in collection.
           paraToInsertMarkdown.Add(paragraph, fieldValues);
           //Set field value as empty.
           args.Text = string.Empty;
       }
   }
} 
  1. Use the following code example to get the data to perform 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();
   dataTable.Rows.Add(datarow);
   datarow["CustomerName"] = "Nancy Davolio";
   datarow["Address"] = "59 rue de I'Abbaye, Reims 51100, France";
   datarow["Phone"] = "1-888-936-8638";
   //Markdown content.
   string markdown = "# Hello Markdown!\nThis is some **bold** text.";
   datarow["ProductList"] = markdown;
   return dataTable;
} 
  1. Use the following code example to append the Markdown to paragraph.
    C#
private static void InsertMarkdown()
{
   //Iterates through each item in the dictionary.
   foreach (KeyValuePair<WParagraph, Dictionary<int, string>> dictionaryItems in paraToInsertMarkdown)
   {
       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;
           // Convert the markdown string to bytes using UTF-8 encoding
           byte[] contentBytes = Encoding.UTF8.GetBytes(fieldValue);

           // Create a MemoryStream from the content bytes
           using (MemoryStream memoryStream = new MemoryStream(contentBytes))
           {
               //Open the markdown Word document
               using (WordDocument markdownDoc = new WordDocument(memoryStream, FormatType.Markdown))
               {
                   TextBodyPart bodyPart = new TextBodyPart(paragraph.OwnerTextBody.Document);
                   BodyItemCollection m_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)
                   {
                       m_bodyItems.Add(entity.Clone());
                   }
                   bodyPart.PasteAt(paragraph.OwnerTextBody, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index);
               }
           }
       }
   }
   paraToInsertMarkdown.Clear();
} 

You can download a complete working sample to replace a merge field with Markdown during mail merge in a Word document from the 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 a merge field with Markdown 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!

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