documents4j
是一個(gè)跨平臺(tái)的文檔轉(zhuǎn)換庫(kù),并且可以在 Linux 上進(jìn)行 Word 轉(zhuǎn) PDF 的操作。
它利用 Microsft Office
的 APIs
來(lái)進(jìn)行文檔轉(zhuǎn)換,因此需要在Linux
上安裝 OpenOffice/LibreOffice
編輯器。
以下是在Linux
環(huán)境下執(zhí)行 Word
轉(zhuǎn) PDF
的基本步驟:
安裝 OpenOffice/LibreOffice 編輯器:
Ubuntu:使用以下命令安裝
sudo apt-get install libreoffice
CentOS:使用以下命令安裝
sudo yum install libreoffice
下載并導(dǎo)入 documents4j 依賴包:
在 Maven 項(xiàng)目中,您可以通過(guò)以下方式導(dǎo)入 documents4j 依賴包:
<!--documents4j-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<!-- documents4j-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
手動(dòng)安裝依賴包
:您可以從 maven central 下載最新版本的 documents4j-local.jar,并將其手動(dòng)導(dǎo)入您的項(xiàng)目文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-588495.html
實(shí)例化 documents4j-local:
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* @Title: Docx4jUtil
* @author: yzd e-mail: 121665820@qq.com
* @date: 2023/6/27 16:04
* @ClassName: Docx4jUtil
* @Description:
*/
@Slf4j
public class WordConvertPdfUtil {
private static final IConverter CONVERTER = LocalConverter.builder().build();
/**
* 通過(guò)documents4j 實(shí)現(xiàn)word轉(zhuǎn)pdf
*
* @param sourcePath 源文件地址 如 /root/example.doc
* @param targetPath 目標(biāo)文件地址 如 /root/example.pdf
*/
public static void documents4jWordToPdf(String sourcePath, String targetPath) {
File inputWord = new File(sourcePath);
File outputFile = new File(targetPath);
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
CONVERTER.convert(docxInputStream)
.as(DocumentType.DOCX)
.to(outputStream)
.as(DocumentType.PDF).execute();
outputStream.close();
docxInputStream.close();
log.info("轉(zhuǎn)換完畢 targetPath = {}", outputFile.getAbsolutePath());
CONVERTER.shutDown();
} catch (Exception e) {
log.error("[documents4J] word轉(zhuǎn)pdf失敗:{}", e.toString());
}
}
public static void main(String[] args) {
documents4jWordToPdf("E:\\萬(wàn)達(dá)接口信息查詢接口文檔.docx","e:\\11.pdf");
}
}
這樣,便可以在 Linux 上使用 documents4j 將 Word 轉(zhuǎn)為 PDF。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-588495.html
到了這里,關(guān)于linux下java實(shí)現(xiàn)word 轉(zhuǎn)pdf的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!