请问如何在Java中将图片插入到Word文档中?
一个想法:
首先,您需要下载WordAPI,可以从这里下载。要在JAVA中创建Word文档,有一个类可以完成您所需的一切。该类称为WordProcessing。
以下是该类实现的方法的简短预览:
正如您所看到的,有许多有用的函数可用于创建文档。
现在,您可以通过调用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
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文字处理器,可以显示图片。