1、在pom文件中添加maven 依赖
<dependency>
<groupId>net.sf.jacob-project</groupId>
<artifactId>jacob</artifactId>
<version>1.14.3</version>
</dependency>
2、下载jacob-1.18
3、主代码
public void wordToPDF(String sfileName, String toFileName)
{
System.out.println("启动Word...");
long start = System.currentTimeMillis();
ComThread.InitSTA();//必须先启动winword.exe进程
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();
}
4.将下载好的jacob-1.18中的jacob-1.18-x64.dll文件复制到jdk的bin目录下,以及jre的bin目录下
5、方法调用完美实现
public static void main(String[] args)
{
Test d = new Test();
d.wordToPDF("E:/111.docx", "E:/合同文本2014.pdf");
}