在此先聲明最重要的一點:使用jacob將html導入word時圖片是使用鏈接的方式引入的,也就是說如果你的圖片刪除了,那么word中圖片也沒了。
原文鏈接:https://blog.csdn.net/feicy101/article/details/52134938?locationNum=15
本人是對原文鏈接中 :jacob替換圖片 進行了測試
maven:
<dependency> <groupId>net.sf.jacob-project</groupId> <artifactId>jacob</artifactId> <version>1.14.3</version> </dependency>
原文代碼:
package com.thinkgem.jeesite.test; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; /** * @author liuwei * @date 2018年9月30日 上午10:58:23 * */ public class InsertPicToWord { /** * 給指定的word文檔在字符串指定位置插入圖片 * @param wordFile word文檔 * @param imagePath 待添加圖片的路徑 * @param tarStr 指定的字符串位置 */ public static void insertImage(String wordFile, String imagePath, String tarStr) { ActiveXComponent app = new ActiveXComponent("Word.Application");// 啟動word try { app.setProperty("Visible", new Variant(false));// 設置word不可見 Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke( docs, "Open", Dispatch.Method, new Object[] { wordFile, new Variant(false), new Variant(false) }, new int[1]).toDispatch(); // 打開word文件,注意這里第三個參數要設為false,這個參數表示是否以只讀方式打開, // 因為我們要保存原文件,所以以可寫方式打開。 Dispatch selection = app.getProperty("Selection").toDispatch(); Dispatch.call(selection, "HomeKey", new Variant(6));// 移到開頭 Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 獲得Find組件 Dispatch.put(find, "Text", tarStr);// 查找字符串tarStr Dispatch.call(find, "Execute");// 執行查詢 Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);// 在指定位置插入圖片 Dispatch.call(doc, "Save");// 保存 Dispatch.call(doc, "Close", new Variant(false)); } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); app.safeRelease(); } } }
測試:
package com.thinkgem.jeesite.test; /** * @author liuwei * @date 2018年9月30日 上午11:00:30 * */ public class InsertPicToWordTest { @SuppressWarnings("static-access") public static void main(String[] args) { // TODO Auto-generated method stub InsertPicToWord word = new InsertPicToWord(); String wordFile = "C:\\Users\\admin\\Desktop\\1.doc"; String imagePath = "C:\\Users\\admin\\Desktop\\2.jpg"; String tarStr = "${image1}"; word.insertImage(wordFile, imagePath, tarStr); } }
你要下載jacob(要和自己項目里dependience中的版本一致),在找到下載jacob里的jacob-1.14.3-x64.dll【和操作系統版本一致】,
將這個文件依次貼到E:\jdk\jre1.8\bin和E:\jdk\1.8\jre\bin【否則會報錯:no jacob-1.14.3-x64 in java.library.path】
執行測試后手動創建的1.doc里確實有了圖片,但是程序也在我的桌面上創建了一個文件夾,該文件夾里存有一張被更名的圖片【即原圖2.jpg】,我將該文件夾刪除后,1.doc中的圖片也消失了,也就是說,這種實現方式是將圖片以鏈接的引入word里的。
這種方式適合向word文檔里寫入文字,對於圖片實現方式不太好。