我有这个代码:
public class ImageAttachmentInDocument {
/**
* @param args
* @throws IOException
* @throws InvalidFormatException
*/
public static void main(String[] args) throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument();
FileInputStream is = new FileInputStream("encabezado.jpg");
doc.addPictureData(IOUtils.toByteArray(is), doc.PICTURE_TYPE_JPEG);
XWPFParagraph title = doc.createParagraph();
XWPFRun run = title.createRun();
run.setText("Fig.1 A Natural Scene");
run.setBold(true);
title.setAlignment(ParagraphAlignment.CENTER);
FileOutputStream fos = new FileOutputStream("test4.docx");
doc.write(fos);
fos.flush();
fos.close();
}
}
(我在 eclipse IDE 中使用 Apache POI 3.11 和 xmlbeans-2.3.0)
当我生成文档时,图像不显示
我究竟做错了什么?
您似乎没有将图像附加到您想要显示的文本中!
从中汲取灵感XWPF 简单图像示例 https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/examples/xwpf/usermodel/SimpleImages.java,我认为你希望你的代码是:
XWPFDocument doc = new XWPFDocument();
XWPFParagraph title = doc.createParagraph();
XWPFRun run = title.createRun();
run.setText("Fig.1 A Natural Scene");
run.setBold(true);
title.setAlignment(ParagraphAlignment.CENTER);
String imgFile = "encabezado.jpg";
FileInputStream is = new FileInputStream(imgFile);
run.addBreak();
run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
is.close();
FileOutputStream fos = new FileOutputStream("test4.docx");
doc.write(fos);
fos.close();
不同之处在于,您不是将图像显式附加到文档,而是将其添加到运行中。 run add 还将其添加到文档中,但重要的是还进行设置以引用您希望其显示的运行中的图片
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)