本文實例為大家分享了java開發利用jacob將word轉pdf的具體代碼,供大家參考,具體內容如下
jacob 缺點:需要 window 環境,而且速度是最慢的需要安裝 msofficeword 以及 saveaspdfandxps.exe ( word 的一個插件,用來把 word 轉化為 pdf )
開發流程:
SaveAsPDFandXPS 下載地址
jacob 包下載地址:
1、先安裝saveaspdfandxps
2、下載 jacob 解壓后存放路徑:
jacob.jar 放在 c:\program files\java\jdk1.8.0_171\jre\lib\ext目錄下
jacob.dll 放在 c:\program files\java\jdk1.8.0_171\jre\bin 目錄下
實現代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
package com.casf.hn.core.util; import java.io.file; import com.jacob.activex.activexcomponent; import com.jacob.com.comthread; import com.jacob.com.dispatch; import com.jacob.com.variant; /** * 效果最好的一種方法,但是需要 window 環境,而且速度是最慢的需要安裝 msofficeword 以及 saveaspdfandxps.exe ( * word 的一個插件,用來把 word 轉化為 pdf,可以不用安裝,本次未安裝測試通過 ) * * * */ public class wordtopdf { private static final int wdformatpdf = 17 ; // pdf 格式 public 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 wdformatpdf); 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(); } public static void main(string[] args) { wordtopdf d = new wordtopdf(); d.wordtopdf( "d:\\cssj\\xxxx.doc" , "d:\\cssj\\xxxx.pdf" ); } } |
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq493820798/article/details/80420140