Customize Merge

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

Following sample 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/ime and \# for numbers) in the input template document.

Screenshot

Customize Merge Screenshot

See the full code below, use RUN EXAMPLE to execute.

Upload your file (Drag files here)

1using System;
2using System.Collections.Generic;
3using System.Data;
4using System.IO;
5using System.Linq;
6using GemBox.Document;
7using GemBox.Document.MailMerging;
8
9class Sample
10{
11    [STAThread]
12    static void Main(string[] args)
13    {
14        // If using Professional version, put your serial key below.
15        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
16
17        DocumentModel document = DocumentModel.Load("InvoiceForMailMerge.docx");
18
19        int numberOfItems = 10;
20        string pathToResources = "Resources";
21
22        document.MailMerge.FieldMerging += (sender, e) =>
23        {
24            if (e.IsValueFound)
25                switch (e.FieldName)
26                {
27                    case "Date":
28                        ((Run)e.Inline).Text = ((DateTime)e.Value).ToString("dddd, MMMM d, yyyy");
29                        break;
30                    case "Price":
31                    case "Total":
32                    case "TotalPrice":
33                        ((Run)e.Inline).Text = ((double)e.Value).ToString("0.00");
34                        break;
35                    case "Name":
36                        e.Inline = new Picture(e.Document, Path.Combine(pathToResources, "Acme.png"));
37                        break;
38                }
39        };
40
41        // Fill items (amount and prices).
42        DataTable dt = new DataTable()
43        {
44            TableName = "Item"
45        };
46        dt.Columns.Add("Date", typeof(DateTime));
47        dt.Columns.Add("Hours", typeof(double));
48        dt.Columns.Add("Price", typeof(double));
49        dt.Columns.Add("Total", typeof(double));
50
51        DateTime startDate = DateTime.Now.AddDays(-numberOfItems);
52        for (int i = 0; i < numberOfItems; i++)
53        {
54            // We worked between 6 and 8 hours per day.
55            int workHours = i % 3 + 6;
56            double totalPrice = workHours * 35;
57
58            dt.Rows.Add(startDate.AddDays(i), workHours, 35, totalPrice);
59        }
60
61        document.MailMerge.Execute(dt);
62
63        // Fill invoice number and date.
64        int invoiceNumber = 14;
65        document.MailMerge.Execute(
66            new
67            {
68                Number = invoiceNumber,
69                InvoiceDate = DateTime.Now.ToShortDateString()
70            });
71
72
73        // Fill customer data.
74        document.MailMerge.Execute(
75            new Dictionary<string, object>()
76            { 
77                { "Name", "ACME Corp" },
78                { "Address" , "240 Old Country Road, Springfield, IL" },
79                { "Country" , "USA" },
80                { "ContactPerson" , "Joe Smith" }
81            });
82
83        // Fill total.
84        document.MailMerge.Execute(new { TotalPrice = dt.Rows.Cast<DataRow>().Sum(row => (double)row["Total"]) });
85
86        // Fill notes.
87        document.MailMerge.Execute(
88            new KeyValuePair<string, object>[]
89            {
90                new KeyValuePair<string, object>("Notes", "Payment via check.")
91            });
92
93        document.Save("Customize Merge.docx");
94    }
95}
1Imports System
2Imports System.Collections.Generic
3Imports System.Data
4Imports System.IO
5Imports System.Linq
6Imports GemBox.Document
7Imports GemBox.Document.MailMerging
8
9Module Samples
10
11    Sub Main()
12
13        ' If using Professional version, put your serial key below.
14        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
15
16        Dim document As DocumentModel = DocumentModel.Load("InvoiceForMailMerge.docx")
17
18        Dim numberOfItems As Integer = 10
19        Dim pathToResources As String = "Resources"
20
21        AddHandler document.MailMerge.FieldMerging, _
22            Sub(sender, e)
23                If e.IsValueFound Then
24                    Select Case e.FieldName
25                        Case "Date"
26                            DirectCast(e.Inline, Run).Text = DirectCast(e.Value, DateTime).ToString("dddd, MMMM d, yyyy")
27                            Exit Select
28                        Case "Price", "Total", "TotalPrice"
29                            DirectCast(e.Inline, Run).Text = CDbl(e.Value).ToString("0.00")
30                            Exit Select
31                        Case "Name"
32                            e.Inline = New Picture(e.Document, Path.Combine(pathToResources, "Acme.png"))
33                            Exit Select
34                    End Select
35                End If
36            End Sub
37
38        ' Fill items (amount and prices).
39        Dim dt As New DataTable()
40        dt.TableName = "Item"
41        dt.Columns.Add("Date", GetType(DateTime))
42        dt.Columns.Add("Hours", GetType(Double))
43        dt.Columns.Add("Price", GetType(Double))
44        dt.Columns.Add("Total", GetType(Double))
45
46        Dim startDate As DateTime = DateTime.Now.AddDays(-numberOfItems)
47        For i As Integer = 0 To numberOfItems - 1
48            ' We worked between 6 and 8 hours per day.
49            Dim workHours As Integer = i Mod 3 + 6
50            Dim totalPrice As Double = workHours * 35
51
52            dt.Rows.Add(startDate.AddDays(i), workHours, 35, totalPrice)
53        Next
54
55        document.MailMerge.Execute(dt)
56
57        ' Fill invoice number and date.
58        Dim invoiceNumber As Integer = 14
59        document.MailMerge.Execute(New With {
60            .Number = invoiceNumber,
61            .InvoiceDate = DateTime.Now.ToShortDateString()
62        })
63
64
65        ' Fill customer data.
66        document.MailMerge.Execute(New Dictionary(Of String, Object)() From {
67            {"Name", "ACME Corp"},
68            {"Address", "240 Old Country Road, Springfield, IL"},
69            {"Country", "USA"},
70            {"ContactPerson", "Joe Smith"}
71        })
72
73        ' Fill total.
74        document.MailMerge.Execute(New With {
75            .TotalPrice = dt.Rows.Cast(Of DataRow)().Sum(Function(row) CDbl(row("Total")))
76        })
77
78        ' Fill notes.
79        document.MailMerge.Execute(New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("Notes", "Payment via check.")})
80
81        document.Save("Customize Merge.docx")
82
83    End Sub
84
85End Module

Check next sample or find out more about GemBox.Document and GemBox Software.