Hello,
I am trying to make a poc based on Aspose.Words for Java and I’m having a problem when try to merge an image.
My word document looks like this:
Titre : { MERGEFIELD TITRE \* MERGEFORMAT }
Image : { MERGEFIELD \d "Image:IMAGETEST" \* MERGEFORMATINET}
My service :
public DocumentDto mergeDocument(String template, Map data) {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(template);
DocumentDto docx = new DocumentDto();
try {
Document document = new Document(is);
document.getMailMerge().setFieldMergingCallback(new HandleMergeImageField());
String[] fields = document.getMailMerge().getFieldNames();
Object[] values = new Object[fields.length];
IntStream.range(0, fields.length).forEach(i -> values[i] = data.get(fields[i]));
document.getMailMerge().execute(fields, values);
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
document.save(dstStream, SaveFormat.DOCX);
docx.setDocument(dstStream.toByteArray());
} catch (Exception e) {
logger.warning(() -> MessageFormat.format("Error : {0}", e.getMessage()));
}
return docx;
}
private class HandleMergeImageField 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 {
if (e.getFieldValue() == null) {
e.setImageStream(new ByteArrayInputStream(new byte[] {}));
} else {
ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
e.setImageStream(imageStream);
}
}
}
My Junit test :
@Test
public void testMergeDocument() {
Map data = new HashMap();
data.put("TITRE", "TITRE_DOC");
data.put("Image:IMAGETEST", "C:\\project\\avatar.jpeg");
DocumentDto docx = service.mergeDocument("com/poc/template.docx", data);
Assert.assertNotNull("document Not null", docx);
Assert.assertNotNull("document Byte Not null", docx.getDocument());
}
My problem is located on HandleMergeImageField. imageFieldMerging, the e.getFieldValue() is null event if arrays passed to getMailMerge().execute contains the value of the field.
I trought also to pass byte[] of the image but I had the same problem.
Thanks for your help;