如何使用 Apache POI 在 Word 文档中插入图像? [英] How to insert a image in word document with Apache POI?

查看:91
本文介绍了如何使用 Apache POI 在 Word 文档中插入图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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)

(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

我做错了什么?

推荐答案

您似乎没有将图像附加到要显示的文本中!

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

XWPF 简单图像示例,我认为您希望您的代码是:

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

这篇关于如何使用 Apache POI 在 Word 文档中插入图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆