Java 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)
 */

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 Word2PDF {
	static final int wdFormatPDF = 17;// PDF 格式    
	
	
	
	public static void main(String[] args) {
		wordToPDF();
	}
    public static void wordToPDF(){    
 
        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 =  "F:\\";
            String sfileName = path+"1.docx";
            String toFileName = path+"1.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,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();
    }
}
发布了34 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36623327/article/details/88959270