Java利用jacob实现文档格式转换

实现文档格式之间的转换,我使用的是jacob-1.7版本,需要jacob.jar来调用activex控件,本机需安装WPS/office,还需要jacob.jar以及jacob.dll 

其中:
    jacob.dll 需要放置在系统system32下,如果系统是c盘:C://windows/system32/下面 

    jacob.dll放在类似这样的目录下,D:Javajre1.8.0_31in

public class Word2Pdf {

/*将office word文档转换为PDF*/
public void word2PDF(String inputFile,String pdfFile){

//打开word应用程序
ActiveXComponent app = new ActiveXComponent("Word.Application");
try {
//设置word不可见,否则会弹出word界面
app.setProperty("Visible", new Variant(false));
//获得word中所有打开的文档,返回Documents对象
Dispatch docs = app.getProperty("Documents").toDispatch();
//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
Dispatch doc = Dispatch.call(docs, "Open", inputFile).toDispatch();
//调用Document对象的SaveAs方法,将文档保存为pdf格式
Dispatch.call(doc,
"SaveAs",
new Variant(pdfFile),
17 //word保存为pdf格式
);
//关闭文档
Dispatch.call(doc, "Close",true);
//关闭word应用程序
app.invoke("Quit");
} catch (Exception e) {
System.out.println(e.getMessage());
app.invoke("Quit");
}
}

/*将office excel文档转换为PDF*/
public void excel2PDF(String inputFile,String pdfFile){

//打开excel应用程序
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
//设置excel不可见,否则会弹出word界面
app.setProperty("Visible", false);
//获得excel中所有打开的文档,返回Workbooks对象
Dispatch excels = app.getProperty("Workbooks").toDispatch();
//调用Workbooks对象中Open方法打开文档,并返回打开的文档对象excel
Dispatch excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
//调用excel对象的SaveAs方法,将文档保存为pdf格式
Dispatch.call(excel,
"ExportAsFixedFormat",
0, //excel保存为pdf格式
pdfFile
);
//关闭文档
Dispatch.call(excel, "Close",true);
//关闭excel应用程序
app.invoke("Quit");
} catch (Exception e) {
System.out.println(e.getMessage());
app.invoke("Quit");
}
}

/*将office ppt文档转换为PDF*/
public void ppt2PDF(String inputFile,String pdfFile){

//打开ppt应用程序
ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
try {
//设置ppt不可见,否则会弹出ppt界面
/*app.setProperty("Visible", new Variant(false));*/
//获得ppt中所有打开的文档,返回ppts对象
Dispatch ppts = app.getProperty("Presentations").toDispatch();
//调用ppts对象中Open方法打开文档,并返回打开的文档对象ppt
Dispatch ppt = Dispatch.call(ppts, "Open", inputFile,
true,// ReadOnly
true,// Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch();
//调用ppt对象的SaveAs方法,将文档保存为pdf格式
Dispatch.call(ppt,
"SaveAs",
/*"ExportAsFixedFormat",*/
pdfFile,
32 //ppt保存为pdf格式
);
//关闭文档
Dispatch.call(ppt, "Close",true);
//关闭ppt应用程序
app.invoke("Quit");
} catch (Exception e) {
System.out.println(e.getMessage());
app.invoke("Quit");
}
}

public static void main(String[] args) throws Exception {
Word2Pdf word2Pdf = new Word2Pdf();
/*word2Pdf.word2PDF("D:/test/#6测试文档.docx", "D:/test/#6测试文档");*/
/*word2Pdf.excel2PDF("D:/test/燃机控制油系统巡检卡.xlsx", "D:/test/燃机控制油系统巡检卡");*/
/*word2Pdf.ppt2PDF("D:/test/设计.pptx", "D:/test/设计.pdf");*/
}
}

原文地址:https://www.cnblogs.com/vofill/p/6381895.html