首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Apache POI在word文档中插入图像?

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

Stack Overflow用户
提问于 2014-11-06 02:55:33
回答 1查看 22.6K关注 0票数 4

我有这样的代码:

代码语言:javascript
复制
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 )

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

我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2014-11-06 07:32:52

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

XWPF Simple Images Example中获得灵感,我认为你希望你的代码是:

代码语言:javascript
复制
    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();        

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

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26764889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档