Convert word to pdf in java under linux

documents4j It is a cross-platform document conversion library, and can perform Word-to-PDF operations on Linux.

It utilizes Microsft Officefor APIs document conversion, so requires the editor Linuxto be installed on it .OpenOffice/LibreOffice

The following are the basic steps to perform a rev Linuxin the environment :WordPDF

Install OpenOffice/LibreOffice editors:

Ubuntu: Install with the following command


sudo apt-get install libreoffice

CentOS: Install with the following command

sudo yum install libreoffice

Download and import the documents4j dependency package:

In a Maven project, you can import the documents4j dependency package in the following ways:

        <!--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>
 

手动安装依赖包: You can download the latest version of documents4j-local.jar from maven central and manually import it into your project

Instantiate 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");
	}
}

In this way, you can use documents4j to convert Word to PDF on Linux.

Guess you like

Origin blog.csdn.net/qq_35385687/article/details/131420553
Recommended