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)文章希望大家以后多多支持腳本之家!
- Java實(shí)現(xiàn)Word轉(zhuǎn)PDF的全過程
- Java調(diào)用py或者exe文件實(shí)現(xiàn)Word轉(zhuǎn)PDF
- Java實(shí)現(xiàn)一鍵將Word文檔轉(zhuǎn)為PDF
- Java實(shí)現(xiàn)WORD和PDF互相轉(zhuǎn)換以及數(shù)據(jù)填充示例
- java將word轉(zhuǎn)pdf的方法示例詳解
- Java將Word文檔轉(zhuǎn)換為PDF文件的幾種常用方法總結(jié)
- Java中Word與PDF轉(zhuǎn)換為圖片的方法詳解
- 探討Java 將Markdown文件轉(zhuǎn)換為Word和PDF文檔
- Java將word文件轉(zhuǎn)成pdf文件的操作方法
- Java實(shí)現(xiàn)word/pdf轉(zhuǎn)html并在線預(yù)覽
- Java實(shí)現(xiàn)一鍵將Word文檔轉(zhuǎn)為PDF的兩種方法
相關(guān)文章
Java中tomcat memecached session 共享同步問題的解決辦法
這篇文章主要介紹了Java中tomcat memecached session 共享同步問題的解決辦法的相關(guān)資料,需要的朋友可以參考下2015-10-10
JAVA簡單鏈接Oracle數(shù)據(jù)庫 注冊和登陸功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了JAVA鏈接Oracle并實(shí)現(xiàn)注冊與登錄功能的代碼實(shí)例,有需要的朋友可以參考一下2014-01-01
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)境過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

