老板要求用java將word轉(zhuǎn)為PDF,這么搞?
1.? 引入pom文件
<dependency><groupId>com.jacobgroupId><artifactId>jacobartifactId><version>1.18version>dependency>
2.? 下載jar文件,手動(dòng)添加至maven倉(cāng)庫(kù)(無(wú)法直接拉取)
cmd進(jìn)入dos: 進(jìn)行以下命令操作,路徑進(jìn)行對(duì)應(yīng)修改
mvn install:install-file -Dfile=C:\Users\MingHao\Downloads\jacob-1.18\jacob-1.18\jacob.jar? -DgroupId=com.jacob -DartifactId=jacob? -Dversion=1.18 -Dpackaging=jar
解析:
-Dfile:本地jar包位置(未引入前)
-DgroupId:項(xiàng)目名 對(duì)應(yīng)
-DartifactId:文件名 對(duì)應(yīng)
-Dversion:版本號(hào) 對(duì)應(yīng)

3. ?在jdk/bin目錄下引入.dll文件(64位:jacob-1.18-x64.dll ?? ? ?32位:jacob-1.18-x86.dll)

資源文件云盤(pán)備份:
?
4.? ?準(zhǔn)備java代碼
import com.jacob.activeX.ActiveXComponent;import com.jacob.com.Dispatch;import java.io.File;public?class?Word2Pdf?{public static void main(String args[]) {ActiveXComponent app = null;String wordFile = "e:/測(cè)試word.docx";????????String?pdfFile?=?"e:/測(cè)試pdf.pdf";System.out.println("開(kāi)始轉(zhuǎn)換...");// 開(kāi)始時(shí)間long start = System.currentTimeMillis();try {// 打開(kāi)wordapp = new ActiveXComponent("Word.Application");// 設(shè)置word不可見(jiàn),很多博客下面這里都寫(xiě)了這一句話,其實(shí)是沒(méi)有必要的,因?yàn)槟J(rèn)就是不可見(jiàn)的,如果設(shè)置可見(jiàn)就是會(huì)打開(kāi)一個(gè)word文檔,對(duì)于轉(zhuǎn)化為pdf明顯是沒(méi)有必要的//app.setProperty("Visible", false);// 獲得word中所有打開(kāi)的文檔Dispatch documents = app.getProperty("Documents").toDispatch();System.out.println("打開(kāi)文件: " + wordFile);// 打開(kāi)文檔Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();// 如果文件存在的話,不會(huì)覆蓋,會(huì)直接報(bào)錯(cuò),所以我們需要判斷文件是否存在File target = new File(pdfFile);if (target.exists()) {target.delete();}System.out.println("另存為: " + pdfFile);// 另存為,將文檔報(bào)錯(cuò)為pdf,其中word保存為pdf的格式宏的值是17Dispatch.call(document, "SaveAs", pdfFile, 17);// 關(guān)閉文檔Dispatch.call(document, "Close", false);// 結(jié)束時(shí)間long end = System.currentTimeMillis();System.out.println("轉(zhuǎn)換成功,用時(shí):" + (end - start) + "ms");}catch(Exception e) {e.getMessage();System.out.println("轉(zhuǎn)換失敗"+e.getMessage());}finally {// 關(guān)閉officeapp.invoke("Quit", 0);}}}?
5.準(zhǔn)備word文檔 (格式:.docx)
? 路徑:e:/測(cè)試word.docx
6.windows環(huán)境準(zhǔn)備
windows電腦安裝wps office,并且設(shè)置wps office為默認(rèn)啟動(dòng)?。(最好不要使用microsoft word 微軟的需要激活,很麻煩,還不成功!)
注:jacb只能在windows系統(tǒng)使用,linux系統(tǒng)暫時(shí)無(wú)法解決
——————END——————
歡迎關(guān)注“Java引導(dǎo)者”,我們分享最有價(jià)值的Java的干貨文章,助力您成為有思想的Java開(kāi)發(fā)工程師!
