java 實現word 轉 pdf


                        java 實現word  轉 pdf

 

不知道網上為啥道友們寫的這么復雜  ,自己看到過一篇還不錯的  , 自己動手改了改 ,測試一下可以用  , 希望大家可以參考一下 , 對大家有幫助

1.引入jar包

(下載jar 地址親測有效:jacob.jar)

2.代碼

 1 public static void wToPdfChange(String wordFile,String pdfFile){//wordFile word 的路徑  //pdfFile pdf 的路徑 
 2         
 3          ActiveXComponent app = null;
 4            System.out.println("開始轉換...");
 5            // 開始時間
 6           // long start = System.currentTimeMillis();  
 7            try {
 8             // 打開word
 9             app = new ActiveXComponent("Word.Application");
10             // 獲得word中所有打開的文檔
11             Dispatch documents = app.getProperty("Documents").toDispatch();
12             System.out.println("打開文件: " + wordFile);
13             // 打開文檔
14             Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
15             // 如果文件存在的話,不會覆蓋,會直接報錯,所以我們需要判斷文件是否存在
16             File target = new File(pdfFile);  
17              if (target.exists()) {  
18                 target.delete();
19              }
20             System.out.println("另存為: " + pdfFile);
21             Dispatch.call(document, "SaveAs", pdfFile, 17);
22             // 關閉文檔
23             Dispatch.call(document, "Close", false);
24            }catch(Exception e) {
25             System.out.println("轉換失敗"+e.getMessage());
26            }finally {
27              // 關閉office
28             app.invoke("Quit", 0);
29            }
30     }

3. 測試代碼

1 public static void main(String[] args) {
2         
3         
4         String word = "D:/可成品/java.docx";
5         String name = "zhukaixin".concat(".pdf");
6         String pdf = "D:\\"+name;
7         wToPdfChange(word, pdf);
8     }

4.運行代碼結果

 

哈哈哈   歡迎各位道友吐槽喲   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@   哈哈哈


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM