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

8

我有这段代码:

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个回答

14

你似乎没有将图片附加到你想要显示的文本中!

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

区别在于,您不是将图像明确地附加到文档上,而是将其添加到运行中。添加运行还将其添加到文档中,但更重要的是设置从您想要在其中显示它的运行引用图片的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接