//將docx檔案裝換成pdf
public void wordToPdf(String sfileName,String toFileName){
//final int wdFormatPDF = 17; // PDF 格式
System.out.println("啟動 Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null; //word運行程式物件
Dispatch doc = null; // 所有word檔案集合
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);
// Dispatch.invoke(doc,
// "SaveAs",
// Dispatch.Method,
// new Object[] {toFileName,new Variant(17)},
// new int[1]);
//Dispatch.call(doc, "SaveAs" , new Variant( toFileName)); // 保存一個新檔案
long end = System.currentTimeMillis();
System.out.println("轉換完成..用時:" + (end - start) + "ms.");
} catch (Exception e) {
System.out.println("========Error:檔案轉換失敗:" + e.getMessage());
} finally {
if(doc!=null){
Dispatch.call(doc, "Close", false);
doc=null;
}
System.out.println("關閉檔案");
if (app != null){
app.invoke("Quit", new Variant[] {});
app=null;
}
// 如果沒有這句話,winword.exe行程將不會關閉
ComThread.Release();
}
}
報錯為:
啟動 Word...
打開檔案...F:/images/youlike_upload/a6b56b9eda104ae285bd14dc422de86d.docx
轉換檔案到 PDF...F:/images/youlike_upload/a6b56b9eda104ae285bd14dc422de86d.pdf
========Error:檔案轉換失敗:Invoke of: SaveAs
Source: Microsoft Word
Description: 命令失敗
關閉檔案
//////////////////////////////
專案啟動后只正確執行了一次,之后就報錯了。請大佬指點呀
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/113254.html
標籤:Java相關
