定义:
Jacob:它允许在java中调用COM接口自动组件,它使用JNI(本地调用程序)来进行本地调用COM库。
注意:
jacob只能在windows系统上运行。项目中服务器必须是windows server。
原因:
jacob需要借助Microsoft Office软件做pdf转换操作,因此需要在服务器上安装Microsoft Office 07/10/13。
一定要确保是64位的!!!一定要确保是64位的!!!一定要确保是64位的!!!
方法:
1.在pom中引入jar包
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jacob</artifactId>
<version>1.18</version>
</dependency>
2.64位系统就用 x64的dll,32位系统就用x86的dll。将dll文件放入C:\Windows\System32
/**
* 将excel转成pdf
* @param inFilePath
* @param outFilePath
* @throws Exception
*/
public static void excelToPdf(String inFilePath, String outFilePath) throws Exception {
ActiveXComponent ax = null;
Dispatch excel = null;
try {
ComThread.InitSTA();
ax = new ActiveXComponent("Excel.Application");
ax.setProperty("Visible", new Variant(false));
ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch excels = ax.getProperty("Workbooks").toDispatch();
Object[] obj = new Object[]{
inFilePath,
new Variant(false),
new Variant(false)
};
excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
// 转换格式
Object[] obj2 = new Object[]{
new Variant(0), // PDF格式=0
outFilePath,
new Variant(0) //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
};
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);
} catch (Exception es) {
es.printStackTrace();
throw es;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close", new Variant(false));
}
if (ax != null) {
ax.invoke("Quit", new Variant[]{});
ax = null;
}
ComThread.Release();
}
}