当前位置:   article > 正文

linux下java实现word 转pdf_documents4j linux

documents4j linux

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

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

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

安装 OpenOffice/LibreOffice 编辑器:

Ubuntu:使用以下命令安装


sudo apt-get install libreoffice
  • 1
  • 2

CentOS:使用以下命令安装

sudo yum install libreoffice
  • 1

下载并导入 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>
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

手动安装依赖包:您可以从 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");
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/414113
推荐阅读
相关标签
  

闽ICP备14008679号