欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

1、POI

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

2、Aspose.Words

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

3、spire.doc.free

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

4、documents4j

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

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

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

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 實現(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時出現(xiàn)異常:", e);
        }
    }

    /**
     * 通過libreoffice 實現(xiàn)word轉(zhuǎn)pdf -- linux 環(huán)境 需要有 libreoffice 服務(wù)
     *
     */
    public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        // 創(chuàng)建臨時文件
        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時出現(xiàn)異常:"+e +tempFile.getPath());
            // 清理臨時文件
            tempFile.delete();
        } finally {
            File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            //清理轉(zhuǎn)換后的pdf文件
            pdfFile.delete();
            // 清理臨時文件,無論是否成功轉(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)建臨時文件
     */
    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)建臨時文件失?。?, e);
            throw new RuntimeException("創(chuàng)建臨時文件失敗", 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.離線安裝(點擊后選擇版本下載rpm包,上傳至linux系統(tǒng))

3.解壓文件

4.進(jìn)入兩個文件夾安裝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  臨時目錄查看,也可以指定文件目錄導(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 實現(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時出現(xiàn)異常:", e);
        }
    }

    /**
     * 通過libreoffice 實現(xiàn)word轉(zhuǎn)pdf -- linux 環(huán)境 需要有 libreoffice 服務(wù)
     *
     */
    public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        // 創(chuàng)建臨時文件
        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時出現(xiàn)異常:"+e +tempFile.getPath());
            // 清理臨時文件
            tempFile.delete();
        } finally {
            File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            //清理轉(zhuǎn)換后的pdf文件
            pdfFile.delete();
            // 清理臨時文件,無論是否成功轉(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)建臨時文件
     */
    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)建臨時文件失?。?, e);
            throw new RuntimeException("創(chuàng)建臨時文件失敗", 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)文章

  • springboot之redis cache TTL選項的使用

    springboot之redis cache TTL選項的使用

    這篇文章主要介紹了springboot之redis cache TTL選項的使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Java里得到00:00:00格式的時分秒的Timestamp

    Java里得到00:00:00格式的時分秒的Timestamp

    Java里如何得到00:00:00格式的時分秒的Timestamp ,下面是具體的實現(xiàn)代碼,需要的朋友可以參考下。
    2009-09-09
  • 解讀Spring?Bean的作用域

    解讀Spring?Bean的作用域

    這篇文章主要介紹了解讀Spring?Bean的作用域,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • Spring boot項目部署到云服務(wù)器小白教程詳解

    Spring boot項目部署到云服務(wù)器小白教程詳解

    這篇文章主要介紹了Spring boot項目部署到云服務(wù)器小白教程詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • Python爬蟲 12306搶票開源代碼過程詳解

    Python爬蟲 12306搶票開源代碼過程詳解

    這篇文章主要介紹了Python爬蟲 12306搶票開源代碼過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • 如何用java給文件加密的簡單實現(xiàn)

    如何用java給文件加密的簡單實現(xiàn)

    文件加密,簡單來說就是把文件讀取出來,把讀取出來的字節(jié)碼數(shù)組進(jìn)行遍歷,把每一個碼值和一個秘鑰(隨便一個數(shù))進(jìn)行異或運算,將運算后的結(jié)果全部寫入到文件里,這篇文章主要介紹了如何用java給文件加密的簡單實現(xiàn),需要的朋友可以參考下
    2023-12-12
  • 說說@ModelAttribute在父類和子類中的執(zhí)行順序

    說說@ModelAttribute在父類和子類中的執(zhí)行順序

    這篇文章主要介紹了@ModelAttribute在父類和子類中的執(zhí)行順序,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Spring boot測試找不到SpringRunner.class的問題

    Spring boot測試找不到SpringRunner.class的問題

    這篇文章主要介紹了Spring boot測試找不到SpringRunner.class的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • swing分割窗口控件JSplitPane使用方法詳解

    swing分割窗口控件JSplitPane使用方法詳解

    這篇文章主要為大家詳細(xì)介紹了swing分割窗口控件JSplitPane的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • IDEA配置Maven的超詳細(xì)步驟

    IDEA配置Maven的超詳細(xì)步驟

    Maven是一個能使我們的java程序開發(fā)節(jié)省時間和精力,是開發(fā)變得相對簡單,還能使開發(fā)規(guī)范化的工具,下面這篇文章主要給大家介紹了關(guān)于IDEA配置Maven的超詳細(xì)步驟,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-08-08

最新評論