如何使用Apache POI在word文档中插入图像?

时间:2014-11-05 18:55:33

标签: java apache-poi

我有这段代码:

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)

生成文档时,不显示图像

我做错了什么?

1 个答案:

答案 0 :(得分:6)

您似乎无法将图片附加到您希望其显示的文字上!

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

不同之处在于,不是将图像显式附加到文档,而是将其添加到运行中。运行添加还将其添加到文档中,但重要的是还设置引用要在其中显示的运行中的图片