java实现word转pdf文件,并保存到本地磁盘
controller方法
/**
* 生成pdf文件
*/
@RequestMapping({"/getPdf"})
public JsonResult pdf(){
// 需要转换 目标word本地磁盘路径
String wordPath = "C:\\docxPath\\" + "测试word.doc";
// 转换为pdf后 存储到本地磁盘的pdf路径
String pdfPath = "C:\\fileUpload\\" + "测试pdf.pdf";
wordToPDF(wordPath,pdfPath);
}
public static void wordToPDF(String sfileName, String toFileName) {
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();
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
17);
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();
}
需要用到的gradle依赖包
compile group: 'net.sf.jacob-project', name: 'jacob', version: '1.14.3'
compile group: 'com.vividsolutions', name: 'jts', version: '1.13'