Customize Merge

Mail merging in GemBox.Document is very flexible and customizable.

Following example shows how to customize mail merge operation by handling FieldMerging event and import data in a specific format or as a picture.

For formatting date/time or numeric values you can use even simpler approach by using field formatting switches (\@ for date/time and \# for numbers) in the input template document.

Customize Merge Screenshot
Upload your file (Drag file here)
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using GemBox.Document;

class Program
{
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("%InputFileName%");

        int numberOfItems = %ItemsCount%;

        document.MailMerge.FieldMerging += (sender, e) =>
        {
            if (e.IsValueFound)
                switch (e.FieldName)
                {
                    case "Date":
                        ((Run)e.Inline).Text = ((DateTime)e.Value).ToString("dddd, MMMM d, yyyy");
                        break;
                    case "Price":
                    case "Total":
                    case "TotalPrice":
                        ((Run)e.Inline).Text = ((double)e.Value).ToString("0.00");
                        break;
                    case "Name":
                        e.Inline = new Picture(e.Document, "%#Acme.png%");
                        break;
                }
        };

        // Fill items (amount and prices).
        DataTable dt = new DataTable()
        {
            TableName = "Item"
        };
        dt.Columns.Add("Date", typeof(DateTime));
        dt.Columns.Add("Hours", typeof(double));
        dt.Columns.Add("Price", typeof(double));
        dt.Columns.Add("Total", typeof(double));

        DateTime startDate = DateTime.Now.AddDays(-numberOfItems);
        for (int i = 0; i < numberOfItems; i++)
        {
            // We worked between 6 and 8 hours per day.
            int workHours = i % 3 + 6;
            double totalPrice = workHours * 35;

            dt.Rows.Add(startDate.AddDays(i), workHours, 35, totalPrice);
        }

        document.MailMerge.Execute(dt);

        // Fill invoice number and date.
        int invoiceNumber = 14;
        document.MailMerge.Execute(
            new
            {
                Number = invoiceNumber,
                InvoiceDate = DateTime.Now.ToShortDateString()
            });


        // Fill customer data.
        document.MailMerge.Execute(
            new Dictionary<string, object>()
            {
                { "Name", "ACME Corp" },
                { "Address" , "240 Old Country Road, Springfield, IL" },
                { "Country" , "USA" },
                { "ContactPerson" , "Joe Smith" }
            });

        // Fill total.
        document.MailMerge.Execute(new { TotalPrice = dt.Rows.Cast<DataRow>().Sum(row => (double)row["Total"]) });

        // Fill notes.
        document.MailMerge.Execute(
            new KeyValuePair<string, object>[]
            {
                new KeyValuePair<string, object>("Notes", "Payment via check.")
            });

        document.Save("Customize Merge.%OutputFileType%");
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.Linq
Imports GemBox.Document

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document As DocumentModel = DocumentModel.Load("%InputFileName%")

        Dim numberOfItems As Integer = %ItemsCount%

        AddHandler document.MailMerge.FieldMerging,
            Sub(sender, e)
                If e.IsValueFound Then
                    Select Case e.FieldName
                        Case "Date"
                            DirectCast(e.Inline, Run).Text = DirectCast(e.Value, DateTime).ToString("dddd, MMMM d, yyyy")
                            Exit Select
                        Case "Price", "Total", "TotalPrice"
                            DirectCast(e.Inline, Run).Text = CDbl(e.Value).ToString("0.00")
                            Exit Select
                        Case "Name"
                            e.Inline = New Picture(e.Document, "%#Acme.png%")
                            Exit Select
                    End Select
                End If
            End Sub

        ' Fill items (amount and prices).
        Dim dt As New DataTable()
        dt.TableName = "Item"
        dt.Columns.Add("Date", GetType(DateTime))
        dt.Columns.Add("Hours", GetType(Double))
        dt.Columns.Add("Price", GetType(Double))
        dt.Columns.Add("Total", GetType(Double))

        Dim startDate As DateTime = DateTime.Now.AddDays(-numberOfItems)
        For i As Integer = 0 To numberOfItems - 1
            ' We worked between 6 and 8 hours per day.
            Dim workHours As Integer = i Mod 3 + 6
            Dim totalPrice As Double = workHours * 35

            dt.Rows.Add(startDate.AddDays(i), workHours, 35, totalPrice)
        Next

        document.MailMerge.Execute(dt)

        ' Fill invoice number and date.
        Dim invoiceNumber As Integer = 14
        document.MailMerge.Execute(New With {
            .Number = invoiceNumber,
            .InvoiceDate = DateTime.Now.ToShortDateString()
        })


        ' Fill customer data.
        document.MailMerge.Execute(New Dictionary(Of String, Object)() From {
            {"Name", "ACME Corp"},
            {"Address", "240 Old Country Road, Springfield, IL"},
            {"Country", "USA"},
            {"ContactPerson", "Joe Smith"}
        })

        ' Fill total.
        document.MailMerge.Execute(New With {
            .TotalPrice = dt.Rows.Cast(Of DataRow)().Sum(Function(row) CDbl(row("Total")))
        })

        ' Fill notes.
        document.MailMerge.Execute(New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("Notes", "Payment via check.")})

        document.Save("Customize Merge.%OutputFileType%")

    End Sub

End Module

Check next example or download examples from GitHub.