JAVA 系统word转pdf

/**
 * windows系统word转pdf
 * @param pdfFile 转换后的pdf文件
 * @param wordFile word源文件
 */
public static void winWordToPdf(File pdfFile, File wordFile) {
    try (InputStream docxInputStream = new FileInputStream(wordFile);
         OutputStream outputStream = new FileOutputStream(pdfFile) ){
        IConverter converter = LocalConverter.builder().build();
        converter.convert(docxInputStream)
                .as(DocumentType.DOCX)
                .to(outputStream)
                .as(DocumentType.PDF).execute();
        converter.shutDown();
    } catch (FileNotFoundException e) {
        log.error("word转换pdf失败", e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

/**
* linux系统word转pdf
   * 使用LibreOffice转换。系统需安装LibreOffice
   * 转换命令 libreoffice --invisible --convert-to pdf --outdir output_dir source_path
   * 转换后的pdf文件名使用的是源文件的名称,所以如果要指定输出文件名称,就需把源文件名称改成想要输出的名称
* @param pdfFile 转换后的pdf文件
* @param wordFile word源文件
*/
public static void linuxWordToPdf(File pdfFile, File wordFile) {
// 获取word文件的绝对路径
String sourcePath = wordFile.getAbsolutePath();
// 获取pdf文件存放文件夹的绝对路径
String outDir = pdfFile.getAbsolutePath().substring(0, pdfFile.getAbsolutePath().lastIndexOf(File.separator));

    // 构建LibreOffice的命令行工具命令
    String command = "libreoffice --invisible --convert-to pdf --outdir " + outDir + " " + sourcePath;
    log.info(command);
    // 执行转换命令
    try {
        executeLinuxCmd(command);
    } catch (Exception e) {
        log.error("linuxWordToPdf linux环境word转换为pdf时出现异常:", e);
    }
}

/**
 * 执行命令行
 *
 * @param cmd 命令行
 * @return
 */
private static boolean executeLinuxCmd(String cmd)  {
    try {
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
    } catch (InterruptedException e) {
        log.error("executeLinuxCmd 执行Linux命令异常:", e);
        Thread.currentThread().interrupt();
        return false;
    } catch (IOException e) {
        log.error("获取系统命令执行环境异常", e);
    }
    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值