Products Technologies Demo Docs Blog Support Company

Using MailMerge with JSON Data

Merge document templates with JSON data using TX Text Control MailMerge by converting nested JSON strings into DataSet objects via Newtonsoft.Json. The JSON is first transformed to XML, then loaded as a DataSet that MailMerge processes through its standard pipeline with relations intact.

Using MailMerge with JSON Data

In the last article, we explained how to create an ASP.NET Web API to merge templates with JSON data in the payload body of an HTTP request. The focus of this article was on the Web API and RESTful services itself.

Extracted from this project, this sample shows how to merge a template with a JSON string directly. The JSON data string has the following form:

{
   "orders":{
      "order":[
         {
            "Id":"10",
            "address":{
               "street":"9774 Kings Drive",
               "city":"Charlotte"
            },
            "phone":"123 898 2298",
            "date":"05/12/2015",
            "total":"1526.88",
            "item":[
               {
                  "name":"Thin-Jam Hex Nut 4",
                  "price":"337.22",
                  "qty":"1",
                  "itemtotal":"337.22"
               },
               {
                  "name":"ML Road Frame - Red, 58",
                  "price":"594.83",
                  "qty":"2",
                  "itemtotal":"1189.66"
               }
            ]
         }
      ]
   }
}

It is the JSON representation of a flat XML file with nested data tables created with Newtonsoft.Json:

// load the data as XML
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("sample_db.xml"));

// the Web API expects the data as a JSON object
// 'JsonConvert' converts the XML to the required JSON format
string jsonText = JsonConvert.SerializeXmlNode(doc);

The following method accepts a template name and the JSON string as parameters. The JSON string is converted back to an XML file which is then converted to a DataSet object.

private void MergeTemplate(string templateName, string JsonData)
{
    // creating a new ServerTextControl and MailMerge class
    using (ServerTextControl tx = new ServerTextControl())
    {
        tx.Create();
        MailMerge mailMerge = new MailMerge();
        mailMerge.TextComponent = tx;

        // load the template
        mailMerge.LoadTemplate(Server.MapPath("templates/" + templateName),
            FileFormat.InternalUnicodeFormat);

        // create a new DataSet object
        DataSet ds = new DataSet();
        XmlDocument doc;

        // convert the JSON string to an XML document
        // object using Newtonsoft.Json
        try
        {
            doc = JsonConvert.DeserializeXmlNode(JsonData);
            lblError.Visible = false;
        }
        catch (Exception exc)
        {
            lblError.Visible = true;
            lblError.Text = exc.Message;
            DocumentViewer1.Visible = false;
            return;
        }

        // convert the XML to a DataSet
        XmlNodeReader reader = new XmlNodeReader(doc);
        ds.ReadXml(reader, XmlReadMode.Auto);

        // merge the template with the DataSet
        mailMerge.Merge(ds.Tables[0]);

        // load the resulting document into the DocumentViewer
        byte[] data;
        mailMerge.SaveDocumentToMemory(out data, BinaryStreamType.InternalUnicodeFormat, null);
        DocumentViewer1.LoadDocumentFromMemory(data, FileFormat.InternalUnicodeFormat);
    }
}

Finally, the document is merged by calling the Merge method. The resulting document is loaded into the ASP.NET DocumentViewer for visualization.

Using MailMerge with JSON data

Download the sample from GitHub and test it on your own.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • Visual Studio 2012 or better
  • TX Text Control .NET Server (trial sufficient)

Reporting

The Text Control Reporting Framework combines powerful reporting features with an easy-to-use, MS Word compatible word processor. Users can create documents and templates using ordinary Microsoft Word skills. The Reporting Framework is included in all .NET based TX Text Control products including ASP.NET, Windows Forms and WPF.

See Reporting products

Related Posts

ASP.NETReportingGitHub

Merging Documents with RESTful Web API's

Build a RESTful ASP.NET Web API endpoint that accepts a TX Text Control template in InternalUnicodeFormat and a JSON data object, then executes a server-side MailMerge to return the merged…


ASP.NETReportingHTML5

Creating Your First ASP.NET Reporting Application

The MailMerge and ServerTextControl components of TX Text Control .NET Server for ASP.NET enable server-side reporting in Web Forms. A template.docx merges with XML data via a button click…


ASP.NETReportingTutorial

New Online Sample: Build your First Report

A new interactive online demo walks through building a report with TX Text Control in three steps: preparing JSON data in a live editor, creating a template with merge fields and repeating blocks,…


ReportingDocumentationReportingCloud

Create your First Document with ReportingCloud

ReportingCloud documentation now includes interactive tutorials for creating documents without code. Users enter an API key, choose a format such as PDF or DOCX, customize the merge data payload,…


ReportingReportingCloudWeb API

Text Control as a Service: Outsource Your Document Processes

ReportingCloud provides TX Text Control document processing as a cloud service, merging JSON data into MS Word templates and exporting to PDF, PDF/A, or DOCX via Web APIs. Consulting services…

Share on this blog post on: