Showing posts with label adding image to word. Show all posts
Showing posts with label adding image to word. Show all posts

Wednesday, 11 September 2013

Adding An Image to Word programatically using Java

Purpose: Adding An Image to Word programatically using Java

Following Code will allow to add an Image to a Word file using Java from local or web based source.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
public class AddImageToWord
{
    public static void main(String[] args) throws Exception
    {
     String img = "";
      IDocument doc = new Document2004();
      doc.addEle(Paragraph.with("Image from Web URL:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      img = Image.from_WEB_URL("http://www.google.com/images/logos/ps_logo2.png").setHeight("100").setWidth("300").create().getContent();
      doc.addEle(img);
      doc.addEle(new BreakLine(2)); //Add two break lines
      doc.addEle(Paragraph.with("Image from Hard Disk:").create());
      doc.addEle(new BreakLine(2)); //Add two break lines
      String wh = Image.from_FULL_LOCAL_PATHL("D://Screen.png").getOriginalWidthHeight();
      String[] temp = wh.split("#");
      System.out.println(temp[0]);
      System.out.println(temp[1]);
      img = Image.from_FULL_LOCAL_PATHL("D://Screen.png").setHeight("300").setWidth("500").create().getContent();
      doc.addEle(img);
     
      File fileObj = new File("D://Java2word_allInOne.doc");
      PrintWriter writer = null;
      try {
          writer = new PrintWriter(fileObj);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      String myWord = doc.getContent();
      writer.println(myWord);
      writer.close();
    }
}