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 否则异步执行的时候容易出现无反应的情况。

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

相关推荐
杨杨杨大侠20 小时前
Atlas Mapper 教程系列 (7/10):单元测试与集成测试
java·开源·github
叽哥20 小时前
Kotlin学习第 7 课:Kotlin 空安全:解决空指针问题的核心机制
android·java·kotlin
guslegend20 小时前
Java面试小册(3)
java
派葛穆20 小时前
Unity-按钮实现场景跳转
java·unity·游戏引擎
弥巷20 小时前
【Android】Viewpager2实现无限轮播图
java
虫小宝20 小时前
返利app排行榜的缓存更新策略:基于过期时间与主动更新的混合方案
java·spring·缓存
SimonKing21 小时前
告别繁琐配置!Retrofit-Spring-Boot-Starter让HTTP调用更优雅
java·后端·程序员
召摇21 小时前
Spring Boot 内置工具类深度指南
java·spring boot
JJJJ_iii21 小时前
【左程云算法09】栈的入门题目-最小栈
java·开发语言·数据结构·算法·时间复杂度
所愿ღ21 小时前
JavaWeb-Session和ServletContext
java·笔记·servlet