|
| 1 | +using Syncfusion.DocIO; |
| 2 | +using Syncfusion.DocIO.DLS; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Data; |
| 5 | +using System.IO; |
| 6 | +using System.Net; |
| 7 | +using System.Text; |
| 8 | + |
| 9 | +namespace ReplaceMergeFieldWithMarkdown |
| 10 | +{ |
| 11 | + class Program |
| 12 | + { |
| 13 | + // Dictionary to store paragraphs and corresponding merge field positions with Markdown content. |
| 14 | + static Dictionary<WParagraph, Dictionary<int, string>> paraToInsertMarkdown = new Dictionary<WParagraph, Dictionary<int, string>>(); |
| 15 | + |
| 16 | + static void Main(string[] args) |
| 17 | + { |
| 18 | + // Open the template document. |
| 19 | + using (FileStream inputFileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) |
| 20 | + { |
| 21 | + using (WordDocument document = new WordDocument(inputFileStream, FormatType.Automatic)) |
| 22 | + { |
| 23 | + // Attach mail merge event handler to replace merge field with Markdown. |
| 24 | + document.MailMerge.MergeField += MergeFieldEvent; |
| 25 | + |
| 26 | + // Retrieve data for mail merge. |
| 27 | + DataTable table = GetDataTable(); |
| 28 | + |
| 29 | + // Perform mail merge. |
| 30 | + document.MailMerge.Execute(table); |
| 31 | + |
| 32 | + // Insert the Markdown content at the specified positions. |
| 33 | + InsertMarkdown(); |
| 34 | + |
| 35 | + // Detach mail merge event handler. |
| 36 | + document.MailMerge.MergeField -= MergeFieldEvent; |
| 37 | + |
| 38 | + // Save the updated document. |
| 39 | + using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite)) |
| 40 | + { |
| 41 | + document.Save(outputFileStream, FormatType.Docx); |
| 42 | + } |
| 43 | + |
| 44 | + // Close the document. |
| 45 | + document.Close(); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + #region Helper Methods |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// Event handler to replace merge fields with Markdown content. |
| 54 | + /// </summary> |
| 55 | + private static void MergeFieldEvent(object sender, MergeFieldEventArgs args) |
| 56 | + { |
| 57 | + if (args.TableName == "Markdown" && args.FieldName == "ProductList") |
| 58 | + { |
| 59 | + // Get the paragraph containing the merge field. |
| 60 | + WParagraph paragraph = args.CurrentMergeField.OwnerParagraph; |
| 61 | + |
| 62 | + // Get the merge field position in the paragraph. |
| 63 | + int mergeFieldIndex = paragraph.ChildEntities.IndexOf(args.CurrentMergeField); |
| 64 | + |
| 65 | + // Store the Markdown content along with its position in the paragraph. |
| 66 | + if (!paraToInsertMarkdown.ContainsKey(paragraph)) |
| 67 | + { |
| 68 | + paraToInsertMarkdown[paragraph] = new Dictionary<int, string>(); |
| 69 | + } |
| 70 | + paraToInsertMarkdown[paragraph][mergeFieldIndex] = args.FieldValue.ToString(); |
| 71 | + |
| 72 | + // Set the field value as empty to remove the original merge field. |
| 73 | + args.Text = string.Empty; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// <summary> |
| 78 | + /// Generates the data required for the mail merge operation. |
| 79 | + /// </summary> |
| 80 | + private static DataTable GetDataTable() |
| 81 | + { |
| 82 | + DataTable dataTable = new DataTable("Markdown"); |
| 83 | + dataTable.Columns.Add("CustomerName"); |
| 84 | + dataTable.Columns.Add("Address"); |
| 85 | + dataTable.Columns.Add("Phone"); |
| 86 | + dataTable.Columns.Add("ProductList"); |
| 87 | + |
| 88 | + DataRow dataRow = dataTable.NewRow(); |
| 89 | + dataRow["CustomerName"] = "Nancy Davolio"; |
| 90 | + dataRow["Address"] = "59 rue de I'Abbaye, Reims 51100, France"; |
| 91 | + dataRow["Phone"] = "1-888-936-8638"; |
| 92 | + |
| 93 | + // Markdown content. |
| 94 | + dataRow["ProductList"] = "# Hello Markdown!\nThis is some **bold** text."; |
| 95 | + |
| 96 | + dataTable.Rows.Add(dataRow); |
| 97 | + return dataTable; |
| 98 | + } |
| 99 | + |
| 100 | + /// <summary> |
| 101 | + /// Inserts Markdown content at the correct positions in the Word document. |
| 102 | + /// </summary> |
| 103 | + private static void InsertMarkdown() |
| 104 | + { |
| 105 | + foreach (var paragraphEntry in paraToInsertMarkdown) |
| 106 | + { |
| 107 | + WParagraph paragraph = paragraphEntry.Key; |
| 108 | + Dictionary<int, string> fieldValues = paragraphEntry.Value; |
| 109 | + |
| 110 | + foreach (var fieldValueEntry in fieldValues) |
| 111 | + { |
| 112 | + int index = fieldValueEntry.Key; |
| 113 | + string markdownContent = fieldValueEntry.Value; |
| 114 | + |
| 115 | + // Convert Markdown content to bytes and create a stream. |
| 116 | + byte[] contentBytes = Encoding.UTF8.GetBytes(markdownContent); |
| 117 | + using (MemoryStream memoryStream = new MemoryStream(contentBytes)) |
| 118 | + { |
| 119 | + using (WordDocument markdownDoc = new WordDocument(memoryStream, FormatType.Markdown)) |
| 120 | + { |
| 121 | + // Prepare to insert the Markdown content at the correct location. |
| 122 | + TextBodyPart bodyPart = new TextBodyPart(paragraph.OwnerTextBody.Document); |
| 123 | + BodyItemCollection bodyItems = bodyPart.BodyItems; |
| 124 | + |
| 125 | + // Copy and paste the markdown at the same position of mergefield in Word document. |
| 126 | + foreach (Entity entity in markdownDoc.LastSection.Body.ChildEntities) |
| 127 | + { |
| 128 | + bodyItems.Add(entity.Clone()); |
| 129 | + } |
| 130 | + bodyPart.PasteAt(paragraph.OwnerTextBody, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index); |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + // Clear the dictionary after processing. |
| 137 | + paraToInsertMarkdown.Clear(); |
| 138 | + } |
| 139 | + |
| 140 | + #endregion |
| 141 | + } |
| 142 | +} |
0 commit comments