用Java寫一個PDF,Word文件轉換工具

来源:https://www.cnblogs.com/weloe/archive/2023/01/09/17038372.html
-Advertisement-
Play Games

前言 前段時間一直使用到word文檔轉pdf或者pdf轉word,尋思著用Java應該是可以實現的,於是花了點時間寫了個文件轉換工具 源碼weloe/FileConversion (github.com) 主要功能就是word和pdf的文件轉換,如下 pdf 轉 word pdf 轉 圖片 word ...


前言

前段時間一直使用到word文檔轉pdf或者pdf轉word,尋思著用Java應該是可以實現的,於是花了點時間寫了個文件轉換工具

源碼weloe/FileConversion (github.com)

主要功能就是word和pdf的文件轉換,如下

  • pdf 轉 word
  • pdf 轉 圖片
  • word 轉 圖片
  • word 轉 html
  • word 轉 pdf

實現方法

主要使用了pdfbox Apache PDFBox | A Java PDF Library以及spire.doc Free Spire.Doc for Java | 100% 免費 Java Word 組件 (e-iceblue.cn)兩個工具包

pom.xml

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>
    </dependencies>

策略介面

public interface FileConversion {

    boolean isSupport(String s);

    String convert(String pathName,String dirAndFileName) throws Exception;

}

PDF轉圖片實現

public class PDF2Image implements FileConversion{
    private String suffix = ".jpg";
    public static final int DEFAULT_DPI = 150;


    @Override
    public boolean isSupport(String s) {
        return "pdf2image".equals(s);
    }

    @Override
    public String convert(String pathName,String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        pdf2multiImage(pathName,outPath,DEFAULT_DPI);

        return outPath;
    }

    /**
     * pdf轉圖片
     * 多頁PDF會每頁轉換為一張圖片,下麵會有多頁組合成一頁的方法
     *
     * @param pdfFile pdf文件路徑
     * @param outPath 圖片輸出路徑
     * @param dpi 相當於圖片的解析度,值越大越清晰,但是轉換時間變長
     */
    public void pdf2multiImage(String pdfFile, String outPath, int dpi) {
        if (dpi <= 0) {
            // 如果沒有設置DPI,預設設置為150
            dpi = DEFAULT_DPI;
        }
        try (PDDocument pdf = PDDocument.load(new FileInputStream(pdfFile))) {
            int actSize = pdf.getNumberOfPages();
            List<BufferedImage> picList = new ArrayList<>();
            for (int i = 0; i < actSize; i++) {
                BufferedImage image = new PDFRenderer(pdf).renderImageWithDPI(i, dpi, ImageType.RGB);
                picList.add(image);
            }
            // 組合圖片
            ImageUtil.yPic(picList, outPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PDF轉word實現

public class PDF2Word implements FileConversion {

    private String suffix = ".doc";

    @Override
    public boolean isSupport(String s) {
        return "pdf2word".equals(s);
    }

    /**
     *
     * @param pathName
     * @throws IOException
     */
    @Override
    public String convert(String pathName,String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        pdf2word(pathName, outPath);

        return outPath;
    }


    private void pdf2word(String pathName, String outPath) throws IOException {
        PDDocument doc = PDDocument.load(new File(pathName));
        int pagenumber = doc.getNumberOfPages();
        // 創建文件
        createFile(Paths.get(outPath));

        FileOutputStream fos = new FileOutputStream(outPath);
        Writer writer = new OutputStreamWriter(fos, "UTF-8");
        PDFTextStripper stripper = new PDFTextStripper();


        stripper.setSortByPosition(true);//排序

        stripper.setStartPage(1);//設置轉換的開始頁
        stripper.setEndPage(pagenumber);//設置轉換的結束頁
        stripper.writeText(doc, writer);
        writer.close();
        doc.close();
    }

}

word轉html

public class Word2HTML implements FileConversion{
    private String suffix = ".html";

    @Override
    public boolean isSupport(String s) {
        return "word2html".equals(s);
    }

    @Override
    public String convert(String pathName, String dirAndFileName) {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        Document doc = new Document();
        doc.loadFromFile(pathName);
        doc.saveToFile(outPath, FileFormat.Html);
        doc.dispose();
        return outPath;
    }
}

word轉圖片

public class Word2Image implements FileConversion{
    private String suffix = ".jpg";

    @Override
    public boolean isSupport(String s) {
        return "word2image".equals(s);
    }

    @Override
    public String convert(String pathName, String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }

        Document doc = new Document();
        //載入文件
        doc.loadFromFile(pathName);
        //上傳文檔頁數,也是最後要生成的圖片數
        Integer pageCount = doc.getPageCount();
        // 參數第一個和第三個都寫死 第二個參數就是生成圖片數
        BufferedImage[] image = doc.saveToImages(0, pageCount, ImageType.Bitmap);
        // 組合圖片
        List<BufferedImage> imageList = Arrays.asList(image);
        ImageUtil.yPic(imageList, outPath);
        return outPath;
    }
}

word轉pdf

public class Word2PDF implements FileConversion{

    private String suffix = ".pdf";

    @Override
    public boolean isSupport(String s) {
        return "word2pdf".equals(s);
    }

    @Override
    public String convert(String pathName, String dirAndFileName) throws Exception {
        String outPath = dirAndFileName + suffix;
        if(Files.exists(Paths.get(outPath))){
            throw new RuntimeException(outPath+" 文件已存在");
        }
        //載入word
        Document document = new Document();
        document.loadFromFile(pathName, FileFormat.Docx);
        //保存結果文件
        document.saveToFile(outPath, FileFormat.PDF);
        document.close();
        return outPath;
    }
}

使用

輸入轉換方法,文件路徑,輸出路徑(輸出路徑如果輸入'null'則為文件同目錄下同名不同尾碼文件)

轉換方法可選項:

  • pdf2word
  • pdf2image
  • word2html
  • word2image
  • word2pdf

例如輸入:

pdf2word D:\test\testpdf.pdf null

控制台輸出:

轉換方法: pdf2word  文件: D:\test\testFile.pdf
轉換成功!文件路徑: D:\test\testFile.doc

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • VUE 筆記目錄:(https://www.cnblogs.com/wenjie2000/p/16378441.html) 視頻教程(P146~P148) 本篇是使用的vue2。雖然vue3.x已經出了,目前但對於後端人員來說瞭解一些vue2就足夠了。不需要過於深入學習 Vue是一套前端框架,免除原 ...
  • 電銷是什麼?就是坐席拿著電話給客戶打電話嗎?no no no,讓我們一起走進京音平臺之電銷系統。 京音平臺2020年初開始建設,過去的兩年多的時間里,經歷了跌宕起伏,有經驗、有教訓,整體來說平臺經歷了人工、自動化階段,目前處於初步智能化階段,希望可以將過去的一些心路歷程分享給大家,共同交流、共同進... ...
  • 每條if語句的核心都是一個值為True或False的表達式。Python根據條件測試的值為True還是False來決定是否執行if語句中的代碼。如果條件測試的值為True,Python就執行緊跟在if語句後面的代碼;如果為False,Python就忽略這些代碼。 1. 檢查是否相等:將一個變數的當前 ...
  • 最近刷leetcode題,使用了move()函數及優先隊列(堆)priority_queue數據結構,記錄一下! 1.move函數 move(obj)函數的功能是把obj當做右值處理,可以應用在對象的移動上。 右值引用 為了支持移動操作,新標準引入了一種新的引入類型——右值引用,所謂右值引用就是必須 ...
  • 元組 1. 元組:不可變的列表。元組一經創建不能被修改。 2. 表示:用圓括弧()來表示,並用逗號來分隔其中的元素。可通過索引訪問其元素。 3. 訪問:訪問列表元素,指出元組的名稱,再指出元素的索引,並將其放在方括弧內。請求獲取列表元素時,Python只返回該元素,而不包括方括弧和引號。元組訪問與列 ...
  • 2023-01-09 一、Mybatis映射文件 1、映射文件根標簽 mapping標簽: 該標簽中的namespace要求與介面的全類名一致 2、映射文件子標簽 (1)cache(該命名空間的緩衝配置) (2)cache-ref(引用其他命名空間的緩存配置) (3)resultMap(描述如何從數 ...
  • python數據分析與可視化常用庫 numpy+matplotlib+pandas 思維導圖 圖中難免有錯誤,後期隨著學習與應用的深入,會不斷修改更新。 當前版本號:1.0 numpy介紹 NumPy 是什麼? NumPy是使用Python進行科學計算的基礎軟體包。除其他外,它包括: 功能強大的N維 ...
  • 【列表一:操作列表】:這裡總結了操作列表的部分知識,包括使用for迴圈遍歷列表、range()函數介紹、使用range()函數創建數值列表,以及是列表的切片。 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...