最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java將Word轉(zhuǎn)換成PDF的常用用法

 更新時(shí)間:2024年08月03日 08:59:33   作者:一個(gè)新人程序猿  
Java開發(fā)人員在處理文檔轉(zhuǎn)換時(shí),常常需要將Word或Excel文檔轉(zhuǎn)換為PDF格式,以便于更好地保持格式一致性、便于分發(fā)和打印,這篇文章主要給大家介紹了關(guān)于Java將Word轉(zhuǎn)換成PDF的常用用法,需要的朋友可以參考下

java中word轉(zhuǎn)換PDF的常用用法

1、POI

POI是Apache下的一個(gè)Java類庫,可以幫助我們實(shí)現(xiàn)Java與各種Office格式文件的互相轉(zhuǎn)換。(不推薦,只能用于文字的文檔,如果有圖片和表格則會排版錯(cuò)誤)

2、Aspose.Words

Aspose.Words for Java是一個(gè)原生庫,為開發(fā)人員提供了豐富的功能來創(chuàng)建、編輯和轉(zhuǎn)換 Word、PDF、Web 文檔,而無需在系統(tǒng)上安裝 Microsoft Word 環(huán)境。這個(gè)工具非常好用,maven上有對應(yīng)的依賴和jar包,但是轉(zhuǎn)換后會有水印,因?yàn)樗牵ㄊ召M(fèi)的)

3、spire.doc.free

Spire.Doc for Java是一個(gè)專業(yè)的 Word API,它使 Java 應(yīng)用程序能夠創(chuàng)建、轉(zhuǎn)換、操作和打印 Word文檔,而無需依賴 Microsoft Word。通過使用這個(gè)多功能庫,開發(fā)人員可以輕松處理大量任務(wù),例如插入圖像、超鏈接、 數(shù)字簽名、書簽和水印、設(shè)置頁眉和頁腳、創(chuàng)建表格、設(shè)置背景圖像以及添加腳注和尾注。這個(gè)跟aspose功能感覺有點(diǎn)差不多,也很好用,但是收費(fèi)比對還是aspose更好用,而且這個(gè)也是收費(fèi)的

4、documents4j

官網(wǎng):https://documents4j.com/#/

GitHub:https://github.com/documents4j/documents4j

documents4j 是一個(gè)跨平臺的文檔轉(zhuǎn)換庫,并且可以在 Linux 上進(jìn)行 Word 轉(zhuǎn) PDF 的操作。這個(gè)比較推薦,開源而且轉(zhuǎn)換后也不會有格式錯(cuò)誤(推薦)

documents4j用法

注意Windows和linux系統(tǒng)的代碼不一樣

1.Windows系統(tǒng)用法

1.導(dǎo)入依賴,本地必須要有wps或者微軟的office

   <!--word轉(zhuǎn)換為PDF文檔-->
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.0.3</version>
        </dependency>

2.編寫轉(zhuǎn)換代碼(這里我都是傳入input輸出output然后根據(jù)流自己操作)

package com.daysuns.dmas.module.testReportwd.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
public class Documents4jUtil {

    /**
     * word轉(zhuǎn)pdf
     *
     */
    public static void convertWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        String os = System.getProperty("os.name").toLowerCase();
        log.info("convertWordToPdf 當(dāng)前操作系統(tǒng):{}", os);
        if (os.contains("win")) {
            // Windows操作系統(tǒng)
            windowsWordToPdf(stream,sourceOutput);
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Unix/Linux/Mac操作系統(tǒng)
            linuxWordToPdf(stream,sourceOutput);
        } else {
            // 未知操作系統(tǒng)
            throw new RuntimeException("不支持當(dāng)前操作系統(tǒng)轉(zhuǎn)換文檔。");
        }
    }

    /**
     * 通過documents4j 實(shí)現(xiàn)word轉(zhuǎn)pdf -- Windows 環(huán)境 需要有 Microsoft Office 服務(wù)
     *
     */
    public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) {
        try{
            IConverter converter = LocalConverter.builder().build();
            converter.convert(stream)
                    .as(DocumentType.DOCX)
                    .to(sourceOutput)
                    .as(DocumentType.PDF).execute();
        } catch (Exception e) {
            log.error("winWordToPdf windows環(huán)境word轉(zhuǎn)換為pdf時(shí)出現(xiàn)異常:", e);
        }
    }

    /**
     * 通過libreoffice 實(shí)現(xiàn)word轉(zhuǎn)pdf -- linux 環(huán)境 需要有 libreoffice 服務(wù)
     *
     */
    public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        // 創(chuàng)建臨時(shí)文件
        File tempFile = createTempFileFromInputStream(stream);
        // 構(gòu)建LibreOffice的命令行工具命令
        String command = "libreoffice6.4 --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent();
        // 執(zhí)行轉(zhuǎn)換命令
        try {
            if (!executeLinuxCmd(command)) {
                throw new IOException("轉(zhuǎn)換失敗");
            }
             readPdfFileToByteArrayOutputStream(tempFile,sourceOutput);
        } catch (Exception e) {
            log.error("ConvertWordToPdf: Linux環(huán)境word轉(zhuǎn)換為pdf時(shí)出現(xiàn)異常:"+e +tempFile.getPath());
            // 清理臨時(shí)文件
            tempFile.delete();
        } finally {
            File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            //清理轉(zhuǎn)換后的pdf文件
            pdfFile.delete();
            // 清理臨時(shí)文件,無論是否成功轉(zhuǎn)換
            tempFile.delete();
        }
    }

    /**
     * 執(zhí)行命令行
     *
     * @param cmd 命令行
     * @return
     * @throws IOException
     */
    private static boolean executeLinuxCmd(String cmd) throws IOException {
        Process process = Runtime.getRuntime().exec(cmd);
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            log.error("executeLinuxCmd 執(zhí)行Linux命令異常:", e);
            Thread.currentThread().interrupt();
            return false;
        }
        return true;
    }

    /**
     *
     * 創(chuàng)建臨時(shí)文件
     */
    private static File createTempFileFromInputStream(InputStream inputStream) {
        try {
            File tempFile = File.createTempFile("temp_word", ".docx");
            Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            return tempFile;
        } catch (IOException e) {
            log.error("創(chuàng)建臨時(shí)文件失敗:", e);
            throw new RuntimeException("創(chuàng)建臨時(shí)文件失敗", e);
        }
    }

    /**
     * 讀取pdf文件
     */
    private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){
        try {
            Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            Files.copy(outputFile, sourceOutput);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

2.linux系統(tǒng)用法

linux操作系統(tǒng)要安裝libreoffice6,原因是documents4j調(diào)用的是office的API

1.在線安裝

sudo yum install libreoffice  (這里建議安裝低版本,高版本要求服務(wù)器的很多對應(yīng)API庫版本要求也比較高)

2.離線安裝(點(diǎn)擊后選擇版本下載rpm包,上傳至linux系統(tǒng))

3.解壓文件

4.進(jìn)入兩個(gè)文件夾安裝rpm包

使用安裝命令

cd LibreOffice_6.4.2_Linux_x86-64_rpm/RPMS
yum localinstall *.rpm

安裝完成查看版本

which libreoffice6.4     --》顯示路徑說明安裝成功
ll /usr/bin/libreoffice6.4  --》得到 "/opt/libreoffice6.4/program/soffice",說明安裝到了 "/opt/libreoffice6.4"

5.腳本測試是否可以成功轉(zhuǎn)換

libreoffice --headless --convert-to pdf 1.doc  --》去/temp  臨時(shí)目錄查看,也可以指定文件目錄導(dǎo)出

6.同樣適用上面代碼成功轉(zhuǎn)換文檔

package com.daysuns.dmas.module.testReportwd.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;



@Slf4j
public class Documents4jUtil {

    /**
     * word轉(zhuǎn)pdf
     *
     */
    public static void convertWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        String os = System.getProperty("os.name").toLowerCase();
        log.info("convertWordToPdf 當(dāng)前操作系統(tǒng):{}", os);
        if (os.contains("win")) {
            // Windows操作系統(tǒng)
            windowsWordToPdf(stream,sourceOutput);
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Unix/Linux/Mac操作系統(tǒng)
            linuxWordToPdf(stream,sourceOutput);
        } else {
            // 未知操作系統(tǒng)
            throw new RuntimeException("不支持當(dāng)前操作系統(tǒng)轉(zhuǎn)換文檔。");
        }
    }

    /**
     * 通過documents4j 實(shí)現(xiàn)word轉(zhuǎn)pdf -- Windows 環(huán)境 需要有 Microsoft Office 服務(wù)
     *
     */
    public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) {
        try{
            IConverter converter = LocalConverter.builder().build();
            converter.convert(stream)
                    .as(DocumentType.DOCX)
                    .to(sourceOutput)
                    .as(DocumentType.PDF).execute();
        } catch (Exception e) {
            log.error("winWordToPdf windows環(huán)境word轉(zhuǎn)換為pdf時(shí)出現(xiàn)異常:", e);
        }
    }

    /**
     * 通過libreoffice 實(shí)現(xiàn)word轉(zhuǎn)pdf -- linux 環(huán)境 需要有 libreoffice 服務(wù)
     *
     */
    public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        // 創(chuàng)建臨時(shí)文件
        File tempFile = createTempFileFromInputStream(stream);
        // 構(gòu)建LibreOffice的命令行工具命令
        String command = "libreoffice6.4 --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent();
        // 執(zhí)行轉(zhuǎn)換命令
        try {
            if (!executeLinuxCmd(command)) {
                throw new IOException("轉(zhuǎn)換失敗");
            }
             readPdfFileToByteArrayOutputStream(tempFile,sourceOutput);
        } catch (Exception e) {
            log.error("ConvertWordToPdf: Linux環(huán)境word轉(zhuǎn)換為pdf時(shí)出現(xiàn)異常:"+e +tempFile.getPath());
            // 清理臨時(shí)文件
            tempFile.delete();
        } finally {
            File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            //清理轉(zhuǎn)換后的pdf文件
            pdfFile.delete();
            // 清理臨時(shí)文件,無論是否成功轉(zhuǎn)換
            tempFile.delete();
        }
    }

    /**
     * 執(zhí)行命令行
     *
     * @param cmd 命令行
     * @return
     * @throws IOException
     */
    private static boolean executeLinuxCmd(String cmd) throws IOException {
        Process process = Runtime.getRuntime().exec(cmd);
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            log.error("executeLinuxCmd 執(zhí)行Linux命令異常:", e);
            Thread.currentThread().interrupt();
            return false;
        }
        return true;
    }

    /**
     *
     * 創(chuàng)建臨時(shí)文件
     */
    private static File createTempFileFromInputStream(InputStream inputStream) {
        try {
            File tempFile = File.createTempFile("temp_word", ".docx");
            Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            return tempFile;
        } catch (IOException e) {
            log.error("創(chuàng)建臨時(shí)文件失?。?, e);
            throw new RuntimeException("創(chuàng)建臨時(shí)文件失敗", e);
        }
    }

    /**
     * 讀取pdf文件
     */
    private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){
        try {
            Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            Files.copy(outputFile, sourceOutput);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

總結(jié) 

到此這篇關(guān)于Java將Word轉(zhuǎn)換成PDF的常用用法的文章就介紹到這了,更多相關(guān)Java將Word轉(zhuǎn)換PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • spring依賴注入原理與用法實(shí)例分析

    spring依賴注入原理與用法實(shí)例分析

    這篇文章主要介紹了spring依賴注入原理與用法,結(jié)合實(shí)例形式分析了spring框架依賴注入的概念、原理、用法案例及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2019-10-10
  • Java中tomcat memecached session 共享同步問題的解決辦法

    Java中tomcat memecached session 共享同步問題的解決辦法

    這篇文章主要介紹了Java中tomcat memecached session 共享同步問題的解決辦法的相關(guān)資料,需要的朋友可以參考下
    2015-10-10
  • Java枚舉從基礎(chǔ)到高級使用技巧完全解析

    Java枚舉從基礎(chǔ)到高級使用技巧完全解析

    Java枚舉(enum)是Java 5引入的一種特殊類,用于表示一組固定的常量(如狀態(tài)、類型等),這篇文章主要介紹了Java枚舉從基礎(chǔ)到高級使用技巧完全解析的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2026-05-05
  • DoytoQuery中的分頁排序方案示例詳解

    DoytoQuery中的分頁排序方案示例詳解

    這篇文章主要為大家介紹了DoytoQuery中的分頁排序方案示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • 使用Jersey構(gòu)建圖片服務(wù)器過程解析

    使用Jersey構(gòu)建圖片服務(wù)器過程解析

    這篇文章主要介紹了使用Jersey構(gòu)建圖片服務(wù)器過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Java Servlet 運(yùn)行原理分析

    Java Servlet 運(yùn)行原理分析

    這篇文章主要介紹了Java Servlet 運(yùn)行原理分析,幫助大家更好的理解和學(xué)習(xí)Java Servlet的相關(guān)知識,感興趣的朋友可以了解下
    2020-11-11
  • JAVA簡單鏈接Oracle數(shù)據(jù)庫 注冊和登陸功能的實(shí)現(xiàn)代碼

    JAVA簡單鏈接Oracle數(shù)據(jù)庫 注冊和登陸功能的實(shí)現(xiàn)代碼

    這篇文章主要介紹了JAVA鏈接Oracle并實(shí)現(xiàn)注冊與登錄功能的代碼實(shí)例,有需要的朋友可以參考一下
    2014-01-01
  • Java中WeakHashMap的使用詳解

    Java中WeakHashMap的使用詳解

    這篇文章主要介紹了Java中WeakHashMap的使用詳解,WeakHashMap是一種弱引用的Map,底層數(shù)據(jù)結(jié)構(gòu)為數(shù)組鏈表,與HashMap相比,WeakHashMap的區(qū)別在于它的key存儲為弱引用,在垃圾回收時(shí),如果key沒有被強(qiáng)引用所引用,那么key會被回收掉,需要的朋友可以參考下
    2023-09-09
  • Java?3年面試經(jīng)驗(yàn)告訴你Mybatis是如何進(jìn)行分頁的

    Java?3年面試經(jīng)驗(yàn)告訴你Mybatis是如何進(jìn)行分頁的

    這篇文章主要介紹了Java?3年面試經(jīng)驗(yàn)告訴你Mybatis是如何進(jìn)行分頁的,對于任何ORM框架,分頁的實(shí)現(xiàn)邏輯無外乎兩種,不管怎么包裝,最終給到開發(fā)者的,只是使用上的差異而已,本文給大家講解的很明白,感興趣的朋友一起看看吧
    2022-09-09
  • 基于Jenkins搭建.NET Core持續(xù)集成環(huán)境過程圖解

    基于Jenkins搭建.NET Core持續(xù)集成環(huán)境過程圖解

    這篇文章主要介紹了基于Jenkins搭建.NET Core持續(xù)集成環(huán)境過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08

最新評論

南溪县| 启东市| 密山市| 连城县| 西乌珠穆沁旗| 罗城| 邵东县| 清丰县| 乐安县| 连南| 舒城县| 禹城市| 农安县| 吴桥县| 咸丰县| 淳安县| 固阳县| 黎城县| 报价| 泸溪县| 南丹县| 桂林市| 儋州市| 凌海市| 永吉县| 南丹县| 建水县| 岢岚县| 馆陶县| 防城港市| 新巴尔虎左旗| 丰顺县| 乐亭县| 灵武市| 海南省| 蒙山县| 余庆县| 武川县| 韶关市| 鱼台县| 靖西县|