Office转Pdf的Java实现

背景

项目中需要在线预览文档,且文档格式有word、excel和ppt等多种Office格式的
所以需要一中能在linux上运行的在线转换工具,经过github的查找,发现LibreOffice的方式,以下介绍以下具体方法

准备环境

安装LibreOffice

yum install libreoffice

文件有点大,需要安装一段时间

安装字体

**

字体一定需要安装,否则会出现乱码问题

**
1、下载字体

yum groupinstall "fonts"

2、修改字符集

vim /etc/locale.conf
LANG="en_US.UTF-8"修改成LANG="zh_CN.UTF-8"

3、重启

reboot

Java实现转换的Demo

代码

LibreOfficeCommandWordService.java

package top.flksweb;

import java.io.*;

public class LibreOfficeCommandWordService {
    
    //需要根据实际情况,查找LibreOffice安装的实际目录,
    //Mac下是默认安装到/usr/local/bin,
    //CentOS下默认安装在/usr/bin
    private final static String sofficeDir ="/usr/local/bin";

    public void word2pdf(String inPath, String outPath) throws Exception {
        if (!new File(inPath).exists()) {
            throw new FileNotFoundException();
        }
        String command = String.format("%s/soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sofficeDir, inPath, outPath);
        String output = this.executeCommand(command);
//        log.info("exec command:[{}]\noutput: [{}]", command, output);
    }

    protected String executeCommand(String command) throws IOException, InterruptedException {
        StringBuffer output = new StringBuffer();
        Process p;
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader)
        ) {
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        }
        p.destroy();
        return output.toString();
    }
}

测试方法

import java.io.File;

public class Office2Pdf {

    public static void main(String[] args) throws Exception {

        LibreOfficeCommandWordService officeCommandWordService = new LibreOfficeCommandWordService();
        File file = new File("/Users/franks/Documents/ESB技术选型报告.docx");
        File outFile = new File("/Users/franks/Documents");
        officeCommandWordService.word2pdf(file.getAbsolutePath(), outFile.getAbsolutePath());
    }
}

至此,测试完成通过。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值