`

Jave Word转换成PDF

 
阅读更多

最近在做一个把word转换成pdf的需求,网上找了好多都不行,要不就依赖第三方插件,最后通过jacod实现了,记录一下        需要下载Jacob.jar包 ,把Jacob.dll放在jre/bin目录下 

 

package com.jieyuechina.util;

import java.io.File;

import org.apache.log4j.Logger;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jieyuechina.test.WordTest;

public class Office2Pdf {
	static final int wdFormatPDF = 17;// PDF 格式  
	public static final Logger log = Logger.getLogger(Office2Pdf.class);
    public void wordToPDF(String sfileName,String toFileName){  
       log.info("启动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();
            log.info("打开文档..." + sfileName);
            log.info("转换文档到PDF..." + toFileName);    
            File tofile = new File(toFileName);    
            if (tofile.exists()) {    
                tofile.delete();    
            }    
            Dispatch.call(doc, "SaveAs",  toFileName, wdFormatPDF);    
            long end = System.currentTimeMillis();    
            log.info("转换完成..用时:" + (end - start) + "ms.");
        } catch (Exception e) {    
        	log.info("========Error:word to pdf 文档转换失败:" + e.getMessage());    
        } finally {
        	Dispatch.call(doc,"Close",false);
            if (app != null)    
                app.invoke("Quit", new Variant[] {});    
            }
          //如果没有这句话,winword.exe进程将不会关闭
           ComThread.Release();   
	}
    public static void main(String[] args) {
    	Office2Pdf d = new Office2Pdf();
    	d.wordToPDF("d:\\outFile2.doc", "d:\\222.pdf");
	}

}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics