java linux word转pdf

 网上搜索到的方式有很多,要么收费,要么失真,本文是推荐的免费,且还原度比较高,亲测可用,转换主要是通过给linux 服务器安装 libreoffice 服务实现的,作者用的版本是7.5.8, 采用yum在线安装的是 5.6.30 版本测试只转换了一页半内容严重失真(不知道啥原因)。最后离线下载了7.5.8版本的解决了,(作者最近又遇到word转出来的pdf条形图图例丢失,后面是通过修改word条形图样式解决的,因为我的word是通过java的poi,xwpfdocument动态生成的,他的图例是展示的数据表,而不是word里面的图例。特此记录)

启动服务

nohup libreoffice7.5 --headless --accept="socket,host=127.0.0.1,port=8100;urp;" --nofirststartwizard &

linux环境下执行命令
libreoffice7.05--headless --invisible --convert-to pdf ./input.docx --outdir ./

代码:

引入依赖

<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-local</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer-msoffice-word</artifactId>
    <version>1.1.10</version>
</dependency>

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

    // 构建LibreOffice的命令行工具命令
    String commands = "libreoffice7.5 --headless --invisible --convert-to pdf "
            + absolutePath + " --outdir " + parentPath;
    logger.info("libreoffice word 转 pdf 命令:" + commands);
    // 执行转换命令
    try {
        boolean result = executeLinuxCmd(commands);
        if (result) {
            // 转换成功,返回转换后的PDF文件
            String pdfFilePath = parentPath + File.separator + file.getName().replaceAll("\\.(docx?|\\w+)$", "") + ".pdf";
            logger.info(pdfFilePath);
            logger.info(pdfFilePath);
            return new File(pdfFilePath);
        } else {
            return null;
        }

    } catch (Exception e) {
        // 转换失败
        logger.error("Word文档转换为PDF失败,原因:执行命令时出现异常。", e);
        return null;
    }
}

/**
 * 执行命令行
 *
 * @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) {
        logger.info("执行 Linux 命令异常:", e);
        return false;
    }
    return true;
}
原文链接 实现Linux下Word转PDF、Java调用命令方式_linux word转pdf-CSDN博客
  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值