java 將word轉為PDF (100%與word軟件轉換一樣)


jdk環境:jdk_8.0.1310.11_64    (64位)

1.引入pom文件

<!-- word轉pdf(依賴windows本地的wps) -->
        <dependency>
            <groupId>com.jacob</groupId>
            <artifactId>jacob</artifactId>
            <version>1.18</version>
        </dependency>

2.下載jar文件,手動添加至maven倉庫(無法直接拉取)

cmd進入dos:

  進行以下命令操作,路徑進行對應修改

  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:項目名 對應 <groupId>com.jacob</groupId>
      -DartifactId:文件名 對應 <artifactId>jacob</artifactId>
      -Dversion:版本號 對應 <version>1.18</version>

     

 

 

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

   

  資源文件雲盤備份:

 

 

 

4.准備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:/測試word.docx";
        String pdfFile = "e:/測試pdf.pdf";

        System.out.println("開始轉換...");
        // 開始時間
        long start = System.currentTimeMillis();
        try {
            // 打開word
            app = new ActiveXComponent("Word.Application");
            // 設置word不可見,很多博客下面這里都寫了這一句話,其實是沒有必要的,因為默認就是不可見的,如果設置可見就是會打開一個word文檔,對於轉化為pdf明顯是沒有必要的
            //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) {
            e.getMessage();
            System.out.println("轉換失敗"+e.getMessage());
        }finally {
            // 關閉office
            app.invoke("Quit", 0);
        }
    }

}

 

5.准備word文檔 (格式:.docx)

   路徑:e:/測試word.docx

6.windows環境准備

  windows電腦安裝wps office,並且設置wps office為默認啟動 。(最好不要使用microsoft word 微軟的需要激活,很麻煩,還不成功!)

注:jacb只能在windows系統使用,linux系統暫時無法解決

 

 


免責聲明!

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



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