The MailMerge.FieldMergingCallback event occurs during mail merge when an image mail merge field is encountered in the document. An image mail merge field is a merge field named like Image:MyFieldName. You can respond to this event to return a file name, stream, or an Image object to the mail merge engine so that it is inserted into the document.
The MailMerge.FieldMergingCallback property accepts a class implementing the IFieldMergingCallback interface. This class defines the method that is called to handle the merging for the image field. The method handler receives an argument of type ImageFieldMergingArgs. There are three properties available ImageFieldMergingArgs.ImageFileName, ImageFieldMergingArgs.ImageStream and ImageFieldMergingArgs.Image to specify from where the image must be taken. Set only one of these properties.
Example
Shows how to insert images stored in a database BLOB field into a report.
[Java]
public void mailMergeImageFromBlob() throws Exception {
Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");
// Set up the event handler for image fields.
doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Loads the driver
// Open the database connection.
String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + getDatabaseDir() + "Northwind.mdb" + ";UID=Admin";
// DSN-less DB connection.
java.sql.Connection conn = java.sql.DriverManager.getConnection(connString);
// Create and execute a command.
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");
com.aspose.words.DataTable table = new com.aspose.words.DataTable(resultSet, "Employees");
// Perform mail merge.
doc.getMailMerge().executeWithRegions(table);
// Close the database.
conn.close();
doc.save(getMyDir() + "MailMerge.MergeImage Out.doc");
}
private class HandleMergeImageFieldFromBlob implements IFieldMergingCallback {
public void fieldMerging(FieldMergingArgs args) throws Exception {
// Do nothing.
}
/**
* 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.
*/
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);
}
}