Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an image into a word document in Java

Tags:

java

ms-word

Can someone point me in the right direction on how to insert an image into a word document in Java?

like image 666
jcrshankar Avatar asked Feb 09 '11 05:02

jcrshankar


2 Answers

Just an idea:

At first you will need to download the WordAPI, which can be downloaded right here. To create word documents with JAVA, there's a class doing everything you need. The class is called WordProcessing.

Here's a short preview of the methods implemented in that class:

  • createNewDocumentFromTemplate(String templateName)
  • createNewDocumentFromTemplateToSelectByUser()
  • setNoteNotMatchingBookmarks(boolean noteNotMatchingBookmarks)
  • typeTextAtBookmark(String bookmark, String textToType)
  • typeTextAtBookmark(String bookmark, String[] linesToType)
  • changeDocumentDirectory(String documentDirectory)
  • saveDocumentAs(String documentName)
  • saveDocumentAsAndClose(String documentName)
  • closeDocument()
  • printAndForget()
  • printToPrinterToSelectByUserAndForget()
  • printAndForget(String printerName)
  • executeMacro(String macroName) <---- Interesting for you
  • quitApplication()
  • exec()

As you can see there are a lot of helpful functions to create your document.

Now you can insert an image by calling the executeMacro function.

The Macro could look like this:

Option Explicit

Sub InsertPicture()

   Dim sPath As String
   Dim sBildPfad As String
   Dim lRes As Long

   'The path of your picture
   sBildPfad = "C:\temp"

   'remember the current path of the picture
   sPath = Options.DefaultFilePath(Path:=wdPicturesPath)

   'changing the path
   Options.DefaultFilePath(Path:=wdPicturesPath) = sBildPfad

   'open dialog
   lRes = Application.Dialogs(wdDialogInsertPicture).Show

   'reset path
   Options.DefaultFilePath(Path:=wdPicturesPath) = sPath

   If lRes <> 0 And ActiveDocument.InlineShapes.Count > 0 Then
      'if inserted, changing the size
      Call PicSize(ActiveDocument.InlineShapes(ActiveDocument.InlineShapes.Count))
   End If

End Sub

Sub PicSize(oPic As InlineShape)
   Dim iScale As Single
   Dim iWidth As Single

   iWidth = 200 ' (pixel)

   oPic.LockAspectRatio = msoTrue
   ' scaling
   iScale = (iWidth / oPic.Width) * 100
   oPic.ScaleWidth = iScale
   oPic.ScaleHeight = iScale
End Sub 
like image 60
oopbase Avatar answered Oct 20 '22 04:10

oopbase


What format is the word file you want to modify ? (OLE2, WordML, docx ?)

Generally the most widely used library for MSOffice file modification is Apache POI.

Also this tutorial will probably be helpful in your current case.

like image 2
Simeon Avatar answered Oct 20 '22 02:10

Simeon