使用Java将图像插入到Word文档中
有人能指出我如何在Java中将图像插入word文档吗?
只是一个想法:
首先,您需要下载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()
正如您所看到的,创建文档有很多有用的function。
现在,您可以通过调用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
您要修改的word文件是什么格式? (OLE2,WordML,docx?)
通常,最广泛使用的MSOffice文件修改库是Apache POI 。
此教程也可能对您当前的案例有所帮助。
假设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 for docx4j即可运行。
ps由于你的问题被标记为“swing”,你可能希望谷歌“docx4all”用于使用Swing实现的docx文字处理器,它显示图像。