开发者

how to insert image into word document using java

开发者 https://www.devze.com 2022-12-24 12:24 出处:网络
how to insert ima开发者_Go百科ge into word document using javahttp://dev.plutext.org/trac/docx4j/browser/trunk/docx4j/src/main/java/org/docx4j/samples/AddImage.javaTake a look at the Apache POI API.Pl

how to insert ima开发者_Go百科ge into word document using java


http://dev.plutext.org/trac/docx4j/browser/trunk/docx4j/src/main/java/org/docx4j/samples/AddImage.java


Take a look at the Apache POI API.


Please try this:

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

You can change the path name accordingly


Docmosis can do this also. You place an image in your document as a placeholder to get the size etc as required, then Docmosis will inject the given image at runtime from Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消