Skip to content

Commit 37b0c78

Browse files
ES-263656-Replace-merge-field-with-HTML
1 parent ce52f36 commit 37b0c78

File tree

6 files changed

+170
-0
lines changed

6 files changed

+170
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.31911.196
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Replace-merge-field-with-HTML", "Replace-merge-field-with-HTML\Replace-merge-field-with-HTML.csproj", "{C17B90BC-F559-456B-B189-90B53FF6CDD4}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {EF357FC6-E9E5-4E3C-B932-43F727BE1DE4}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<html>
2+
<body>
3+
<div style="font-family:calibri;color:#203864;">
4+
<ul>
5+
<li>Mountain-200</li>
6+
<li>Mountain-300</li>
7+
<li>Road-150</li>
8+
</ul>
9+
</div>
10+
</body>
11+
</html>
Binary file not shown.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
using Syncfusion.DocIO;
2+
using Syncfusion.DocIO.DLS;
3+
using System.Collections.Generic;
4+
using System.Data;
5+
using System.IO;
6+
7+
namespace Replace_merge_field_with_HTML
8+
{
9+
class Program
10+
{
11+
static Dictionary<WParagraph, Dictionary<int, string>> paraToInsertHTML = new Dictionary<WParagraph, Dictionary<int, string>>();
12+
static void Main(string[] args)
13+
{
14+
// Open the template Word document.
15+
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite))
16+
{
17+
using (WordDocument document = new WordDocument(fileStream, FormatType.Docx))
18+
{
19+
//Creates mail merge events handler to replace merge field with HTML.
20+
document.MailMerge.MergeField += new MergeFieldEventHandler(MergeFieldEvent);
21+
//Gets data to perform mail merge.
22+
DataTable table = GetDataTable();
23+
//Performs the mail merge.
24+
document.MailMerge.Execute(table);
25+
//Append HTML to paragraph.
26+
InsertHtml();
27+
//Removes mail merge events handler.
28+
document.MailMerge.MergeField -= new MergeFieldEventHandler(MergeFieldEvent);
29+
// Save the modified document.
30+
using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
31+
{
32+
document.Save(outputStream, FormatType.Docx);
33+
}
34+
}
35+
}
36+
}
37+
38+
#region Helper methods
39+
/// <summary>
40+
/// Replaces merge field with HTML string by using MergeFieldEventHandler.
41+
/// </summary>
42+
/// <param name="sender"></param>
43+
/// <param name="args"></param>
44+
public static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
45+
{
46+
if (args.TableName.Equals("HTML"))
47+
{
48+
if (args.FieldName.Equals("ProductList"))
49+
{
50+
//Gets the current merge field owner paragraph.
51+
WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
52+
//Gets the current merge field index in the current paragraph.
53+
int mergeFieldIndex = paragraph.ChildEntities.IndexOf(args.CurrentMergeField);
54+
//Maintain HTML in collection.
55+
Dictionary<int, string> fieldValues = new Dictionary<int, string>();
56+
fieldValues.Add(mergeFieldIndex, args.FieldValue.ToString());
57+
//Maintain paragraph in collection.
58+
paraToInsertHTML.Add(paragraph, fieldValues);
59+
//Set field value as empty.
60+
args.Text = string.Empty;
61+
}
62+
}
63+
}
64+
/// <summary>
65+
/// Gets the data to perform mail merge
66+
/// </summary>
67+
/// <returns></returns>
68+
private static DataTable GetDataTable()
69+
{
70+
DataTable dataTable = new DataTable("HTML");
71+
dataTable.Columns.Add("CustomerName");
72+
dataTable.Columns.Add("Address");
73+
dataTable.Columns.Add("Phone");
74+
dataTable.Columns.Add("ProductList");
75+
DataRow datarow = dataTable.NewRow();
76+
dataTable.Rows.Add(datarow);
77+
datarow["CustomerName"] = "Nancy Davolio";
78+
datarow["Address"] = "59 rue de I'Abbaye, Reims 51100, France";
79+
datarow["Phone"] = "1-888-936-8638";
80+
//Reads HTML string from the file.
81+
string htmlString = File.ReadAllText(Path.GetFullPath(@"Data/File.html"));
82+
datarow["ProductList"] = htmlString;
83+
return dataTable;
84+
}
85+
/// <summary>
86+
/// Append HTML to paragraph.
87+
/// </summary>
88+
private static void InsertHtml()
89+
{
90+
//Iterates through each item in the dictionary.
91+
foreach (KeyValuePair<WParagraph, Dictionary<int, string>> dictionaryItems in paraToInsertHTML)
92+
{
93+
WParagraph paragraph = dictionaryItems.Key as WParagraph;
94+
Dictionary<int, string> values = dictionaryItems.Value as Dictionary<int, string>;
95+
//Iterates through each value in the dictionary.
96+
foreach (KeyValuePair<int, string> valuePair in values)
97+
{
98+
int index = valuePair.Key;
99+
string fieldValue = valuePair.Value;
100+
//Inserts HTML string at the same position of mergefield in Word document.
101+
paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index);
102+
}
103+
}
104+
paraToInsertHTML.Clear();
105+
}
106+
#endregion
107+
}
108+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<RootNamespace>Replace_merge_field_with_HTML</RootNamespace>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
11+
</ItemGroup>
12+
13+
<ItemGroup>
14+
<None Update="Data\File.html">
15+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
16+
</None>
17+
<None Update="Data\Template.docx">
18+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
19+
</None>
20+
<None Update="Output\.gitkeep">
21+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
22+
</None>
23+
</ItemGroup>
24+
25+
</Project>

0 commit comments

Comments
 (0)