我正在使用Apache 3.17。
代码如下(main方法+ addImage + addTitle方法)。
package office;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class WordGenerator {
XWPFDocument doc = new XWPFDocument();
public WordGenerator(){
this.doc = new XWPFDocument();
}
public XWPFDocument getDoc(){
return this.doc;
}
public static void main(String[] args) throws IOException, InvalidFormatException{
WordGenerator wg=new WordGenerator();
wg.addTitle("ola");
wg.addImage("path/to/image.jpg");
FileOutputStream out = new FileOutputStream("simple.docx");
wg.getDoc().write(out);
out.close();
}
public void addTitle(String title){
XWPFParagraph p=this.doc.createParagraph();
XWPFRun run=p.createRun();
run.setText(title);
}
public void addImage(String imagePath) throws IOException, InvalidFormatException{
int format=-1;
InputStream stream=new FileInputStream(imagePath);
if (imagePath.endsWith(".png")){
format = XWPFDocument.PICTURE_TYPE_PNG;
}else if (imagePath.endsWith(".jpeg") || imagePath.endsWith(".jpg")){
format = XWPFDocument.PICTURE_TYPE_JPEG;
}
if (format<0){
System.out.println("problem format");
stream.close();
return;
}
XWPFParagraph p=this.doc.createParagraph();
XWPFRun run=p.createRun();
run.addPicture(stream, format, imagePath, Units.toEMU(200), Units.toEMU(200));
System.out.println("picture added");
}
}
结果是,如果我同时添加图像和标题, 然后它生成一个空文档。
如果我只添加标题,则生成的文档是正确的。
答案 0 :(得分:0)
这是apache POI中的一个已知错误(几个错误报告之一here)
参见本SO问题中讨论的工作:
how to add a picture to a .docx document with Apache POI XWPF in java
Insert picture in word document
你真的需要写出docx文件吗?