java 將word轉為PDF (100%與word軟體轉換一樣)
阿新 • • 發佈:2021-12-22
1.在jdk/bin目錄下引入.dll檔案(64位:jacob-1.18-x64.dll 32位:jacob-1.18-x86.dll)
import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import java.io.File; public class Word2Pdf { public static void main(String args[]) { ActiveXComponent app = null; String wordFile = "e:/測試word.docx"; String pdfFile = "e:/測試pdf.pdf"; System.out.println("開始轉換..."); // 開始時間 long start = System.currentTimeMillis(); try { // 開啟word app = new ActiveXComponent("Word.Application"); //WPS為:KWPS.Application // 設定word不可見,很多部落格下面這裡都寫了這一句話,其實是沒有必要的,因為預設就是不可見的,如果設定可見就是會開啟一個word文件,對於轉化為pdf明顯是沒有必要的 //app.setProperty("Visible", false); // 獲得word中所有開啟的文件 Dispatch documents = app.getProperty("Documents").toDispatch(); System.out.println("開啟檔案: " + wordFile); // 開啟文件 Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch(); // 如果檔案存在的話,不會覆蓋,會直接報錯,所以我們需要判斷檔案是否存在 File target = new File(pdfFile); if (target.exists()) { target.delete(); } System.out.println("另存為: " + pdfFile); // 另存為,將文件報錯為pdf,其中word儲存為pdf的格式巨集的值是17 Dispatch.call(document, "SaveAs", pdfFile, 17); // 關閉文件 Dispatch.call(document, "Close", false); // 結束時間 long end = System.currentTimeMillis(); System.out.println("轉換成功,用時:" + (end - start) + "ms"); }catch(Exception e) { e.getMessage(); System.out.println("轉換失敗"+e.getMessage()); }finally { // 關閉office app.invoke("Quit", 0); } } }
注意事項:
windows電腦安裝wps office,並且設定wps office為預設啟動。(最好不要使用microsoft word 微軟的需要啟用,很麻煩,還不成功!)
相關資源:
jacob-1.18-x64.dll,jacob.jar
連結:https://pan.baidu.com/s/1Cx9f_6kmJirTkvbq9dloDw
提取碼:ejq2