[英]Insert an image into a word document in Java
有人能指出我如何在Java中将图像插入word文档吗?
What format is the word file you want to modify ? 您要修改的word文件是什么格式? (OLE2, WordML, docx ?) (OLE2,WordML,docx?)
Generally the most widely used library for MSOffice file modification is Apache POI . 通常,最广泛使用的MSOffice文件修改库是Apache POI 。
Also this tutorial will probably be helpful in your current case. 此教程也可能对您当前的情况有所帮助。
Just an idea: 只是一个想法:
At first you will need to download the WordAPI, which can be downloaded right here . 首先,您需要下载WordAPI,可以在此处下载。 To create word documents with JAVA, there's a class doing everything you need. 要使用JAVA创建word文档,有一个类可以完成您需要的所有操作。 The class is called WordProcessing . 该类称为WordProcessing 。
Here's a short preview of the methods implemented in that class: 以下是该类中实现的方法的简短预览:
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. 现在,您可以通过调用executeMacro函数来插入图像。
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
Assuming docx is OK, you could use docx4j. 假设docx正常,您可以使用docx4j。 The AddImage sample includes: AddImage示例包括:
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. 无需运行Word for docx4j即可运行。
ps Since your question is tagged "swing", you may wish to Google "docx4all" for a docx word processor implemented using Swing, which displays images. ps由于你的问题被标记为“swing”,你可能希望谷歌“docx4all”用于使用Swing实现的docx文字处理器,它显示图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.