0

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.

Dylan Corriveau
  • 2,561
  • 4
  • 29
  • 36
Giovanni Bitliner
  • 2,032
  • 5
  • 31
  • 50

1 Answers1

0

This is a known bug in apache POI (one of several bug reports here )

see work arounds discussed in this SO questions:

how to add a picture to a .docx document with Apache POI XWPF in java

Insert picture in word document

Do you actually need to write out docx files?

Community
  • 1
  • 1
dkatzel
  • 31,188
  • 3
  • 63
  • 67