`

java使用jacob word 转pdf

阅读更多
查询了很多网站 知道使用jacob 可以将word 转换成pdf;

首先我自己的环境是windows xp ,office2007 ,jdk1.5;

1.先下载office2007 能另存为pdf的插件 SaveAsPDFandXPS.exe 安装

2.附件提供了jacob1.9的下载

3.这点很重要也是耗时我最久的就是jacob.dll与jacob.jar的存放位置;位置不对则会出现app.getProperty("Documents").toDispatch()这句话无法正常执行;

位置如下文件存放在jdk的jre下 例如我这边是
jacob.jar 放在 E:\jdk1.5.0_14\jre\lib\ext
jacob.dll 放在 E:\jdk1.5.0_14\jre\bin
下能正常执行;
按网上说的 放在windows\system32下则会出现错误

源代码如下:
static final int wdFormatPDF = 17;// PDF 格式  
    public void wordToPDF(String sfileName,String toFileName){  
          
        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();  
            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();   
	}
    public static void main(String[] args) {
    	Test d = new Test();
    	d.wordToPDF("E:\\321.doc", "E:\\test_321test.pdf");
	}

分享到:
评论
4 楼 mengzhimin2011 2015-08-31  
启动Word...
Exception in thread "main" java.lang.NoSuchMethodError: com.jacob.com.Dispatch.call(Lcom/jacob/com/Dispatch;Ljava/lang/String;[Ljava/lang/Object;)Lcom/jacob/com/Variant;
at com.word.CopyOfWordConPfd.wordToPDF(CopyOfWordConPfd.java:96)
at com.word.CopyOfWordConPfd.main(CopyOfWordConPfd.java:106)

怎么处理啊?
3 楼 zengxuefei 2014-07-11  
不错,楼主给力
2 楼 kugoooooo 2014-06-24  
为什么我每次执行到Dispatch.call(doc, "Close", false);时就报错呢,报错信息:
启动Word...
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class com.jacob.com.Dispatch
at ext.rcw.WordToPdf.wordToPDF(WordToPdf.java:45)
at ext.rcw.WordToPdf.main(WordToPdf.java:56)
1 楼 xiexiaoming052 2014-06-24  
我也是

相关推荐

Global site tag (gtag.js) - Google Analytics