Creating Mail Merge Documents in C# with NOV Rich Text Editor

Introduction

Mail merge separates the document design from business data. It is commonly used to automatically create personalized bulk emails or letters.

The process behind mail merge is rather simple:

First, the document author creates a template in some common Word format like DOCX or RTF. This template contains placeholders called fields, which should be populated differently for each individualized e-mail or letter. Commonly, fields contain information about the recipient’s name, address, telephone, or other individualizing data.

The next step is to merge the template with data extracted from a data source. This is done for each record in the data source, by populating the fields in the template that map to the values in each record.

Then the document is laid out and exported to the target format or e-mailed, and the process returns to the previous step until all records are processed.

NOV Rich Text Editor supports mail merge data fields, greeting lines, field mappings, merge document generation, and common data sources including Access databases, Excel spreadsheets, and CSV files.

Creating the Document Template

The content and code excerpts of this article follow directly the mail merge example shipped with the NOV installation and add some brief descriptions.

During the document construction, the code uses the CreateMergeField to add a template placeholder:

private static NFieldInline CreateMailMergeField(NMailMergeFieldValue value)
{
	NFieldInline fieldInline = new NFieldInline(value);
	fieldInline.FontStyle = ENFontStyle.Bold;
	return fieldInline;
}
								

Then the example creates a few sample paragraphs that contain fields that are about to be populated from a database:

NParagraph paragraph = new NParagraph();
paragraph.Inlines.Add(new NTextInline("We would like to offer you a unique software component that will help you leverage multiple platforms with single code base. We believe that as a "));
paragraph.Inlines.Add(CreateMailMergeField(new NMailMergeSourceFieldValue("Title")));
paragraph.Inlines.Add(new NTextInline(" in your company you will be very interested in this solution. If that's the case do not hesitate to contact us in order to arrange a meeting in "));
paragraph.Inlines.Add(CreateMailMergeField(new NMailMergePredefinedFieldValue(ENMailMergeDataField.City)));
paragraph.Inlines.Add(new NTextInline("."));
section.Blocks.Add(paragraph);
								

You can also, of course, create the document template from the user interface and not programmatically, which is also completely supported by the control. This involves the usual creation of a rich text view and then loading the document from a specified location:

									NRichTextView richTextView = new NRichTextView();

									richTextView.LoadFromLocalFile(@"C:\Templates\Customer-Letter.docx");
								

Merge the Template with Data

The next step is to merge the document template with the data. This involves two steps:

First, you need to create the data source - NOV Rich Text Editor supports database, CSV file, Excel file, and memory table data sources for the input data. The example uses CSV as the data source for example:

NMailMergeDataSource dataSource = new NCsvDataSource(new NFile("c://mailmergedata//data.csv"));
								

After you create the data source, you need to create a mapping that defines how the columns in the data source map to template fields:

// Create the field mappings
NMailMergeFieldMap fieldMap = new NMailMergeFieldMap();

fieldMap.Set(ENMailMergeDataField.CourtesyTitle, "TitleOfCourtesy");
fieldMap.Set(ENMailMergeDataField.FirstName, "FirstName");
fieldMap.Set(ENMailMergeDataField.LastName, "LastName");
fieldMap.Set(ENMailMergeDataField.City, "City");
dataSource.FieldMap = fieldMap;
								

Then you assign the data source to the document using the DataSource property.

richTextView.Content.MailMerge.DataSource = dataSource;
								

That's it; now we're ready to create bulk documents, which in this case are sample notification letters.

Generating the Batch of Mail Merge Documents

The final step is to generate the batch of mail merge documents. This is done by looping through the data source records and saving a separate document for each record in the data source:

string targetPath = "c:\\temp\\";
// Switch the mail merge of the cloned rich text view to preview mode
NMailMerge mailMerge = richTextView.Content.MailMerge;
mailMerge.PreviewMailMerge = true;

// Loop through all mail merge records to save individual documents to file
for (int i = 0; i < mailMerge.DataRecordCount; i++)
{
	// Move to the next data source record
	mailMerge.CurrentDataRecordIndex = i;

	// Save the merged document to file
	string fileName = "Document" + i.ToString(CultureInfo.InvariantCulture) + ".docx";
	clonedRichTextView.SaveToLocalFile(NPath.Current.Combine(targetPath, fileName));
}
			

From an automation standpoint, it does not matter if you generate DOCX, RTF or PDF files, and the choice of target format is based purely on the application and the expected users of the generated bulk of documents.

Conclusion

NOV Rich Text Editor combines MS Word-like mail merge features and export to multiple widely accepted text formats. This enables C# applications to generate personalized letters, contracts, notices, and reports without Microsoft Office automation.

About Nevron Software

Founded in 1998, Nevron Software is a component vendor specializing in the development of premium presentation layer solutions for .NET-based technologies. Today, Nevron has established itself as a trusted partner worldwide for .NET LOB applications, SharePoint portals, and reporting solutions. Nevron technology is used by many Fortune 500 companies, large financial institutions, global IT consultancies, academic institutions, governments, and non-profits.
For more information, visit: www.nevron.com.
  
Nevron Chart for WinForms is a first-class product. Its wide range of possibilities, looks, settings and other options gives you a very powerful tool to support your own application and to make end user a superb presenter. This product’s price/performance ratio is the best in its segment. It seems that only limitation is the one from the user.
  

Bostjan Maljevec
Eunomia