|
| 1 | +using Syncfusion.DocIO; |
| 2 | +using Syncfusion.DocIO.DLS; |
| 3 | +using Syncfusion.Drawing; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Data; |
| 6 | +using System.IO; |
| 7 | + |
| 8 | +namespace Modify_font_during_mail_merge |
| 9 | +{ |
| 10 | + class Program |
| 11 | + { |
| 12 | + static void Main(string[] args) |
| 13 | + { |
| 14 | + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("Ngo9BigBOggjHTQxAR8/V1NMaF5cXmBCf1FpRmJGdld5fUVHYVZUTXxaS00DNHVRdkdmWX1cdnRRQ2NcUkZwXUo="); |
| 15 | + using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite)) |
| 16 | + { |
| 17 | + //Opens the template document. |
| 18 | + using (WordDocument document = new WordDocument(fileStream, FormatType.Docx)) |
| 19 | + { |
| 20 | + // Retrieve all merge field group names present in the document. |
| 21 | + string[] mergeGroupNames = document.MailMerge.GetMergeGroupNames(); |
| 22 | + //Modify group names in the document |
| 23 | + ModifyGroupName(document, mergeGroupNames); |
| 24 | + //Creates file stream. |
| 25 | + using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite)) |
| 26 | + { |
| 27 | + //Saves the Word document to file stream. |
| 28 | + document.Save(outputStream, FormatType.Docx); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + #region Helper methods |
| 35 | + /// <summary> |
| 36 | + /// Find and modify merge group name in the document |
| 37 | + /// </summary> |
| 38 | + /// <param name="document"></param> |
| 39 | + /// <param name="mergeGroupNames"></param> |
| 40 | + private static void ModifyGroupName(WordDocument document, string[] mergeGroupNames) |
| 41 | + { |
| 42 | + // Iterate through each merge group name. |
| 43 | + foreach (string mergeGroupName in mergeGroupNames) |
| 44 | + { |
| 45 | + // Find the merge field in the document that matches the current group name (Contains begin and end group). |
| 46 | + // The "FieldName" property is used to locate the specific merge field. |
| 47 | + List<Entity> mergeFieldsWithFieldName = document.FindAllItemsByProperty(EntityType.MergeField, "FieldName", mergeGroupName); |
| 48 | + foreach (Entity entity in mergeFieldsWithFieldName) |
| 49 | + { |
| 50 | + WMergeField currentMergeField = entity as WMergeField; |
| 51 | + // You can modify the field name as needed. |
| 52 | + // Example: Modify the field name by appending "_123" to it. |
| 53 | + currentMergeField.FieldName = mergeGroupName + "_123"; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + #endregion |
| 58 | + } |
| 59 | +} |
0 commit comments