linux下java实现word 转pdf

documents4j 是一个跨平台的文档转换库,并且可以在 Linux 上进行 Word 转 PDF 的操作。

它利用 Microsft OfficeAPIs 来进行文档转换,因此需要在Linux上安装 OpenOffice/LibreOffice 编辑器。

以下是在Linux环境下执行 WordPDF 的基本步骤:

安装 OpenOffice/LibreOffice 编辑器:

Ubuntu:使用以下命令安装


sudo apt-get install libreoffice

CentOS:使用以下命令安装

sudo yum install libreoffice

下载并导入 documents4j 依赖包:

在 Maven 项目中,您可以通过以下方式导入 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>
 

手动安装依赖包:您可以从 maven central 下载最新版本的 documents4j-local.jar,并将其手动导入您的项目

实例化 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();

	/**
	 * 通过documents4j 实现word转pdf
	 *
	 * @param sourcePath 源文件地址 如 /root/example.doc
	 * @param targetPath 目标文件地址 如 /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("转换完毕 targetPath = {}", outputFile.getAbsolutePath());
			CONVERTER.shutDown();
		} catch (Exception e) {
    
    
			log.error("[documents4J] word转pdf失败:{}", e.toString());
		}
	}



	public static void main(String[] args) {
    
    
		documents4jWordToPdf("E:\\万达接口信息查询接口文档.docx","e:\\11.pdf");
	}
}

这样,便可以在 Linux 上使用 documents4j 将 Word 转为 PDF。

猜你喜欢

转载自blog.csdn.net/qq_35385687/article/details/131420553
今日推荐