• 实现Linux下Word转PDF、Java调用命令方式


    使用 LibreOffice 实现 Word 转 PDF 和 Java 调用命令

    1、 安装 LibreOffice

    • 外网安装
    # 一键安装
    yum install -y libreoffice
    # 验证版本
    libreoffice --version
    # Warning: -version is deprecated.  Use --version instead.
    # LibreOffice 7.5.6.2 f654817fb68d6d4600d7d2f6b647e47729f55f15
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 内网安装
      官网下载,找最新版本
      在这里插入图片描述

    使用版本拼接本地下载

    https://download.documentfoundation.org/libreoffice/stable/7.5.6/rpm/x86_64/LibreOffice_7.5.6_Linux_x86-64_rpm.tar.gz
    https://download.documentfoundation.org/libreoffice/stable/7.5.6/rpm/x86_64/LibreOffice_7.5.6_Linux_x86-64_rpm_langpack_zh-CN.tar.gz
    https://download.documentfoundation.org/libreoffice/stable/7.5.6/rpm/x86_64/LibreOffice_7.5.6_Linux_x86-64_rpm_helppack_zh-CN.tar.gz
    
    • 1
    • 2
    • 3

    下载完成放到内网服务器

    # 安装软件包
    tar -zxvf LibreOffice_7.5.6_Linux_x86-64_rpm.tar.gz
    cd LibreOffice_7.5.6.2_Linux_x86-64_rpm/RPMS/
    rpm -ivh *.rpm
    
    # 安装中文语言包
    tar -zxvf LibreOffice_7.5.6_Linux_x86-64_rpm_langpack_zh-CN.tar.gz
    cd LibreOffice_7.5.6.2_Linux_x86-64_rpm_langpack_zh-CN/RPMS/
    rpm -ivh *.rpm
    
    # 安装离线帮助文档
    tar -zxvf LibreOffice_7.5.6_Linux_x86-64_rpm_helppack_zh-CN.tar.gz
    cd LibreOffice_7.5.6.2_Linux_x86-64_rpm_helppack_zh-CN/RPMS/
    rpm -ivh *.rpm
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2、启动服务

    # 开启接口服务,用于word转pdf
    nohup libreoffice7.5 --headless --accept="socket,host=127.0.0.1,port=8100;urp;" --nofirststartwizard &
    libreoffice7.05--headless --invisible --convert-to pdf ./input.docx --outdir ./
    
    
    • 1
    • 2
    • 3
    • 4

    3、安装字体库

    # 字体
    cd /usr/share/fonts
    # 拷贝至该目录下 C:\Windows\Fonts :simhei.ttf、Microsoft YaHei UI
    yum install -y fontconfig mkfontscale
    mkfontdir
    fc-cache -fv
    # 命令执行成功后终端最后一行会显示 fc-cache: succeeded
    #验证
    fc-list :lang=zh
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4、Java调用Linux命令

    支持 windowsLinux 转换 PDFwindows需要安装微软Microsoft Office,Linux环境安装LibreOffice开源Office

    • 依赖
    <dependency>
        <groupId>com.documents4jgroupId>
        <artifactId>documents4j-localartifactId>
        <version>1.1.10version>
    dependency>
    <dependency>
        <groupId>com.documents4jgroupId>
        <artifactId>documents4j-transformer-msoffice-wordartifactId>
        <version>1.1.10version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • DocxUtil
    package com.gwssi.common.utils;
    
    import com.documents4j.api.DocumentType;
    import com.documents4j.api.IConverter;
    import com.documents4j.job.LocalConverter;
    import com.gwssi.common.core.constant.PathConstants;
    import com.gwssi.util.PathUtils;
    import lombok.extern.slf4j.Slf4j;
    
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.UUID;
    
    @Slf4j
    public class DocxUtil {
    
    
        /**
         * 通过documents4j 实现word转pdf
         *
         * @param sourcePath 源文件地址 如 /root/example.doc
         */
        public static File documents4jWordToPdf(String sourcePath) {
            return documents4jWordToPdf(new File(sourcePath));
        }
    
        public static File documents4jWordToPdf(File file) {
            String os = System.getProperty("os.name").toLowerCase();
    
            log.info("当前系统:{}", os);
            if (os.contains("win")) {
                // Windows操作系统
                return winDocuments4jWordToPdf(file);
            } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
                // Unix/Linux/Mac操作系统
                return linuxDocuments4jWordToPdf(file);
            } else {
                // 未知操作系统
                throw new RuntimeException("不支持当前操作系统转换文档");
            }
        }
    
        /**
         * 通过documents4j 实现word转pdf -- Windows 环境 需要有 Microsoft Office 服务
         *
         * @param file 源文件
         */
        public static File winDocuments4jWordToPdf(File file) {
            File outputFile = new File(PathUtils.getTempPath());
            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();
                docxInputStream.close();
                outputStream.close();
                return outputFile;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 通过documents4j 实现word转pdf -- linux 环境 需要有 libreoffice 服务
         *
         * @param file 源文件
         */
        public static File linuxDocuments4jWordToPdf(File file) {
            // 获取文件的绝对路径和目录路径
            String absolutePath = file.getAbsolutePath();
            String parentPath = file.getParent();
    
            // 构建LibreOffice的命令行工具命令
            String commands = "libreoffice7.5 --headless --convert-to pdf "
                    + absolutePath + " --outdir " + parentPath;
            // 执行转换命令
            try {
                boolean result = ExecUtil.executeLinuxCmd(commands);
                if (result) {
                    // 转换成功,返回转换后的PDF文件
                    String pdfFilePath = parentPath + File.separator + file.getName().replaceAll("\\.(docx?|\\w+)$", "") + ".pdf";
                    log.info(pdfFilePath);
                    log.info(pdfFilePath);
                    return new File(pdfFilePath);
                } else {
                    return null;
                }
    
            } catch (Exception e) {
                // 转换失败
                log.error("Word文档转换为PDF失败,原因:执行命令时出现异常。", e);
                return null;
            }
        }
    
    
    }
    
    
    
    • 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
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • ExecUtil
    @Slf4j
    public class ExecUtil {
    
        public static boolean executeLinuxCmd(String cmd) throws IOException {
            // 执行命令行工具命令
            Process process = Runtime.getRuntime().exec(cmd);
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                log.error("执行 Linux 命令异常:",e);
                return false;
            }
            return true;
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    嵌入式Linux系统编程-》线程池+面试题+源码+Makefile【第9天】
    大厂面试题-Java并发编程基础篇(五)
    AWS设备接入-MQTT方式
    【Day14】类和对象
    Linux21 --- 计算机网络基础概论(网络基本概念、网络分层模型、网络应用程序通信流程)
    Ubuntu 20.04 固定内核,降低版本, 锁定内核
    java面向对象(八)
    C++设计模式_08_Factory Method工厂方法模式
    Asp.NetCore 从数据库加载配置(二)
    T1065 奇数求和(信息学一本通C++)
  • 原文地址:https://blog.csdn.net/F15217283411/article/details/133947490