|
| 1 | +using Syncfusion.DocIO.DLS; |
| 2 | + |
| 3 | +namespace Insert_hyperlink_during_mailmerge |
| 4 | +{ |
| 5 | + class Program |
| 6 | + { |
| 7 | + public static void Main(string[] args) |
| 8 | + { |
| 9 | + // Open the template Word document |
| 10 | + WordDocument document = new WordDocument(Path.GetFullPath(@"Data/Template.docx")); |
| 11 | + // Subscribe to the MailMerge.MergeField event |
| 12 | + // This event is triggered whenever a merge field is processed during mail merge |
| 13 | + document.MailMerge.MergeField += MailMerge_MergeField; |
| 14 | + // Define the merge field names present in the template document |
| 15 | + string[] fieldNames = new string[] { "EmployeeId", "Name", "Phone", "City", "Contact" }; |
| 16 | + // Define the values that will replace the merge fields during mail merge |
| 17 | + string[] fieldValues = new string[] { "1001", "Peter", "+122-2222222", "London", "peter@xyz.com" }; |
| 18 | + //Execute Mail merge |
| 19 | + document.MailMerge.Execute(fieldNames, fieldValues); |
| 20 | + // Save the result document |
| 21 | + document.Save(Path.GetFullPath(@"../../../Output/output.docx")); |
| 22 | + } |
| 23 | + /// <summary> |
| 24 | + /// Event handler that customizes how merge fields are processed. |
| 25 | + /// </summary> |
| 26 | + /// <param name="sender">The source object raising the event (MailMerge engine).</param> |
| 27 | + /// <param name="args">Provides details about the current merge field being processed</param> |
| 28 | + private static void MailMerge_MergeField(object sender, MergeFieldEventArgs args) |
| 29 | + { |
| 30 | + |
| 31 | + // Check if the current merge field is "Contact", If Yes this field will be replaced with a hyperlink |
| 32 | + if (args.FieldName == "Contact") |
| 33 | + { |
| 34 | + // Create a new paragraph and append hyperlink, |
| 35 | + WParagraph paragraph = new WParagraph(args.Document); |
| 36 | + WField hyperlink = paragraph.AppendHyperlink(args.FieldValue.ToString(), "Click ME", HyperlinkType.WebLink) as WField; |
| 37 | + // Get the current merge field object being processed |
| 38 | + WField mergeField = args.CurrentMergeField as WField; |
| 39 | + // Ensure the merge field exists before replacing it |
| 40 | + if (mergeField != null) |
| 41 | + { |
| 42 | + // Get the paragraph that contains the merge field |
| 43 | + WParagraph ownerParagraph = mergeField.OwnerParagraph; |
| 44 | + // Insert the child entity (e.g., hyperlink) from the new paragraph into the original paragraph |
| 45 | + for (int i = 0; i < paragraph.ChildEntities.Count; i++) |
| 46 | + { |
| 47 | + int fieldIndex = ownerParagraph.ChildEntities.IndexOf(mergeField); |
| 48 | + ownerParagraph.ChildEntities.Insert(fieldIndex, paragraph.ChildEntities[i].Clone()); |
| 49 | + } |
| 50 | + // Remove the original merge field from the paragraph |
| 51 | + ownerParagraph.ChildEntities.Remove(mergeField); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments