使用Java将图像插入word文档

时间:2011-02-09 05:49:48

标签: java ms-word

有人能指出我如何在Java中将图像插入word文档吗?

3 个答案:

答案 0 :(得分:2)

您要修改的word文件是什么格式? (OLE2,WordML,docx?)

通常,用于MSOffice文件修改的最广泛使用的库是Apache POI

同样this tutorial可能对您目前的情况有所帮助。

答案 1 :(得分:2)

只是一个想法:

首先,您需要下载WordAPI,可以直接下载here。要使用JAVA创建word文档,有一个类可以完成您需要的所有操作。该课程称为WordProcessing

以下是该课程中实施的方法的简短预览:

  • 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)< ----有意为你
  • quitApplication()
  • EXEC()

正如您所看到的,创建文档有很多有用的功能。

现在您可以通过调用executeMacro函数来插入图像。

宏可能如下所示:

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 

答案 2 :(得分:1)

假设docx正常,您可以使用docx4j。 AddImage示例包括:

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

无需运行Word即可让docx4j正常工作。

ps由于你的问题被标记为“swing”,你可能希望谷歌“docx4all”用于使用Swing实现的docx文字处理器,它显示图像。