且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-07 12:03:16

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

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