美文网首页
Java基于Libreoffice转换word/excel/pp

Java基于Libreoffice转换word/excel/pp

作者: basic13 | 来源:发表于2023-02-21 19:10 被阅读0次

Java面对office转pdf这种需求,大多采用POI、pdfbox等工具进行转换,转换精度和效率取决于相关工具的支持程度,难免有些样式不符、错位等现象,如果需要完全一致的office转pdf的体验,还是得依赖office软件,目前OpenOffice和Libreoffice均提供了对应的命令行工具来实现office文件转pdf。本文介绍Libreoffice转pdf的方法及java调用Libreoffice命令行的方法。

一、安装Libreoffice

windows:直接下载Libreoffice
下载 LibreOffice | LibreOffice 简体中文官方网站 - 自由免费的办公套件
centos:使用yum安装:
yum install -y libreoffice
alpine:使用apk安装:
apk add libreoffice
其他操作系统可以参考官方安装说明或自行搜索安装方法。

注意,windows在安装完成之后,找到libreoffice安装目录,将对应目录加入PATH参数,一般安装位置在C:\Program Files\LibreOffice\program,添加入PATH和JDK添加PATH一样的操作:

配置PATH示例

安装/配置完成后,在命令行中输入soffice --help,确认该命令行可以使用:

soffice示例

二、Libreoffice转换Office到PDF的命令

soffice --invisible --convert-to pdf --outdir  "输出文件夹" "PDF文件所在位置"

例如:

soffice --invisible --convert-to pdf --outdir  "/home/pdfconvertor/result/" "/home/pdfconvertor/pdf/1.docx"

执行后,会在输出文件夹下生成与源文件名同名的pdf文件(文件后缀会改为pdf),如上面的例子,输出文件为/home/pdfconvertor/result/1.pdf

三、Java调用命令行转换为PDF

添加Commons-exec依赖:

          <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-exec</artifactId>
                <version>${commons-exec.version}</version>
            </dependency>

进行转换:

   public static File convert(File officeFile) throws Exception {
        DefaultExecutor exec = new DefaultExecutor();
        File tempFolder = new File(System.getProperty("java.io.tmpdir"), "office2pdf-" + UUID.randomUUID());
        // 同步等待
        Semaphore semaphore = new Semaphore(1);
        semaphore.acquire();
        ExecuteResultHandler erh = new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                semaphore.release();
                //转换完成逻辑
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                semaphore.release();
                //转换失败逻辑
                e.printStackTrace();
            }
        };
        String command = "soffice --invisible --convert-to pdf --outdir \"" + tempFolder.getAbsolutePath() + "\" \"" + officeFile.getAbsolutePath() + "\"";
        System.out.println("执行office文件转换任务,命令为" + command);
        exec.execute(CommandLine.parse(command), erh);
        // 等待执行完成
        semaphore.acquire();
        File file = new File(tempFolder.getAbsolutePath() + File.separator + officeFile.getName().substring(0, officeFile.getName().indexOf(".")) + ".pdf");
        if (!file.exists()) {
            // 转换失败逻辑
        }
        return file;
    }

四、字体相关问题

因Libreoffice转换会依赖本地字体,因此如果部署在服务器上使用时,没有对应的字体会造成字体异常,此时需要在服务器上安装对应的字体。
centos上解决方法如下:
拷贝常用的字体文件到linux的字体文件夹/usr/share/fonts
刷新字体缓存fc-cache -fv

随后重启应用即可。

相关文章

网友评论

      本文标题:Java基于Libreoffice转换word/excel/pp

      本文链接:https://www.haomeiwen.com/subject/drvinrtx.html