有没有办法使用胡子语法或java创建docx报告在图像上插入图像?
在docx中,我声明了这样的背景图像:{{Image:BackgroundImage}}。我正在运行这段代码。
Document doc = new Document(dataDir + "ImagesTemplate.docx");
doc.getMailMerge().execute(new String[]{"BackgroundImage","AnpotherImage"}, new Object[]{"image1.png","image2.png");
doc.save(dataDir + "ImageOutput.docx");
当然,图像的路径并不是一成不变的。 有没有办法将image2插入到image1?
答案 0 :(得分:0)
Aspose.Words API中没有这样的方法来在另一个图像上渲染图像。但是,您可以使用自定义代码实现此目的。
在您的示例中,您传递了背景图像和前景图像,这意味着将有两个单独的字段。我们只需传递一个字段。在自定义代码中,我们可以放入2个或更多图像。
// Suppose the field name is just "Image"
doc.getMailMerge().setFieldMergingCallback(new HandleMergeFields()); // This method will do the trick
doc.getMailMerge().execute(new String[]{"Image"}, new Object[]{Common.DATA_DIR + "images/001-front.jpg"});
Word模板中的字段名称也应为"图像"。
关于文件名,我假设您只传递一个文件名,例如" 001-front.jpg&#34 ;.在自定义代码中,我将使用它提取背景图像。相应的图像将是" 001-back.jpg"
现在用于处理图像的自定义覆盖方法。
private static class HandleMergeFields implements IFieldMergingCallback
{
public void fieldMerging(FieldMergingArgs e) throws Exception
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.getDocument());
// If the field name is "Image"
if (e.getFieldName().equals("Image"))
{
try
{
// Go to that place and remove the field
mBuilder.moveToMergeField("Image", true, true);
// Get the field value
String fieldValue = (String)e.getFieldValue();
// Field value is the front image
String frontImgPath = fieldValue;
// Get the background image.
// You can use any logic here to find your background image
String backImagePath = frontImgPath.replace("-front.jpg", "-back.jpg");
// First insert the background image in the document
BufferedImage backImage = ImageIO.read(new File(backImagePath));
Shape shape = mBuilder.insertImage(backImage);
shape.setWrapType(WrapType.NONE);
// Now insert the foreground image
File secondFile = new File(frontImgPath);
if (secondFile.exists() == true)
{
BufferedImage imgsecond = ImageIO.read(secondFile);
Shape shapeLegend = mBuilder.insertImage(imgsecond);
shapeLegend.setWrapType(WrapType.NONE);
// Position where to add the foreground image
double secondTop = 0;
double secondLeft = shape.getWidth() - shapeLegend.getWidth();
shapeLegend.setTop(secondTop);
shapeLegend.setLeft(secondLeft);
}
}
catch(Exception ex)
{
System.err.println("Can't load map image. Exception: " + ex.getMessage());
}
}
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
{
try
{
}
catch(Exception ex)
{
System.err.println("Error putting map image. Exception: " + ex.getMessage());
}
}
private DocumentBuilder mBuilder;
}