需求有一個将office檔案轉成PDF并添加水印的功能,office轉PDF需要用到jacob功能
轉化代碼
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
private static final int msoTrue = -1;
private static final int msofalse = 0;
public static boolean word2PDF(String inputFile,String pdfFile){
try{
ComThread.InitSTA();
//打開word應用程式
ActiveXComponent app = new ActiveXComponent("Word.Application");
//設定word不可見
app.setProperty("Visible", false);
//獲得word中所有打開的文檔,傳回Documents對象
Dispatch docs = app.getProperty("Documents").toDispatch();
//調用Documents對象中Open方法打開文檔,并傳回打開的文檔對象Document
Dispatch doc = Dispatch.call(docs,
"Open",
inputFile,
false,
true
).toDispatch();
//調用Document對象的SaveAs方法,将文檔儲存為pdf格式
/*
Dispatch.call(doc,
"SaveAs",
pdfFile,
wdFormatPDF //word儲存為pdf格式宏,值為17
);
*/
Dispatch.call(doc,
"ExportAsFixedFormat",
pdfFile,
wdFormatPDF //word儲存為pdf格式宏,值為17
);
//關閉文檔
Dispatch.call(doc, "Close",false);
//關閉word應用程式
app.invoke("Quit", 0);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally{
ComThread.Release();
}
}
public static boolean excel2PDF(String inputFile,String pdfFile){
try{
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Excel.Application");
app.setProperty("DisplayAlerts", "False");
app.setProperty("Visible", false);
Dispatch excels = app.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.call(excels,
"Open",
inputFile,
false,
true
).toDispatch();
Dispatch.call(excel,
"ExportAsFixedFormat",
xlTypePDF,
pdfFile
);
Dispatch.call(excel, "Close",false);
app.invoke("Quit");
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally{
ComThread.Release();
}
}
public static boolean ppt2PDF(String inputFile,String pdfFile){
try{
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
//app.setProperty("Visible", msofalse);
Dispatch ppts = app.getProperty("Presentations").toDispatch();
Dispatch ppt = Dispatch.call(ppts,
"Open",
inputFile,
true,//ReadOnly
true,//Untitled指定檔案是否有标題
false//WithWindow指定檔案是否可見
).toDispatch();
Dispatch.call(ppt,
"SaveAs",
pdfFile,
ppSaveAsPDF
);
Dispatch.call(ppt, "Close");
app.invoke("Quit");
return true;
}catch(Exception e){
return false;
}finally{
ComThread.Release();
}
}
這個是網上找到的功能,的确可以實作需求,但是有很明顯的缺陷。
代碼轉化完後會打開一個程序,但是結束時卻不會主動開閉,導緻記憶體占用最終崩潰。
是以要在 每個方法前 加上
ComThread.InitSTA();
結束加上
ComThread.Release(); //釋放程序
1. 注意事項
2.1 注意使用高版本的ofiice,建議office2010.
2.2啟動office的列印服務

将office列印設定為系統預設
2.3 由于高本版的office經常将excel自動設定為受保護的視圖,需要解除檔案狀态
Excel檔案 檔案--選項—信任中心—信任中心設定—受信任的位置-添加新位置(可能涉及到需要用到的檔案的地方,例如tomcat檔案夾和檔案上傳目錄)
2.4 服務啟動的tomcat使用jacob元件時要設定 DOCM權限,否則用不了。Tomcat catalina方式啟動或者main方式啟動不會有這個問題。
運作輸入 comexp.msc -32
找到 office Excel 和word ,右鍵屬性
辨別---互動式使用者
安全-配置權限 –編輯
将所有權限勾上