Aspose.Words

How-to: Insert Check Boxes during Mail Merge

You can download the complete source code of the MailMergeFormFields sample here.

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 is inserted, but a customer 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 HTML into merge fields (sample code in the documentation for the MergeField event).

·          Insert images from any custom storage (files, BLOB fields etc).

·          Insert text with formatting (font, size, style etc).

This screenshot of Microsoft Word shows a template document with the merge fields:

Image Hosted by ImageShack.us

This screenshot of Microsoft Word shows the generated document. Note some fields were replaced with simple text, some fields were replaced with check box form fields and the Subject field was replaced with a text input form field.

Example MailMergeFormFields

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

[Java]

 

package MailMergeFormFields;

 

import java.io.File;

import java.net.URI;

 

import com.aspose.words.Document;

import com.aspose.words.IFieldMergingCallback;

import com.aspose.words.FieldMergingArgs;

import com.aspose.words.DocumentBuilder;

import com.aspose.words.TextFormFieldType;

import com.aspose.words.ImageFieldMergingArgs;

 

 

/**

* This sample shows how to insert check boxes and text input form fields during mail merge into a document.

*/

class Program

{

    /**

     * The main entry point for the application.

     */

    public static void main(String[] args) throws Exception

    {

        Program program = new Program();

        program.execute();

    }

 

    private void execute() throws Exception

    {

        URI exeDir = Program.class.getResource("").toURI();

        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

 

        // Load the template document.

        Document doc = new Document(dataDir + "Template.doc");

 

        // Setup mail merge event handler to do the custom work.

        doc.getMailMerge().setFieldMergingCallback(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",

            "Test message 1", true, false, true};

 

        // Execute the mail merge.

        doc.getMailMerge().execute(fieldNames, fieldValues);

 

        // Save the finished document.

        doc.save(dataDir + "Template Out.doc");

    }

 

    private class HandleMergeField implements IFieldMergingCallback

    {

        /**

         * This handler is called for every mail merge field found in the document,

         * for every record found in the data source.

         */

        public void fieldMerging(FieldMergingArgs e) throws Exception

        {

            if (mBuilder == null)

                mBuilder = new DocumentBuilder(e.getDocument());

 

            // We decided that we want all boolean values to be output as check box form fields.

            if (e.getFieldValue() instanceof Boolean)

            {

                // Move the "cursor" to the current merge field.

                mBuilder.moveToMergeField(e.getFieldName());

 

                // It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.

                String checkBoxName = java.text.MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());

 

                // Insert a check box.

                mBuilder.insertCheckBox(checkBoxName, (Boolean)e.getFieldValue(), 0);

 

                // Nothing else to do for this field.

                return;

            }

 

            // Another example, we want the Subject field to come out as text input form field.

            if ("Subject".equals(e.getFieldName()))

            {

                mBuilder.moveToMergeField(e.getFieldName());

                String textInputName = java.text.MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());

                mBuilder.insertTextInput(textInputName, TextFormFieldType.REGULAR, "", (String)e.getFieldValue(), 0);

            }

        }

 

        public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception

        {

            // Do nothing.

        }

 

        private DocumentBuilder mBuilder;

    }

}