2

how to insert image into word document using java

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at the Apache POI API.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.