How to Generate Invoices from XML Data using Mail Merge in a .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 generate invoices from XML data using mail merge in a Word document using C#.
Overview of the Mail Merge Logic:
- Load the template Word document.
- Enable the option to start each mail merge record on a new page.
- Read the XML file into an XmlDocument and Convert nodes into dynamic objects for flexible access.
- Extract invoice data from the dynamic object.
- Prepare the mail merge data source.
- Execute the nested mail merge.
- Save and close the document.
Steps to generate invoices from XML data using mail merge in a Word document:
- Create a new .NET Core console application project.
- Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
Note:
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a 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 a trial message.
- Include the following namespaces in the Program.cs file.
C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using System.Dynamic;
using System.Xml;
- Use the following code example to generate invoices from XML data using mail merge in a Word document.
C#
// Load the template Word document
WordDocument document = new WordDocument(Path.GetFullPath(@"Data/Template.docx"));
// start each record at new page
document.MailMerge.StartAtNewPage = true;
// Perform mail merge using relational XML data
document.MailMerge.ExecuteNestedGroup(GetRelationalData());
// Save the result Word document.
document.Save(Path.GetFullPath("../../../Output/Output.docx"));
// Close the Word document
document.Close();
- Use the following code example to prepare the mail merge data source from XML.
C#
private static MailMergeDataTable GetRelationalData()
{
// Load the XML data file
Stream xmlStream = File.OpenRead(Path.GetFullPath(@"Data/InvoiceDetails.xml"));
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(xmlStream);
xmlStream.Dispose();
ExpandoObject customerDetails = new ExpandoObject();
GetDataAsExpandoObject((xmlDocument as XmlNode).LastChild, ref customerDetails);
// Convert dynamic object into dictionary
IDictionary<string, object> customerDict = customerDetails as IDictionary<string, object>;
// Get the "Invoices" list
List<ExpandoObject> invoicesList = customerDict["Invoices"] as List<ExpandoObject>;
// Take the first item in that list
IDictionary<string, object> firstInvoiceGroup = invoicesList[0] as IDictionary<string, object>;
// Get the "Invoice" list from that group
List<ExpandoObject> invoices = firstInvoiceGroup["Invoice"] as List<ExpandoObject>;
// Create MailMergeDataTable with group name "Invoices"
MailMergeDataTable dataTable = new MailMergeDataTable("Invoices", invoices);
return dataTable;
}
- Use the following code example to convert XML nodes into dynamic objects.
C#
private static void GetDataAsExpandoObject(XmlNode node, ref ExpandoObject dynamicObject)
{
if (node.InnerText == node.InnerXml)
// Leaf node: store text value
dynamicObject.TryAdd(node.LocalName, node.InnerText);
else
{
// Handle child nodes
List<ExpandoObject> childObjects;
// If the tag already exists, reuse the list; otherwise create a new one
if ((dynamicObject as IDictionary<string, object>).ContainsKey(node.LocalName))
childObjects = (dynamicObject as IDictionary<string, object>)[node.LocalName] as List<ExpandoObject>;
else
{
childObjects = new List<ExpandoObject>();
dynamicObject.TryAdd(node.LocalName, childObjects);
}
// Create a new child object for the current node
ExpandoObject childObject = new ExpandoObject();
// Recursively process all child nodes
foreach (XmlNode childNode in (node as XmlNode).ChildNodes)
{
GetDataAsExpandoObject(childNode, ref childObject);
}
// Add the processed child object to the list
childObjects.Add(childObject);
}
}
You can download a complete working sample to generate invoices from XML data using mail merge in a Word document from GitHub.
Final Output Image: Template Invoice, XML Data, and Final Invoices
Take a moment to peruse the documentation where you can find basic Word document processing options along with 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 generate invoices from XML data using 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 with 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!