如何使用java将图像插入到word文档中

时间:2010-03-22 17:49:28

标签: java ms-word

如何使用java

将图像插入到word文档中

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

查看Apache POI API。

答案 2 :(得分:1)

请试试这个:

import java.io.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ImageDoc 
{
    public static void main(String[] args) throws IOException, InvalidFormatException 
    {
        XWPFDocument docx = new XWPFDocument();
        XWPFParagraph par = docx.createParagraph();
        XWPFRun run = par.createRun();
        run.setText("Hello, World. This is my first java generated docx-file. Have fun.");
        run.setFontSize(13);
        InputStream pic = new FileInputStream("C:\\Users\\amitabh\\Pictures\\pics\\3.jpg");
        //byte [] picbytes = IOUtils.toByteArray(pic);
        //run.addPicture(picbytes, Document.PICTURE_TYPE_JPEG);
        run.addPicture(pic, Document.PICTURE_TYPE_JPEG, "3", 0, 0);
        FileOutputStream out = new FileOutputStream("C:\\Users\\amitabh\\Pictures\\pics\\finallyhurray.doc"); 
        docx.write(out); 
        out.close(); 
        pic.close();
    }
}

您可以相应地更改路径名

答案 3 :(得分:0)

Docmosis也可以这样做。您将文档中的图像作为占位符放置,以获得所需的大小等,然后Docmosis将在运行时从Java注入给定的图像。