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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26764889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:33:29  来源:igfitidea点击:

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

javaapache-poi

提问by Erika Hernández

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)

(我在 Eclipse IDE 中使用 Apache POI 3.11 和 xmlbeans-2.3.0)

when I generate the document, the image is not displayed

当我生成文档时,图像不显示

What am I doing wrong?

我究竟做错了什么?

回答by Gagravarr

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:

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

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

不同之处在于,不是将图像显式附加到文档,而是将其添加到运行中。运行添加还将其添加到文档中,但重要的是还设置了一些内容以引用您希望它显示的运行中的图片