java將word文件轉為pdf


 

import java.io.File;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

public class Word2Pdf
{
public static void main(String args[])
{
ActiveXComponent app = null;
String wordFile = "C:/xxxxx.doc";
String pdfFile = "C:/xxxxx.pdf";
System.out.println("開始轉換...");
long start = System.currentTimeMillis();
try
{
// 打開word
app = new ActiveXComponent("Word.Application");
// app.setProperty("Visible", false);
// 獲得word中所有打開的文檔
Dispatch documents = app.getProperty("Documents").toDispatch();
System.out.println("打開文件: " + wordFile);
// 打開文檔
Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
// 如果文件存在的話,不會覆蓋,會直接報錯,所以我們需要判斷文件是否存在
File target = new File(pdfFile);
if (target.exists())
{
target.delete();
}
System.out.println("另存為: " + pdfFile);
// 另存為,將文檔報錯為pdf,其中word保存為pdf的格式宏的值是17
Dispatch.call(document, "SaveAs", pdfFile, 17);
// 關閉文檔
Dispatch.call(document, "Close", false);
// 結束時間
long end = System.currentTimeMillis();
System.out.println("轉換成功,用時:" + (end - start) + "ms");
}
catch (Exception e)
{
System.out.println("轉換失敗" + e.getMessage());
}
finally
{
// 關閉office
app.invoke("Quit", 0);
}
}
}

 

涉及jar包 jacob.jar 可在 http://sqdownb.onlinedown.net/down/74195_20170622162225.zip 下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM