在Java中向Word文档插入图片

7

请问如何在Java中将图片插入到Word文档中?

3个回答

2
你想要修改的 Word 文件是哪种格式?(OLE2、WordML、docx?)
通常用于 MSOffice 文件修改的最广泛使用的库是 Apache POI
此外,这个教程 在你目前的情况下可能会有所帮助。

2

一个想法:

首先,您需要下载WordAPI,可以从这里下载。要在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 

参数macroname应该包含宏的代码,如果没有,我们该如何传递它? - Govind Balaji

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);

运行docx4j无需运行Word。

顺便提一下,由于您的问题被标记为“swing”,您可能希望在Google上搜索“docx4all”,这是一个使用Swing实现的docx文字处理器,可以显示图片。


我尝试过这个,但是没有成功。AddImage.java文件有什么用?我已经看了代码,但是没有很清楚的想法。你能否请解释一下这段代码的作用? - jcrshankar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接