Products Technologies Demo Docs Blog Support Company

Implementing Conditional Table Cell Colors with MailMerge

The MailMerge class provides an extensible framework to inject custom logic to the merge process. This ASP.NET MVC sample shows how to implement conditional table cell colors using the online document editor and an ASP.NET backend.

Implementing Conditional Table Cell Colors with MailMerge

MailMerge is a powerful, extensible framework that allows you to inject custom logic to the merge process. The TXTextControl.DocumentServer.MailMerge.FieldMerged event can be used to manipulate the results, but also gives access to the surrounding instance of the TXTextControl.TableCell class.

This enables you to implement features such as conditional table cell colors based on specific filter instructions.

In this sample, the table cell Qty should be highlighted red, if quantity is higher than 10, otherwise it should be green.

Conditional Cells

This sample shows two interesting aspects:

  • It shows how to use the JavaScript API to store data in the TableCell object.

  • And it illustrates how to merge the created document server-side using MailMerge.

The sample implements HTML form elements to set the conditions for table cells. If the input position is inside a table cell, the following code is used to store the conditions in the table cell by serializing the object as a Json string:

// stores the selected conditions in the cell name
function setTableCellConditions(empty = false) {

    TXTextControl.tables.getItem(function (table) {

        if (table === null)
            return; // no table

        // create a cellFilterInstructions object
        var cellFilterInstructions = {
            compareValue: document.getElementById("compareValue").value,
            operator: document.getElementById("operator").value,
            trueColor: document.getElementById("trueColor").value,
            falseColor: document.getElementById("falseColor").value
        }

        table.cells.getItemAtInputPosition(function (cell) {

            if (cell === null)
                return; // no cell

            if (empty === true)
                cell.setName(""); // delete instructions
            else
                // sel instructions to cell name
                cell.setName(JSON.stringify(cellFilterInstructions));

        });

    })
}

If the input position is changed to another cell, the form elements are updated to reflect the conditions of that cell:

// check cell status on input position changes
TXTextControl.addEventListener("inputPositionChanged", function () {
    TXTextControl.tables.getItem(function (table) { // table at input pos?

        if (table === null) { // return if no table available
            EnableFormElements(
                ["operator", "compareValue", "trueColor", "falseColor", "enableCondition"],
                false); return;
        }

        // enable form elements
        EnableFormElements(
            ["operator", "compareValue", "trueColor", "falseColor", "enableCondition"],
            true);

        table.cells.getItemAtInputPosition(function (cell) { // cell at input pos

            if (cell == null) { // return if more cells are selected
                enableCellConditions(false);
                document.getElementById("enableCondition").setAttribute(
                    "disabled", "disabled");
                return;
            }

            // check the cell name that stores the conditions
            cell.getName(function (cellName) {
                if (cellName === "") { enableCellConditions(false); return; }
                updateSettings(JSON.parse(cellName));
            });
        });

    })
});

Finally, when clicking Merge, the document is saved and sent to the backend controller:

function mergeDocument() {
    TXTextControl.saveDocument(TXTextControl.streamType.InternalUnicodeFormat,
        function (e) {
            var serviceURL = "/Home/MergeDocument";

            $.ajax({
                type: "POST",
                url: serviceURL,
                contentType: 'application/json',
                data: JSON.stringify({
                    Document: e.data,
                }),
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {
                TXTextControl.loadDocument(TXTextControl.streamType.InternalUnicodeFormat, data);
            }

            function errorFunc(error) {
                console.log(error);
            }
        });
}

In the controller, an HttpPost method accepts the document and calls the MergeJsonData method to merge data into the given template:

[HttpPost]
public string MergeDocument(string Document)
{
    using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl())
    {
        tx.Create();
        tx.Load(Convert.FromBase64String(Document), 
                TXTextControl.BinaryStreamType.InternalUnicodeFormat);

        using (TXTextControl.DocumentServer.MailMerge mailMerge = 
               new TXTextControl.DocumentServer.MailMerge())
        {
            mailMerge.TextComponent = tx;
            mailMerge.FieldMerged += MailMerge_FieldMerged;

            string data = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/data.json"));
            mailMerge.MergeJsonData(data, false);
        }

        byte[] results;

        tx.Save(out results, TXTextControl.BinaryStreamType.InternalUnicodeFormat);
        return Convert.ToBase64String(results);
    }
}

The FieldMerged event is attached to handle the custom condition. If the field is inside a table cell, the TableCell.Name property is deserialized to a CellFilterInstructions object in order to apply the table cell color according to the defined instructions.

private void MailMerge_FieldMerged(object sender, 
  TXTextControl.DocumentServer.MailMerge.FieldMergedEventArgs e)
{
    // custom field handling
    if (e.TableCell == null)
        return;

    // if TableCell.Name has instructions, create a CellFilterInstructions object
    // and evaluate the instructions and set the table cell color
    if (e.TableCell.Name != "")
    {
        CellFilterInstructions instructions = 
          (CellFilterInstructions)JsonConvert.DeserializeObject(
            e.TableCell.Name, typeof(CellFilterInstructions));

        // retrieve the color
        Color? color = instructions.GetColor(e.MailMergeFieldAdapter.ApplicationField.Text);

        // apply the color
        if (color != null)
            e.TableCell.CellFormat.BackColor = (Color)color;
    }
}

Test this on your own by downloading the sample project from our GitHub repository.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

Also See

This post references the following in the documentation:

  • Javascript: TableCellCollection.getItemAtInputPosition Method
  • Javascript: TXTextControl.addEventListener Method
  • Javascript: TXTextControl.saveDocument Method

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 2019
  • TX Text Control .NET Server X18 (trial sufficient)

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETJavaScriptDocument Editor

Detect Toggle Button Changes Using a MutationObserver

This article shows how to detect changes of toggle buttons in the ribbon of the web editor using a MutationObserver. The state of a toggle button in the ribbon visualizes the state of a certain…


ASP.NETASP.NET CoreDocument Editor

Merging Templates with MailMerge with Different Merge Field Settings in C#

This article shows how to merge templates with different merge field settings using the MailMerge class. The various settings allow for the removal of unused fields or the possibility to make…


ASP.NETMailMergeMVC

Getting Started: ServerTextControl and MailMerge with ASP.NET MVC (.NET…

This article shows how to use the TX Text Control ASP.NET ServerTextControl and MailMerge classes within an ASP.NET web application in Visual Studio 2022.


ASP.NETAzureHTML5

Deploying the MVC HTML5 Editor to Azure App Services

This article describes how to deploy the ASP.NET MVC HTML5 editor to Azure App Services.


ASP.NETGitHubHTML5

MVC: Loading Files from the Backstage Menu

Happy New Year, everybody! In the last blog entry, we showed how to replace the file menu with an MS Word-style backstage menu. This project shows how to load documents from a partial view in the…