如何使用jodreports和java在odt文件上运行时插入

时间:2012-04-18 18:50:01

标签: java image insert

我需要使用java在doc或odt文档中插入各种图像,图像是在运行时生成的。当时我很想使用jodreports,因为它很容易生成最终文档的模板,但我被卡住了,因为我找不到任何类型的文档告诉我如何插入图像。如果您可以回答我的问题,请发布一个代码段或告诉我我可以使用哪个其他库。

非常感谢你的帮助(抱歉我的英语不好)。

3 个答案:

答案 0 :(得分:1)

在班级中创建一个ImageSource - 对象。

ImageSource imagen =
new RenderedImageSource(ImageIO.read(new File(ruta_fisica_imagen)));

将此对象添加到Map对象

在模板中定义jooscript.image(name)

更多信息,该文件是西班牙文 http://www.montesinos.org.es/2010/11/jodreports-mini-how-to.html

答案 1 :(得分:1)

在我的页面https://xbrowser.altervista.org/informatica-portata/odt-converter/ 你可以一步一步找到如何实现你的问题。

图书馆是:

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import net.sf.jooreports.templates.DocumentTemplate;
import net.sf.jooreports.templates.DocumentTemplateException;
import net.sf.jooreports.templates.DocumentTemplateFactory;
import net.sf.jooreports.templates.image.FileImageSource;

这是方法

private Map<String, Object> data = new HashMap<String, Object>();;
private Logger log = Logger.getLogger(this.getClass().getName());

private void createOdt() {

DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
DocumentTemplate template = null;

File inputFile = new File("/path/template.odt"); //inserire il path relativo alla posizione del template .odt
try {
template = documentTemplateFactory.getTemplate(inputFile);
log.debug("input file ok -> " + inputFile);
} catch (IOException e) {
log.error(e);
}
try {
tmpFile = File.createTempFile("odt_", ".odt");

data.put("qrcode", new FileImageSource(new File("/img/src/qrcode.jpg"))); //qui è possibile generare per esempio un qrcode
template.createDocument(data, new FileOutputStream(tmpFile));

log.debug("output file temporaneo creato ("+ tmpFile.getAbsolutePath() + ")..");
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (DocumentTemplateException e) {
log.error(e);
}
}

此时,必须在.odt模板中插入具有以下模态的图像:

  1. 插入图片
  2. 双击图像进入图像属性
  3. 选择“选项”标签
  4. 在“名称”字段中插入:jooscript.image(qrcode)
  5. 正如您所看到的,图像名称显示的是qrcode,它正是我们代码中{(1}})的hashmap键的名称。

    通过这种方式,可以在.odt中定义的模板中显示来自java代码的动态生成的图像。

    我希望你能提供帮助

答案 2 :(得分:0)

只想确认@Jarabid的方法有效。

//visual signature
ImageSource signatureImage = 
      new RenderedImageSource(ImageIO.read(new File("resources/Signature.png")));
data.put("signature", signatureImage);

我在Mac上使用LibreOffice,我做的是:

  • 从文件插入图像(使用占位符图像)
  • 双击图片以显示图片属性
  • 选择“选项”标签
  • 名称粘贴:jooscript.image(签名)

首先尝试完美。快乐:)