Java通过documents4j和libreoffice把word转为pdf

文章目录

word转pdf的相关第三方jar说明

  • docx4j
    免费开源、稍微复杂点的word,样式完全乱了,且xalan升级为2.7.3后会报错。
  • poi
    免费开源、官方文档少、学习成本大、使用复杂、生成的样式也有问题。
  • aspire.doc
    样式保留很好、使用方便。
    未付费时,第一行会有红色水印且超过500个段落(大概25页)会被截取。
    网上没有破解版。
  • aspose.words
    样式保留很好、使用方便。
    网上有破解版。
  • documents4j
    样式保留很好、使用方便。
    底层直接调用微软的office所以,完美保留样式

Linux系统安装LibreOffice

在线安装

CentOS:使用以下命令安装

bash 复制代码
sudo yum install libreoffice

Ubuntu:使用以下命令安装

bash 复制代码
sudo apt-get install libreoffice

执行命令需要root权限:sudo -i、su

离线安装

在linux下离线安装libreoffice

word转pdf验证

查看版本:

bash 复制代码
libreoffice --version

启动服务:

bash 复制代码
nohup libreoffice --headless --accept="socket,host=127.0.0.1,port=8100;urp;" --nofirststartwizard &

word转pdf验证:

bash 复制代码
// 安装完后进入/usr/bin 或者 usr/local/bin目录下执行。 outdir输出是一个文件夹
libreoffice --headless --invisible --convert-to pdf /file/word/test.docx --outdir /file/word/test

也可以安装Apache OpenOffice,二者基本差不多,更推荐LibreOffice
LibreOffice vs OpenOffice:哪个免费办公套件更适合你?

Java工具类代码

maven依赖:

xml 复制代码
<!--word转pdf-->
<dependency>
	<groupId>com.documents4j</groupId>
	<artifactId>documents4j-local</artifactId>
	<version>${documents4j.version}</version>
</dependency>
<dependency>
	<groupId>com.documents4j</groupId>
	<artifactId>documents4j-transformer-msoffice-word</artifactId>
	<version>${documents4j.version}</version>
</dependency>

java代码:

java 复制代码
package com.chinamobile.cmss.services.main.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Documents4j工具类
 *
 * @author liquanhong
 * @createTime 2023/12/05
 */
@Slf4j
public class Documents4jUtil {

    // windows 生成目录
    private static String winDirUrl = "D:\\temp\\file\\pdf\\";

    /**
     * word转pdf
     *
     * @param file word源文件
     */
    public static void convertWordToPdf(File file) {
        String os = System.getProperty("os.name").toLowerCase();
        log.info("convertWordToPdf 当前操作系统:{}", os);
        if (os.contains("win")) {
            // Windows操作系统
            windowsWordToPdf(file);
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Unix/Linux/Mac操作系统
            linuxWordToPdf(file);
        } else {
            // 未知操作系统
            throw new RuntimeException("不支持当前操作系统转换文档。");
        }
    }

    /**
     * 通过documents4j 实现word转pdf -- Windows 环境 需要有 Microsoft Office 服务
     *
     * @param file 源文件
     */
    public static void windowsWordToPdf(File file) {
        File outputFile = new File(winDirUrl + file.getName().replaceAll("\\.(docx?|\\w+)$", "") + ".pdf");
        try(InputStream  docxInputStream = new FileInputStream(file);
            OutputStream outputStream = new FileOutputStream(outputFile)){
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
        } catch (Exception e) {
            log.error("winWordToPdf windows环境word转换为pdf时出现异常:", e);
        }
    }

    /**
     * 通过libreoffice 实现word转pdf -- linux 环境 需要有 libreoffice 服务
     *
     * @param file 源文件
     */
    public static void linuxWordToPdf(File file) {
        // 获取文件的绝对路径和目标路径
        String absolutePath = file.getAbsolutePath();
        String parentPath = file.getParent();

        // 构建LibreOffice的命令行工具命令
        String command = "libreoffice --headless --invisible --convert-to pdf " + absolutePath + " --outdir " + parentPath;
        // 执行转换命令
        try {
            executeLinuxCmd(command);
        } catch (Exception e) {
            log.error("linuxWordToPdf linux环境word转换为pdf时出现异常:", e);
        }
    }

    /**
     * 执行命令行
     *
     * @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 执行Linux命令异常:", e);
            Thread.currentThread().interrupt();
            return false;
        }
        return true;
    }
}

命令行注意加上 --headless --invisible 否则异步执行的时候容易出现无反应的情况。

参考链接参考链接参考链接

相关推荐
Peter(阿斯拉)9 分钟前
[Java性能优化]_[时间优化]_[字符串拼接的多种方法性能分析]
java·性能优化·stringbuilder·string·字符串拼接·stringbuffer·时间优化
HAPPY酷34 分钟前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf
水痕011 小时前
gin结合minio来做文件存储
java·eureka·gin
寒士obj2 小时前
Spring事物
java·spring
柯南二号3 小时前
【Java后端】Spring Boot 集成 MyBatis-Plus 全攻略
java·spring boot·mybatis
桦说编程10 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen10 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研10 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
没有bug.的程序员11 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋11 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat