java代码将office转成pdf-1

2018-06-30  本文已影响0人  一路清寒

应公司需求,要将docx,xls .等格式要转pdf还要转成图片 浏览 之前想了一个快捷方法,用linux命令脚本转,openoffice ,发现很大问题,转化速度太慢,页码多的情况下,太消耗资源,300页多转换过程中,服务器可能就挂掉。然后就推翻掉。虽然不要写代码,而且中文支持很好。就几行命令

之后就想了,直接用java 编码吧。

之前写好了测试。好久没贴出来,今天找了半天。测试了一下发现xlsx格式不能转换了,有点奇怪,先粘出来docx的把,这问题,我等下在调一下。

依赖的jar 我就直接截图了。你们需要的话,对照下就行。

spring, struts2 大家忽略 哈哈

好了 ,我也好不容易找齐了依赖,然后就在网上找了代码整理一下 代码的话 很简单 我主要想保存资料,然后分享下,以后有用的可以直接来找了。


public class Word2Pdf {

          public static void main(String args[]) {

        ActiveXComponent app = null;

        String wordFile = "D:\\temp\\a.docx";

      String pdfFile = "D:/temp/a222.pdf";

      System.out.println("开始转换...");

      // 开始时间

      long start = System.currentTimeMillis(); 

try {

        // 打开word

        app = new ActiveXComponent("Word.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) {

        System.out.println("转换失败"+e.getMessage());

      }finally {

            // 关闭office

        app.invoke("Quit", 0);

      }

    }

}

测试结果:

下面在分享转存图片的。在下一个文章里

上一篇 下一篇

猜你喜欢

热点阅读