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