Windows下将Word文档转换为PDF文档

Word文档转换为PDF文档效果最好的一种方法,但是需要window环境,而且速度是最慢的,并且需要安装msofficeWord以及SaveAsPDFandXPS.exe(word的一个插件,用来把word转化为pdf)

Office版本是2007(或者以上),因为SaveAsPDFandXPS是微软为office2007及以上版本开发的插件
SaveAsPDFandXPS下载地址:http://www.microsoft.com/zh-cn/download/details.aspx?id=7
jacob 包下载地址:http://sourceforge.net/projects/jacob-project/
我下的是jacob-1.17-M2.zip(下载最新的)
下载下来的jacob里的jar包导入到项目里,

jacob的dll文件放到到你的jdk/jre/bin下面(不放会报错:java.lang.NoClassDefFoundError: Could not initialize class com.jacob.com.Dispatch)

static final int wdFormatPDF = 17;// PDF 格式    
    public void wordToPDF(String docFileName){    

        System.out.println("启动Word...");      
        long start = System.currentTimeMillis();      
        ActiveXComponent app = null;  
        Dispatch doc = null;  
        try {      
            app = new ActiveXComponent("Word.Application");      
            app.setProperty("Visible", new Variant(false));  
            Dispatch docs = app.getProperty("Documents").toDispatch();    

            String path =  this.getSession().getServletContext().getRealPath("/")+"attachment/";
            String sfileName = path+"/doc/"+ docFileName + ".doc";
            String toFileName = path+"/pdf/"+ docFileName + ".pdf";

            doc = Dispatch.call(docs,  "Open" , sfileName).toDispatch();  
            System.out.println("打开文档..." + sfileName);  
            System.out.println("转换文档到PDF..." + toFileName);      
            File tofile = new File(toFileName);      
            if (tofile.exists()) {      
                tofile.delete();      
            }      
            Dispatch.call(doc,      
                          "SaveAs",      
                          toFileName, // FileName      
                          wdFormatPDF);      
            long end = System.currentTimeMillis();      
            System.out.println("转换完成..用时:" + (end - start) + "ms.");  


        } catch (Exception e) {      
            System.out.println("========Error:文档转换失败:" + e.getMessage());      
        } finally {  
            Dispatch.call(doc,"Close",false);  
            System.out.println("关闭文档");  
            if (app != null)      
                app.invoke("Quit", new Variant[] {});      
            }  
          //如果没有这句话,winword.exe进程将不会关闭  
           ComThread.Release();

    }
需要注意的是,如果没有安装SaveAsPDFandXPS.exe的话会提示

========Error:文档转换失败:Invoke of: SaveAs
Source: Microsoft Word
Description:

本文转载自:http://feifei.im/archives/93


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值