Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a image in word document with Apache POI?

I have this code:

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();        
    }
}

(I am using Apache POI 3.11 and xmlbeans-2.3.0 in eclipse IDE)

when I generate the document, the image is not displayed

What am I doing wrong?

like image 959
Erika Hernández Avatar asked Dec 25 '22 02:12

Erika Hernández


1 Answers

You don't seem to be attaching the image to the text where you want it shown!

Taking inspiration from the XWPF Simple Images Example, I think what you'd want your code to be is:

    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();        

The difference there is that rather than explicitly attaching the image to the document, you instead add it to a run. The run add also adds it to the document, but importantly also sets things up to reference the picture from the run you want it to show in

like image 103
Gagravarr Avatar answered Dec 28 '22 09:12

Gagravarr