前提:word是office 2010版的(提取码:ba1b)
1、引入jacob.jar包
2、分别在对应位置引入jacob-1.17-x64.dll文件
(1)Tomcat的bin下
(2)jdk的bin下
(3)jre的bin下
(4)C:\Windows\System32 的下面
3、编写代码
package com.test;
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 {
public static void main(String[] args) {
String realPath="D:/file/"; //文件路径
String fileName="测试文档.docx"; //word文件名称
wordToPDF(realPath+fileName,realPath+fileName.substring(0,fileName.lastIndexOf("."))+".pdf");
if(new File(realPath+fileName.substring(0,fileName.lastIndexOf("."))+".pdf").exists()){
System.out.println("转换成功,请前往"+realPath+"查看");
}else{
System.out.println("转换失败");
}
}
//转换:参数【原word文件地址,转换后的pdf文件地址】
public static void wordToPDF(String wordpath,String pdfpath){
//ActiveXComponent 一个已经编译好的基于COM的软件组件,通过DCOM实现了对调用程序的透明化
ActiveXComponent app = null;
Dispatch doc = null; //Dispatch:调度处理类,封装了一些方法来操作office,里面所有的可操作对象基本都是这种类型
try {
app = new ActiveXComponent("Word.Application"); //调用word应用程序
app.setProperty("Visible", new Variant(false)); //设置组件是否可见(不可见:打开的过程都是隐藏的)
Dispatch docs = app.getProperty("Documents").toDispatch(); //获取所有文档并将文档转换成 Dispatch类型
doc = Dispatch.call(docs, "Open" ,wordpath).toDispatch(); //call()方法:调用COM对象的方法;Open:打开word文档
File tofile = new File(pdfpath);
if (tofile.exists()) {
tofile.delete(); //存在便删除
}
Dispatch.call(doc,"SaveAs",pdfpath,17); //将文档另存到pdfpath,文档类型是17【pdf格式】
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
Dispatch.call(doc,"Close",false); //关闭
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//结束后关闭进程
ComThread.Release();
}
}
4、在文件路径中放入word文件
5、启动项目
6、查看效果
PS:完整版项目(提取码:9o7h)
(1)new Variant(true)组件的是否可见
(2)文档参数参考值,数据来源于网络
0 | Doc |
1 | Dot |
2-5 | Txt |
6 | Rtf |
7 | Txt |
8、10 | htm |
11 | Xml |
12、16 | Docx |
13 | Docm |
14 | Dotx |
15 | Dotm |
17 | |