我有这样的代码:
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 )
当我生成文档时,图像不显示
我做错了什么?
发布于 2014-11-06 07:32:52
您似乎没有将图像附加到您想要显示的文本的位置!
从XWPF Simple Images Example中获得灵感,我认为你希望你的代码是:
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还会将其添加到文档中,但重要的是,它还会设置为引用您希望在其中显示的运行图片
https://stackoverflow.com/questions/26764889
复制相似问题