java 版 word装pdf

资源支持:

1. 需要安装word2007 及 SaveAsPDFandXPS.exe补丁

2.添加jacob支持

 下载 jacob-1.17-M2.zip 

 1.其中的dll( jacob-1.17-M2-x86.dll、jacob-1.17-M2-x64.dll) 复制到 C:\Windows\System32 去

 2.eclipse中 添加 jacob.jar的应用


实现代码:

package jacob;

import java.io.File;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
  
public class Test {  
    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" , sourceFile).toDispatch();   
            doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] {                    
               sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch();               
            System.out.println("打开文档..." + sfileName);  
            System.out.println("转换文档到PDF..." + toFileName);      
            File tofile = new File(toFileName);      
            if (tofile.exists()) {      
                tofile.delete();      
            }        
//          Dispatch.call(doc, "SaveAs",  destFile,  17);                    
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {                
                toFileName, new Variant(17) }, new int[1]);    
            long end = System.currentTimeMillis();      
            System.out.println("转换完成..用时:" + (end - start) + "ms.");                
        } catch (Exception e) {  
            e.printStackTrace();  
            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("d:\\27.doc", "d:\\27.pdf");  
    }  
  
}  


你可能感兴趣的:(java 版 word装pdf)