Image Field Merging

I have implemented an IFieldMergingCallback to perform advanced field merging with images. I can’t figure out the logic on some things, though, specifically what the best way to get the image is. Things seem inconsistent.

Here’s part of my code:

@Override
public void imageFieldMerging(ImageFieldMergingArgs ifma) throws Exception {
LOG.debug(“Merging image field {} with img”,ifma.getDocumentFieldName());
try {
DocumentBuilder builder = new DocumentBuilder(ifma.getDocument());
if (builder.moveToMergeField(ifma.getDocumentFieldName())) {
Shape shape = new Shape(ifma.getDocument(),ShapeType.IMAGE);

LOG.debug(“merging image field, is field value null? {}”,(ifma.getFieldValue() == null));
LOG.debug(“How about the image itself? {}”,(ifma.getImage() == null));
LOG.debug(“What about stream? {}”,(ifma.getImageStream() == null));



Depending on the situation, I see different values being null, and I’ve noticed that only one of the three methods does not return null. Can anyone help me understand when things will be one way or the other?

Thanks,
Brian

Hi Brian,


Thanks for your inquiry. You simply need to place an image merge field in your template Word document. Here is the syntax of such fields:

Image:MyFieldName

You can then insert Image by using the following code:

DataTable dataTable = new DataTable();
dataTable.getColumns().add(“MyImageField”);
DataRow row = dataTable.newRow();
row.set(0, ImageIO.read(new File(getMyDir() + “aspose.words.jpg”)));
dataTable.getRows().add(row);

Document doc = new Document(getMyDir() + “imagetemplate.docx”);

doc.getMailMerge().setFieldMergingCallback(new HandleImageMergeField());
doc.getMailMerge().execute(dataTable);

doc.save(getMyDir() + “out.docx”);

private static class HandleImageMergeField 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 {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write((BufferedImage) e.getFieldValue(), “jpg”, os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
e.setImageStream(is);
}
}

I hope, this helps.

Best regards,