【发布时间】:2012-04-18 18:50:01
【问题描述】:
我需要使用 java 在 doc 或 odt 文档中插入各种图像,这些图像是在运行时生成的。当时我很想使用 jodreports,因为它很容易生成最终文档的模板,但我被困住了,因为我找不到任何类型的文档告诉我如何插入图像。如果您能回答我的问题,请发布代码 sn-p 或告诉我可以使用哪个其他库。
非常感谢您的帮助(也很抱歉我的英语不好)。
【问题讨论】:
我需要使用 java 在 doc 或 odt 文档中插入各种图像,这些图像是在运行时生成的。当时我很想使用 jodreports,因为它很容易生成最终文档的模板,但我被困住了,因为我找不到任何类型的文档告诉我如何插入图像。如果您能回答我的问题,请发布代码 sn-p 或告诉我可以使用哪个其他库。
非常感谢您的帮助(也很抱歉我的英语不好)。
【问题讨论】:
在你的类中创建一个ImageSource-object。
ImageSource imagen =
new RenderedImageSource(ImageIO.read(new File(ruta_fisica_imagen)));
将此对象添加到地图对象中
在模板中定义jooscript.image(name)
更多信息,文档是西班牙文 http://www.montesinos.org.es/2010/11/jodreports-mini-how-to.html
【讨论】:
在我的页面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 模板中使用以下方式插入图像:
如您所见,图片的名称显示了 qrcode,这正是我们代码中 hashmap 键的名称(data.put("qrcode"))。
通过这种方式,可以在 .odt 中定义的模板中显示从 java 代码动态生成的图像。
希望对你有所帮助
【讨论】:
只是想确认@Jarabid 的方法有效。
//visual signature
ImageSource signatureImage =
new RenderedImageSource(ImageIO.read(new File("resources/Signature.png")));
data.put("signature", signatureImage);
我在 Mac 上使用 LibreOffice,我所做的是:
第一次尝试就完美了。快乐:)
【讨论】: