I am using Apache 3.17.
The code is below (main method + addImage + addTitle methods).
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");
}
}
The result is that if I add both image and title, then it generates an empty document.
If I add only the title, then the generated document is the right one.