开发者

Insert an image into a word document in Java

Can someone point me in the rig开发者_如何学Cht direction on how to insert an image into a word document in Java?


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 


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.


Assuming docx is OK, you could use docx4j. The AddImage sample includes:

org.docx4j.wml.P p = newImage( wordMLPackage, bytes, 
            filenameHint, altText, 
            id1, id2 );
// Now add our p to the document
wordMLPackage.getMainDocumentPart().addObject(p);

No need to be running Word for docx4j to work.

ps Since your question is tagged "swing", you may wish to Google "docx4all" for a docx word processor implemented using Swing, which displays images.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜