word转pdf(亲测可用)

本文介绍了如何通过Java的DocUtils类,利用LibreOffice在服务器环境中将Word文档转换为PDF格式,详细展示了word2PDFCmd方法和执行LinuxShell命令的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:项目有需求word转pdf
实现思路:在服务器上安装libreoffice
libreoffice --convert-to pdf --outdir / /Invoice1706094532861.doc

代码工具类:

public class DocUtils {

    public static File word2PDFCmd(String inputWordFilePath) throws Exception {
        String command = "libreoffice --convert-to pdf --outdir " + "/" + " " + inputWordFilePath;
        log.info("command:{}", command);
        try {
            executeLinuxShell(command);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        File inputFile = new File(inputWordFilePath);
        String name = "bid.pdf";
        if (inputWordFilePath.endsWith("doc")) {
            name = inputFile.getName().replace(".doc", ".pdf");
        }
        if (inputWordFilePath.endsWith("docx")) {
            name = inputFile.getName().replace(".docx", ".pdf");
        }
        File outputFile = new File("/" + name);
        return outputFile;
    }


    public static String executeLinuxShell(String shellPath) {
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(new String[]{"/bin/bash", "-c", shellPath});
            String line;
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer out = new StringBuffer();
            while ((line = stdoutReader.readLine()) != null) {
                out.append(line);
            }
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (stdoutReader != null) {
                    try {
                        stdoutReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            process.destroy();
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值