2

how to insert image into word document using java

RubyDubee
  • 2,426
  • 2
  • 23
  • 34
user302267
  • 161
  • 2
  • 2
  • 4

4 Answers4

1

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

Amitabh Ranjan
  • 1,500
  • 3
  • 23
  • 39
1

Take a look at the Apache POI API.

ninesided
  • 23,085
  • 14
  • 83
  • 107
0

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.

Paul Jowett
  • 6,513
  • 2
  • 24
  • 19