Insert Checkboxes, Text Input, or Images

The merge engine takes a document as input, looks for MERGEFIELD fields in it, and replaces them with the data obtained from the data source. Typically, plain text and HTML are inserted, but Aspose.Words users can also generate a document that handles more unusual scenarios for mail merge fields.

Powerful Aspose.Words functionality allows you to extend the mail merge process:

  • insert checkboxes and text input form fields into the document during a mail merge
  • insert images from any custom storage (files, BLOB fields, etc.)

Insert Checkboxes and Text Input during Mail Merge

Sometimes it is necessary to perform a mail merge operation so that not text is substituted in the merge field, but a checkbox or text input field. Even though this is not the most common scenario, it is very handy for some tasks.

The following screenshot of a Word document shows a template with merge fields:

insert-checkboxes-html-or-images-during-mail-merge-aspose-words-java-1

This screenshot of the Word document below shows the already generated document:

insert-checkboxes-html-or-images-during-mail-merge-aspose-words-java-2

The following code example shows how to insert checkboxes and input text fields into a document during a mail merge:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document(getMyDir() + "Mail merge destinations - Fax.docx");
// Setup mail merge event handler to do the custom work.
doc.getMailMerge().setFieldMergingCallback(new HandleMergeField());
// Trim trailing and leading whitespaces mail merge values.
doc.getMailMerge().setTrimWhitespaces(false);
String[] fieldNames = {
"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
"Subject", "Body", "Urgent", "ForReview", "PleaseComment"
};
Object[] fieldValues = {
"Josh", "Jenny", "123456789", "", "Hello",
"<b>HTML Body Test message 1</b>", true, false, true
};
doc.getMailMerge().execute(fieldNames, fieldValues);
doc.save(getArtifactsDir() + "WorkingWithFields.MailMergeFormFields.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static 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>
public void /*IFieldMergingCallback.*/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*/Boolean)
{
// Move the "cursor" to the current merge field.
mBuilder.moveToMergeField(e.getFieldName());
String checkBoxName = MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());
mBuilder.insertCheckBox(checkBoxName, (Boolean) e.getFieldValue(), 0);
return;
}
switch (e.getFieldName())
{
case "Body":
mBuilder.moveToMergeField(e.getFieldName());
mBuilder.insertHtml((String) e.getFieldValue());
break;
case "Subject":
{
mBuilder.moveToMergeField(e.getFieldName());
String textInputName = MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());
mBuilder.insertTextInput(textInputName, TextFormFieldType.REGULAR, "", (String) e.getFieldValue(), 0);
break;
}
}
}
public void imageFieldMerging(ImageFieldMergingArgs args)
{
args.setImageFileName("Image.png");
args.getImageWidth().setValue(200.0);
args.setImageHeight(new MergeFieldImageDimension(200.0, MergeFieldImageDimensionUnit.PERCENT));
}
private DocumentBuilder mBuilder;
}

Insert Images during Mail Merge

When performing a mail merge operation, you can insert images from the database into the document using special image mail merge fields. The image mail merge field is a merge field named Image:MyFieldName.

Insert Images from a Database

During a mail merge, when an image mail merge field is encountered in a document, the FieldMergingCallback event is fired. You can respond to this event to return a filename, stream, or image object to the mail merge engine so it can be inserted into the document.

The following code example shows how to insert images stored in a database BLOB field into a report:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public void mailMergeImageFromBlob() throws Exception
{
Document doc = new Document(getMyDir() + "Mail merge destination - Northwind employees.docx");
doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb";
Connection connection = DriverManager.getConnection(connString, "Admin", "");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");
DataTable dataTable = new DataTable(resultSet, "Employees");
IDataReader dataReader = new DataTableReader(dataTable);
doc.getMailMerge().executeWithRegions(dataReader, "Employees");
connection.close();
doc.save(getArtifactsDir() + "WorkingWithFields.MailMergeImageFromBlob.docx");
}
public static class HandleMergeImageFieldFromBlob implements IFieldMergingCallback
{
public void fieldMerging(FieldMergingArgs args)
{
// Do nothing.
}
/// <summary>
/// This is called when mail merge engine encounters Image:XXX merge field in the document.
/// You have a chance to return an Image object, file name, or a stream that contains the image.
/// </summary>
public void imageFieldMerging(ImageFieldMergingArgs e) throws Exception
{
// The field value is a byte array, just cast it and create a stream on it.
ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
// Now the mail merge engine will retrieve the image from the stream.
e.setImageStream(imageStream);
}
}

Set Image Properties during Mail Merge

While merging an image merge field, you may sometimes need to control various image properties, such as WrapType.

Currently, using ImageFieldMergingArgs you can only set image width or height properties, respectively. To overcome this issue, Aspose.Words provides the Shape property, which facilitates to get full control over the inserted image or any other shape.

The following code example shows how to set various image properties:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("{{#foreach example}}");
builder.writeln("{{Image(126pt;126pt):stempel}}");
builder.writeln("{{/foreach example}}");
doc.getMailMerge().setUseNonMergeFields(true);
doc.getMailMerge().setTrimWhitespaces(true);
doc.getMailMerge().setUseWholeParagraphAsRegion(false);
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS
| MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS
| MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS
| MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);
doc.getMailMerge().setFieldMergingCallback(new ImageFieldMergingHandler());
doc.getMailMerge().executeWithRegions(new DataSourceRoot());
doc.save(getArtifactsDir() + "WorkingWithFields.MailMergeImageField.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static class ImageFieldMergingHandler implements IFieldMergingCallback
{
public void fieldMerging(FieldMergingArgs args)
{
// Implementation is not required.
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
{
Shape shape = new Shape(args.getDocument(), ShapeType.IMAGE);
{
shape.setWidth(126.0); shape.setHeight(126.0); shape.setWrapType(WrapType.SQUARE);
}
shape.getImageData().setImage(getMyDir() + "Mail merge image.png");
args.setShape(shape);
}
}