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.运行代码结果

哈哈哈   欢迎各位道友吐槽哟   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@   哈哈哈

原文地址:https://www.cnblogs.com/zhukaixin/p/9154469.html