Home > Code > C# > How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps

How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps

by sher azam   on Jan 13, 2016   Category: C#   |  Views: 746    |  Points: 25   |  Gold 


This technical tip explains how developers can insert check boxes or HTML during mail merge. One of the important Aspose.Words features is the reporting (mail merge) engine. The mail merge engine takes a document on input, looks for MERGEFIELD fields in it and replaces them with data obtained from the data source. Normally, simple text and HTML is inserted, but a user asked if it is possible to generate a document where boolean data values are output as check box form fields. The answer is yes - it is possible and it is very easy, thanks to the ability to extend the mail merge process using event handlers. The MailMerge object provides the MergeField and MergeImageField event handlers. Other interesting examples of extending standard mail merge using event handlers are:

• Insert images from any custom storage (files, BLOB fields etc).
• Insert text with formatting (font, size, style etc).

Complete source code of a program that inserts checkboxes and text input form fields into a document during mail merge is provided below.

//[C# Code Sample]

using System;
using System.IO;
using System.Reflection;
using Aspose.Words;
using Aspose.Words.Fields;
using Aspose.Words.MailMerging;

namespace MailMergeFormFields
{
/// <summary>
/// This sample shows how to insert check boxes and text input form fields during mail merge into a document.
/// </summary>
class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
Program program = new Program();
program.Execute();
}

private void Execute()
{
string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;

// Load the template document.
Document doc = new Document(dataDir + "Template.doc");

// Setup mail merge event handler to do the custom work.
doc.MailMerge.FieldMergingCallback = new HandleMergeField();

// This is the data for mail merge.
String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
"Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
"<b>HTML Body Test message 1</b>", true, false, true};

// Execute the mail merge.
doc.MailMerge.Execute(fieldNames, fieldValues);

// Save the finished document.
doc.Save(dataDir + "Template Out.doc");
}

private class HandleMergeField : IFieldMergingCallback
{
/// <summary>
/// This handler is called for every mail merge field found in the document,
/// for every record found in the data source.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.Document);

// We decided that we want all boolean values to be output as check box form fields.
if (e.FieldValue is bool)
{
// Move the "cursor" to the current merge field.
mBuilder.MoveToMergeField(e.FieldName);

// It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);

// Insert a check box.
mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);

// Nothing else to do for this field.
return;
}

// We want to insert html during mail merge.
if (e.FieldName == "Body")
{
mBuilder.MoveToMergeField(e.FieldName);
mBuilder.InsertHtml((string)e.FieldValue);
}

// Another example, we want the Subject field to come out as text input form field.
if (e.FieldName == "Subject")
{
mBuilder.MoveToMergeField(e.FieldName);
string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
}
}

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}

private DocumentBuilder mBuilder;
}
}
}

//[VB.NET Code Sample]


Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Reflection
Imports Aspose.Words
Imports Aspose.Words.Fields
Imports Aspose.Words.MailMerging

Namespace MailMergeFormFields
''' <summary>
''' This sample shows how to insert check boxes and text input form fields during mail merge into a document.
''' </summary>
Friend Class Program
''' <summary>
''' The main entry point for the application.
''' </summary>
Public Shared Sub Main(ByVal args() As String)
Dim program As New Program()
program.Execute()
End Sub

Private Sub Execute()
Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath

' Load the template document.
Dim doc As New Document(dataDir & "Template.doc")

' Setup mail merge event handler to do the custom work.
doc.MailMerge.FieldMergingCallback = New HandleMergeField()

' This is the data for mail merge.
Dim fieldNames() As String = {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment"}
Dim fieldValues() As Object = {"Josh", "Jenny", "123456789", "", "Hello", "<b>HTML Body Test message 1</b>", True, False, True}

' Execute the mail merge.
doc.MailMerge.Execute(fieldNames, fieldValues)

' Save the finished document.
doc.Save(dataDir & "Template Out.doc")
End Sub

Private Class HandleMergeField
Implements IFieldMergingCallback
''' <summary>
''' This handler is called for every mail merge field found in the document,
''' for every record found in the data source.
''' </summary>
Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
If mBuilder Is Nothing Then
mBuilder = New DocumentBuilder(e.Document)
End If

' We decided that we want all boolean values to be output as check box form fields.
If TypeOf e.FieldValue Is Boolean Then
' Move the "cursor" to the current merge field.
mBuilder.MoveToMergeField(e.FieldName)

' It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
Dim checkBoxName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)

' Insert a check box.
mBuilder.InsertCheckBox(checkBoxName, CBool(e.FieldValue), 0)

' Nothing else to do for this field.
Return
End If

' We want to insert html during mail merge.
If e.FieldName = "Body" Then
mBuilder.MoveToMergeField(e.FieldName)
mBuilder.InsertHtml(DirectCast(e.FieldValue, String))
End If

' Another example, we want the Subject field to come out as text input form field.
If e.FieldName = "Subject" Then
mBuilder.MoveToMergeField(e.FieldName)
Dim textInputName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", CStr(e.FieldValue), 0)
End If
End Sub

Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
' Do nothing.
End Sub

Private mBuilder As DocumentBuilder
End Class
End Class
End Namespace



More about Aspose.Words for .NET

Aspose.Words is a word processing component that enables Java & .NET applications to read, write and modify Word documents without using Microsoft Word. Other useful features include document creation, content and formatting manipulation, mail merge abilities, reporting features, TOC updated/rebuilt, Embedded OOXML, Footnotes rendering and support of DOCX, DOC, WordprocessingML, HTML, XHTML, TXT and PDF formats (requires Aspose.Pdf). It supports both 32-bit and 64-bit operating systems. You can even use Aspose.Words to build applications with Mono.

- Homepage of Aspose.Words for .NET: http://www.aspose.com/.net/word-component.aspx

- Download Aspose.Words for .NET: http://www.aspose.com/community/files/51/.net-components/aspose.words-for-.net/default.aspx



Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts