Document Studio .NET
Next-generation .NET compliant multi-format document viewing & processing suite for .NET developers
Compatibility
Visual Studio 2013/2015/2017/2019

Create DOCX, DOC, PDF and images using mail-merge in .NET

Learn to use the latest mail-merge functionality in Document Studio .NET.

Mail merge was a word-processing feature originally popularized by software such as WordStar and WordPerfect. In very simple terms, it is the ability to create multiple copies of the same document where certain pre-defined placeholders are replaced in each copy with a set of values picked up from another document or data source. A typical mail-merge scenario would be for a company to send a common letter to all its customers. For this, a template document is prepared. It would contain the contents of the letter that is same for all recipients. The places where the names or addresses need to appear would be left empty but marked with certain placeholders. When the mail-merge operation is performed, the placeholders would be replaced with individual customer details kept in another document as rows of delimited data. In Microsoft Word, the placeholders are called merge-fields and the merge-field data can be picked up from a variety of sources such as spreadsheets or databases. When mail merge is performed by code, many more data sources can be used.

Mail Merge with Document Studio .NET

In November last year, we previewed the mail merge functionality in Document Studio. It it is now available as a full-fledged feature.

Design Goals

After a few brainstorming sessions, we decided that the functionality should be available as simple as possible and also as versatile as the user wants it to be. Here are the design goals that we came up with:

Rather than tacking the mail-merge functionality on the IDocument interface, we came up with a MailMerge utility class with a very simple API. With a new MailMerge instance, the developer would only need to specify the input template and connect it to a data source to get the mail merge function ready to roll. For those, who need more than the default functionality, several optional features and event hooks are also provided. We also introduced a IMailMergeSource interface that developers could implement to integrate custom and non-standard data sources.

A Mail-Merge Demo

To see how this mail-merge function works, here is an example.

For the sake of simplicity, the NorthWind database that is shipped with MS Access has been used in this example. (NorthWind database is also shipped with SQL Server and you could use that too.) The Customers table in the database will be used in conjunction with a DOCX template document. To keep the list short, the table had been filtered to customers from Germany, a total of 11 records.

SELECT ContactName, Address, City, PostalCode, Country
FROM Customers
WHERE Country='Germany'
ORDER BY ContactName;
The data source for the merge operation is a DataTable created from an Access database.

Then, a DOCX template document was created in MS Word. Some merge-fields with the same name as the column names from the Customers table were also inserted in appropriate places.

A template document with two pages was created. MergeFields with same names as the column names from the DataTable were used in the template

Then, in Visual Studio, a Windows Forms project was created. The MDB database file and the template document were then copied to the Debug/Release folder to eliminate the need to specify absolute pathnames. A button-click handler did the mail merge.

private void button1_Click(object sender, EventArgs e) {
  try {
    // Initialize mail-merge
    MailMerge mm = new MailMerge();

    // Specify mail-merge template document
    mm.TemplateFileName = "letter_envelope_template.docx";      

    // Set up data source
    DataSet ds = new DataSet();
    OleDbConnection conn = 
      new OleDbConnection(
             "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FPNWIND.MDB");
    conn.Open();
    OleDbDataAdapter da =
        new OleDbDataAdapter(
            "SELECT ContactName, Address, City, PostalCode, Country " +
            " FROM Customers " + 
            " WHERE Country='Germany' " +
            " ORDER BY ContactName",
             conn);
    da.Fill(ds);
    DataTable dt = ds.Tables[0];

    // Specify mail-merge input data
    mm.DataSource = dt; 
    
    // Set unfilled fields to be removed
    mm.MailMergeCleanupOptions = MailMergeCleanupOptions.RemoveUnmappedFields; 

    // Set handler for EndJob event to show the final result
    mm.EndJob += mm_EndJob;
    
    // Mail-merge template document with data
    mm.Merge(
        new SaveToFileAction(
            Environment.CurrentDirectory, 
            "Letter to {{ContactName}}"));

    // Clean up
    conn.Close();

  } catch (Exception err) {
    MessageBox.Show(err.Message.ToString());
  }            
}

void mm_EndJob(object sender, MailMergeEndJobEventArgs e) {
  MessageBox.Show(
      e.Result.SucceededCount + " documents created!\n" +
      e.Result.FailedCount + " documents failed!\n" +
      e.Result.SkippedCount + " documents skipped!\n");
}

When the button is clicked, the application created 11 output documents.

This animation shows the documents that were created as the output of the merge operation.
This animation shows the output folder.

The Merge() command requires a post-merge action. Here you can specify if the output document needs to be saved to a file or a stream or just sent as an e-mail attachment. It could also be saved to a custom document format that you have derived from IDocument.

Another novel feature in the Merge() command is the ability to specify merge-fields in the output file names too in the same way that you specify them in the template document.

Events

The MailMerge class provides several events that provide you more control over the entire mail-merge operation. The EndJob event has been used in the code example given above. To provide a non-disruptive performance, the Merge() method returns without issue. Errors encountered by it are available only if you handle the Error event.

Merge Input

MailMerge accepts merge input data from a variety of sources, namely:

IDynamicMailMergeSource is meant for your custom data sources. Just implement its methods to supply data from your exquisite data store implementations. ☺

Merge Template

The merge template document can be in one of several formats. Currently, MailMerge supports:

Output Formats

Currently, MailMerge can generate documents in the following formats. In future, more formats will be supported.

---o0O0o---

Our .NET Developer Tools
Gnostice Document Studio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
Gnostice Document Studio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
Gnostice Document Studio Java

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2024 Gnostice Information Technologies Private Limited. All rights reserved.