How to Merge Two Records Per Page during Mail Merge in ASP.NET Word?
Syncfusion® Essential® DocIO is a ASP.NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can merge two records per page during mail merge in a Word document using C#.
To achieve this, follow the steps below:
- Retrieve the data table from a JSON file and assign group name to the data table.
- Extract the first and last paragraphs from the template Word document.
- Set the StartAtNewPage Boolean property as true to start each record on new page and by adding page break.
- Perform the mail merge using the ExecuteGroup API.
- After merging, delete only odd page breaks to ensure exactly two records appear on each page without extra blank pages.
Steps to merge two records per page during 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.
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from 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 trail message.
- Include the following namespaces in Program.cs file
C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
- Include the following properties.
C#
static int count = 0; // Counter for page breaks.
static WParagraph endPara; // Variable to store the end paragraph.
static int index; // Index for the beginning paragraph.
- Use the following code example to merge two records per page during mail merge in a Word document.
C#
// Opens the template document
using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Automatic))
{
// Get the beginning paragraph where group starts.
TextSelection selection = document.Find("BeginGroup:Employees", true, true);
WParagraph beginPara = selection.GetAsOneRange().OwnerParagraph;
// Get the end paragraph where group ends.
TextSelection endSelection = document.Find("EndGroup:Employees", true, true);
endPara = endSelection.GetAsOneRange().OwnerParagraph.NextSibling as WParagraph;
// Start each record on a new page during mail merge.
document.MailMerge.StartAtNewPage = true;
// Execute the group mail merge
document.MailMerge.ExecuteGroup(GetDataTable());
// Get index of the beginning paragraph for iteration.
index = beginPara.OwnerTextBody.ChildEntities.IndexOf(beginPara);
// Remove odd page breaks in document.
IterateTextBody(beginPara.OwnerTextBody);
// Save the result to a file.
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
document.Save(outputFileStream, FormatType.Docx);
}
}
}
- Use the following helper method to iterate through the child entities of a WTextBody to process paragraphs, tables, and block content controls.
C#
// Method to iterate through the text body and handle elements.
static void IterateTextBody(WTextBody textBody)
{
// Loop through each entity in the text body (paragraphs, tables, etc.).
for (int i = index; i < textBody.ChildEntities.Count; i++)
{
IEntity bodyItemEntity = textBody.ChildEntities[i];
switch (bodyItemEntity.EntityType)
{
case EntityType.Paragraph:
WParagraph paragraph = bodyItemEntity as WParagraph;
// Process paragraph unless it's the end paragraph.
if (paragraph != endPara)
IterateParagraph(paragraph.Items, paragraph);
break;
case EntityType.Table:
// Process tables.
IterateTable(bodyItemEntity as WTable);
break;
case EntityType.BlockContentControl:
BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl;
// Iterate through body items in block content control.
IterateTextBody(blockContentControl.TextBody);
break;
}
}
- Use the following helper method to iterate through the rows and cells of a table.
C#
// Method to iterate through the table rows and cells.
static void IterateTable(WTable table)
{
// Loop through rows and cells in a table.
foreach (WTableRow row in table.Rows)
{
foreach (WTableCell cell in row.Cells)
{
// Reuse text body iteration logic for table cells.
IterateTextBody(cell);
}
}
}
- Use the following helper method to remove page break.
C#
// Method to iterate through paragraphs and remove page breaks.
static void IterateParagraph(ParagraphItemCollection paraItems, WParagraph paragraph)
{
if (paragraph != null)
{
// Loop through the paragraph items in reverse order to check for page breaks.
for (int i = paraItems.Count - 1; i >= 0; i--)
{
ParagraphItem item = paraItems[i];
if (item is Break && (item as Break).BreakType == BreakType.PageBreak)
{
count++; // Count the page break.
if (count % 2 != 0)
paraItems.Remove(item); // Remove the page break if count is odd.
}
}
}
}
- Use the following helper method to get data from a JSON file and convert it to a DataTable.
C#
// Method to get data from a JSON file and convert it to a DataTable for mail merge.
private static DataTable GetDataTable()
{
string jsonString = File.ReadAllText(Path.GetFullPath(@"../../../Data/Data.json"));
DataTable dataTable = new DataTable("Employees");
JObject json = JObject.Parse(jsonString);
bool columnsAdded = false;
foreach (var item in json["Employees"])
{
// Add columns once.
if (!columnsAdded)
{
foreach (JProperty property in item)
{
dataTable.Columns.Add(property.Name, typeof(string));
}
columnsAdded = true;
}
// Add rows to DataTable.
DataRow row = dataTable.NewRow();
foreach (JProperty property in item)
{
row[property.Name] = property.Value.ToString();
}
dataTable.Rows.Add(row);
}
return dataTable;
}
You can download a complete working sample to merge two records per page during mail merge in a Word document from the GitHub.
By executing the program, you will get the Word document as follows.
Take a moment to peruse the documentation where you can find basic Word document processing options along with the 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 merge two records per page during mail merge in ASP.NET Word.
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 for 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!