Articles in this section

How to Insert Hyperlink during Mail Merge in .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 insert a hyperlink during mail merge in a Word document using C#.

This article explains how to insert a hyperlink during mail merge. In this example, the Contact merge field is converted into a hyperlink during the mail merge process. You can use any merge field as needed.

Overview of the Insert Hyperlink During Mail Merge Logic:

  • Open the template Word document.
  • Retrieve employee details from a data source and create a MailMergeDataTable with the employee collection.
  • Attach event handlers for merge fields and image fields.
  • Perform the mail merge operation and store the Contact merge field’s index and owner paragraph in a collection.
  • After completing the mail merge process, iterate through the collection to get each paragraph and retrieve the merge field text based on the index.
  • Insert a hyperlink at the merge field text position and remove the original merge field text.
  • Save and close the document.

Steps to insert a hyperlink 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 trial message.

  1. Include the following namespaces in the Program.cs file
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. Use the following code example to insert a hyperlink during mail merge in a Word document.
    C#
// Open the template Word document
WordDocument document = new WordDocument(Path.GetFullPath(@"Data/EmployeesTemplate.docx"));
// Gets the employee details as IEnumerable collection.
List<Employee> employeeList = GetEmployees();
// Creates an instance of MailMergeDataTable by specifying MailMerge group name and IEnumerable collection.
MailMergeDataTable dataSource = new MailMergeDataTable("Employees", employeeList);
// Uses the mail merge events handler for image fields.
document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_EmployeeImage);
// Uses the mail merge event handler for merge fields.
document.MailMerge.MergeField += MailMerge_MergeField;
// Performs Mail merge.
document.MailMerge.ExecuteGroup(dataSource);
// Insert Hyperlink to the merge field text.
InsertHyperlink(document);
// Save the result document
document.Save(Path.GetFullPath(@"../../../Output/output.docx"));
// Close the Word document
document.Close();
  1. Use the following helper method to insert a hyperlink during mail merge in a Word document.
    C#
static Dictionary<WParagraph, List<int>> paraToInsertHyperlink = new Dictionary<WParagraph, List<int>>();

private static void InsertHyperlink(WordDocument document)
{
   foreach (KeyValuePair<WParagraph, List<int>> dictionaryItems in paraToInsertHyperlink)
   {
       // Get the paragraph where Hyperlink needs to be inserted.
       WParagraph paragraph = dictionaryItems.Key;
       // Get the list of index for the merge fields.
       List<int> 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];
           // Get the merge field content to insert as Hyperlink.
           WTextRange mergeFieldText = paragraph.ChildEntities[index] as WTextRange;                                       
           if (mergeFieldText != null)
           {
               string hyperlinkText = mergeFieldText.Text;
               WParagraph hyperlinkParagraph = new WParagraph(document);
               WField hyperlink = hyperlinkParagraph.AppendHyperlink(hyperlinkText, hyperlinkText, HyperlinkType.WebLink) as WField;
               // Insert the child entity (e.g., hyperlink) from the new paragraph into the original paragraph
               for (int j = hyperlinkParagraph.ChildEntities.Count - 1; j >= 0; j--)
               {
                   paragraph.ChildEntities.Insert(index, hyperlinkParagraph.ChildEntities[j].Clone());
               }
               // Remove the original merge field text from the paragraph
               paragraph.ChildEntities.Remove(mergeFieldText);
           }
       }
   }
   paraToInsertHyperlink.Clear();
}
  1. Use the following code example to handle the MergeField event.
    C#
private static void MailMerge_MergeField(object sender, MergeFieldEventArgs args)
{

   // Check if the current merge field is "Contact"
   if (args.FieldName == "Contact")
   {
       // Get the mergefield's Owner paragraph
       WParagraph mergeFieldOwnerParagraph = args.CurrentMergeField.OwnerParagraph;
       // Check if this paragraph already has an entry in the dictionary.
       // If not, create a new list to store field index.
       if (!paraToInsertHyperlink.TryGetValue(mergeFieldOwnerParagraph, out var fields))
       {
           fields = new List<int>();
           paraToInsertHyperlink[mergeFieldOwnerParagraph] = fields;                  
       }
       // Add the current merge field's index
       fields.Add(mergeFieldOwnerParagraph.ChildEntities.IndexOf(args.CurrentMergeField));
   }
}
  1. Use the following code example to handle the MergeImageField event.
    C#
private static void MergeField_EmployeeImage(object sender, MergeImageFieldEventArgs args)
{
   //Binds image from file system during mail merge.
   if (args.FieldName == "Photo")
   {
       string photoFileName = args.FieldValue.ToString();
       //Gets the image from file system.
       FileStream imageStream = new FileStream(Path.GetFullPath(@"Data/" + photoFileName), FileMode.Open, FileAccess.Read);
       args.ImageStream = imageStream;
   }
}
  1. Use the following code example to get the Employees details.
    C#
public static List<Employee> GetEmployees()
{
    List<Employee> employees = new List<Employee>();
    employees.Add(new Employee("Nancy", "Smith", "Sales Representative", "505 - 20th Ave. E. Apt. 2A,", "Seattle", "WA", "USA","[email protected]", "Nancy.png"));
    employees.Add(new Employee("Andrew", "Fuller", "Vice President, Sales", "908 W. Capital Way", "Tacoma", "WA", "USA", "[email protected]", "Andrew.png"));
    employees.Add(new Employee("Roland", "Mendel", "Sales Representative", "722 Moss Bay Blvd.", "Kirkland", "WA", "USA", "[email protected]", "Janet.png"));
    employees.Add(new Employee("Margaret", "Peacock", "Sales Representative", "4110 Old Redmond Rd.", "Redmond", "WA", "USA", "[email protected]", "Margaret.png"));
    employees.Add(new Employee("Steven", "Buchanan", "Sales Manager", "14 Garrett Hill", "London", string.Empty, "UK", "[email protected]", "Steven.png"));
    return employees;
}
  1. Use the following code example to maintain employee details.
    C#
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string Country { get; set; }
    public string Title { get; set; }
    public string Contact { get; set; }
    public string Photo { get; set; }
    public Employee(string firstName, string lastName, string title, string address, string city, string region, string country, string contact, string photoFilePath)
    {
        FirstName = firstName;
        LastName = lastName;
        Title = title;
        Address = address;
        City = city;
        Region = region;
        Country = country;
        Contact = contact;
        Photo = photoFilePath;
    }
}

You can download a complete working sample to insert a hyperlink 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 insert a hyperlink during mail merge in a Word document 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!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied