天天看點

Java word轉pdf 精确擷取檔案頁數(jacob)

注意: 該項目需在windows下進行, 如果需要商用需準備Windows伺服器

這裡我們用到的工具是jacob 需要建立一個maven項目添加以下依賴

<dependency>
            <groupId>net.sf.jacob-project</groupId>
            <artifactId>jacob</artifactId>
            <version>1.14.3</version>
            <scope>compile</scope>
        </dependency>
           

下一步就是配置我們的jacob

1.首先找到我們的jre安裝目錄, 我這裡的目錄是 C:\Program Files\Java\jdk1.8.0_241\jre\bin

Java word轉pdf 精确擷取檔案頁數(jacob)

然後将這兩個檔案複制到目錄中

  1. jacob-1.14.3-x64.dll
  2. jacob-1.14.3-x86.dll
jacob配置檔案下載下傳位址
連結:https://pan.baidu.com/s/1PLvmjzRu8nbQAOohqcd0uw 
提取碼:pd1o
           
Java word轉pdf 精确擷取檔案頁數(jacob)

完成以上的這些操作就可以直接開始編寫代碼進行頁數擷取

package com.yysd.pdfutil.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.*;

/**
 * @author dell
 */
public class Word2PdfUtil {

    // 不儲存待定的更改。
    static final int wdDoNotSaveChanges = 0;
    // word轉PDF 格式
    static final int wdFormatPDF = 17;


    /**
     * 測試main方法
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        // 需要傳入的 word 路徑可以是本機 也可以是網絡路徑
        Word2PdfUtil.word2pdf("http://8e2a-60-216-158-158.ngrok.io/aaaa.docx","C:\\Users\\dell\\Desktop\\wordpage\\web.pdf");
//      Word2PdfUtil.word2pdf("C:\\Users\\dell\\Desktop\\wordpage\\web.docx","C:\\Users\\dell\\Desktop\\wordpage\\web.pdf");

        String fileUrl  = "http://6820-58-56-64-2.ngrok.io/aaaa.docx";
        //截取發送過來的檔案名
        System.out.println(fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length() - 1));

        //将檔案下載下傳後儲存在D盤,傳回結果為下載下傳檔案大小
        long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("D:\\file"));

        System.out.println("Download size: " + size);

        //進行Md5加密
        System.out.println("加密後: "+DigestUtil.md5Hex(new FileInputStream("D:\\file\\aaaa.docx")));

//      建立需要解析的PDF檔案
        File file = new File("C:\\Users\\dell\\Desktop\\wordpage\\web.pdf");
//      加載檔案
        PDDocument doc = PDDocument.load(file);
//      通過工具類擷取頁數,列印
        System.out.println("頁數為 : "+doc.getNumberOfPages());

    }


    /**
     *   工具類
     * inputStream 轉 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception{
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 1024;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }


    public static boolean word2pdf(String source, String target) {
        System.out.println("Word轉PDF開始啟動...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            System.out.println("打開文檔:" + source);
            Dispatch doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();
            System.out.println("轉換文檔到PDF:" + target);
            File tofile = new File(target);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", target, wdFormatPDF);
            Dispatch.call(doc, "Close", false);
            long end = System.currentTimeMillis();
            System.out.println("轉換完成,用時:" + (end - start)/1000 + "秒");
            return true;
        } catch (Exception e) {
            System.out.println("Word轉PDF出錯:" + e.getMessage());
            return false;
        } finally {
            if (app != null) {
                app.invoke("Quit", wdDoNotSaveChanges);
            }
        }
    }
}
           

demo項目上傳到gitee 位址:

https://gitee.com/programmer-k/pdfutil.git