5.1 java实现doc文档转pdf文件 > 我的程序猿之路:第四一章



 1 public static void main(String args[]) throws Exception{
 2         ActiveXComponent app = null;
 3         String wordFile = "C:\\Users\\FAN\\Desktop\\aa.doc";
 4         String pdfFile = "C:\\Users\\FAN\\Desktop\\aa1.pdf";
 5         System.out.println("开始转换...");
 6         // 开始时间
 7         long start = System.currentTimeMillis();
 8         try {
 9             // 打开word
10             app = new ActiveXComponent("Word.Application");
11             // 设置word不可见,很多博客下面这里都写了这一句话,其实是没有必要的,因为默认就是不可见的,如果设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的
12             //app.setProperty("Visible", false);
13             // 获得word中所有打开的文档
14             Dispatch documents = app.getProperty("Documents").toDispatch();
15             System.out.println("打开文件: " + wordFile);
16             // 打开文档
17             Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
18             // 如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在
19             File target = new File(pdfFile);
20             if (target.exists()) {
21                 target.delete();
22             }
23             System.out.println("另存为: " + pdfFile);
24             // 另存为,将文档报错为pdf,其中word保存为pdf的格式宏的值是17
25             Dispatch.call(document, "SaveAs", pdfFile, 17);
26             // 关闭文档
27             Dispatch.call(document, "Close", false);
28             // 结束时间
29             long end = System.currentTimeMillis();
30             System.out.println("转换成功,用时:" + (end - start) + "ms");
31         }catch(Exception e) {
32             System.out.println("转换失败"+e.getMessage());
33         }finally {
34             // 关闭office
35             app.invoke("Quit", 0);
36         }
37     }
用到2个文件
1.jacob.jar
2.jacob-1.18-x64.dll

导入jacob.jar包
jacob-1.18-x64.dll文件,放在jdk文件下面的bin目录下




原文作者:输出是最好的学习

来 源:CSDN
原 文:https://blog.csdn.net/m0_37568521/article/details/78545887
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/fanyuyi-boke/p/qiao_duo_shao_nian_dai_ma_neng_ba_shou_zhi_mo_ping41.html
5.1