TX Text Control .NET Server

MailMerge

Topic

MailMerge creates documents such as invoices, letters, contracts and reports from a template and data. Find out what the class does, how templates and data fit together, where it runs and which classes you work with. Your first merge is a tutorial in Getting Started: Mail Merge.

What MailMerge Is

MailMerge is a .NET component in the TXTextControl.DocumentServer namespace that merges template documents with data. It is derived from System.ComponentModel.Component and is included in both TX Text Control engine packages, TXTextControl.TextControl.Core.SDK and TXTextControl.TextControl.ASP.SDK.

MailMerge does not hold a document itself. Its TextComponent property connects it to a ServerTextControl that contains the template. After the merge, the merged document is in the same ServerTextControl, and you save it as PDF, DOCX or another supported format.

What You Do With It

  • Generate business documents such as invoices, quotes, contracts, letters and reports from data in your application.
  • Create PDF documents from MS Word compatible templates, for example for archiving, sharing or electronic signing.
  • Offer document generation as a service, for example a Web API endpoint that receives a template and JSON data and returns a PDF.
  • Prepare forms. Merge known data into a template with form fields, and let users complete the remaining fields in the Document Viewer.

How a Merge Works

Every merge has the same three parts: a template, the data, and a MailMerge instance that brings them together. You load the template into a ServerTextControl, connect MailMerge to it through the TextComponent property, call a merge method and save the document:

using TXTextControl;
using TXTextControl.DocumentServer;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    // load a DOCX template and import its MS Word fields
    LoadSettings loadSettings = new LoadSettings
    {
        ApplicationFieldFormat = ApplicationFieldFormat.MSWord,
        LoadSubTextParts = true
    };

    tx.Load("template.docx", StreamType.WordprocessingML, loadSettings);

    // merge JSON data into the template
    using (MailMerge mailMerge = new MailMerge { TextComponent = tx })
    {
        mailMerge.MergeJsonData(File.ReadAllText("data.json"));
    }

    // save the merged document as PDF
    tx.Save("output.pdf", StreamType.AdobePDF);
}

MailMerge also provides its own methods to load a template (LoadTemplate) and to save the merged document (SaveDocument).

TX Text Control uses pre-shaped data: you prepare the data in the hierarchy the document needs, for example as a JSON file or a business object built from several sources, instead of letting the template run queries. The data then controls the output. By default, a merge field without matching data is removed from the document, and so is a merge block without data. Pre-Shaped Data explains the concept.

Templates

A template is a regular document with static content and placeholders for the data. Business users design it in MS Word or in the Document Editor, and developers can also create it in code. Templates are typically stored as DOCX files or in the internal TX Text Control format. The formatting of the placeholders is preserved when data is merged.

Template elementWhat it does
Merge fieldA placeholder for a single value, such as a customer name. Merge fields are MS Word compatible MERGEFIELD fields. Dot notation such as Customer.CustomerName reaches values in nested objects, and fields can add text before and after the value and format numbers and dates.
Merge blockA section that is repeated for each record of a collection, for example a table row for each invoice line item. Blocks can be nested for master-detail reports, and their rows can be sorted and filtered. In the document, a merge block is a SubTextPart whose name is the prefix txmb_ followed by the block name.
Block for a single objectA merge block bound to a nested object instead of an array. It is merged once if the object exists in the data and removed if it is missing, which makes it a simple way to include optional sections.
Image merge fieldA merge field whose name is prefixed with image:, which is merged as an image.
Form fieldDepending on the FormFieldMergeType property, form fields are not merged, preselected, or replaced with a value from the data. By default, they are not merged.

In the Document Editor, users insert merge fields and merge blocks from the Reporting ribbon tab, which lists the names found in JSON data that you load into the editor. In code, the MergeField class inserts merge fields, and the DataSourceManager class analyzes a data source and inserts complete merge blocks.

When you load a DOCX template for merging, set LoadSettings.ApplicationFieldFormat to ApplicationFieldFormat.MSWord so that its merge fields are imported, and LoadSettings.LoadSubTextParts to true so that its merge blocks are loaded.

Data Sources

MailMerge provides a merge method for each kind of data:

MethodData
MergeJsonDataA JSON string with a single object or an array of equally structured objects
MergeObjectA single object of any type
MergeObjectsAn IEnumerable collection of objects, or of Dictionary instances with string keys
MergeA System.Data.DataTable, whose related tables in the DataSet fill the merge blocks of the same name

The reference also lists Merge() and Merge(bool append) without a DataTable. They merge the data of a Report Data Source Configuration file, a Windows Forms feature that .NET Server applications don't use, as Data Sources explains.

With business objects, MailMerge reads the public properties through .NET reflection: properties become merge fields, and properties of type IEnumerable become merge blocks. For an array or collection with several records, the template is merged once per record, and by default all results are appended to one document.

Control the Merge Result

Properties of MailMerge change how the merge treats fields, blocks and whitespace: by default, RemoveEmptyFields and RemoveEmptyBlocks remove fields and blocks that receive no data, UseTemplateFormat decides whether the page size and margins of the template are used, and MergeCulture sets the culture of numbers and dates. Control the Merge Result lists these properties with their defaults.

Events let your code react during the merge. For example, FieldMerged occurs when a field has been merged and tells you whether it was merged successfully, and BlockRowMerged lets you change the content or formatting of a merged row in a repeating block.

Where MailMerge Runs

MailMerge runs wherever ServerTextControl runs: in console applications, services, ASP.NET Core applications and Web APIs. With the Core package, the same code runs on Windows and Linux, including Docker containers.

Generating a large document with many nested merge blocks and hundreds or thousands of pages can take several seconds or longer. For such jobs, consider processing them in a background task instead of within the HTTP request. For high-volume workloads, the TXTextControl.DocumentServer.ParallelMailMerge package on nuget.org sends merge jobs to isolated worker processes in parallel. The blog article Create 100,000 Documents in Under an Hour with Parallel MailMerge in .NET C# describes it.

Key Classes

ClassNamespacePurpose
MailMergeTXTextControl.DocumentServerMerges data into the template held by a ServerTextControl
ServerTextControlTXTextControlHolds the template and the merged document, and loads and saves them
LoadSettingsTXTextControlImports the merge fields and merge blocks of a DOCX template
MergeFieldTXTextControl.DocumentServer.FieldsCreates and changes merge fields, including their text before and after and their formats
DataSourceManagerTXTextControl.DocumentServer.DataSourcesAnalyzes a data source, lists the tables and columns you can use as merge blocks and merge fields, and inserts merge blocks
MergeBlockInfoTXTextControl.DocumentServer.DataSourcesDescribes a merge block, including its sorting and filter instructions

Next Steps