利用OpenOffice/LibreOffice将office文件转换成pdf

利用OpenOffice/LibreOffice将office文件转换成pdf

开发环境:Windows操作系统
项目架构:Maven
依赖Jar包:jodconverter-local-4.2.0.jar
转换软件:OpenOffice / LibreOffice

pom.xml配置
<dependencies>
    <!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-local -->
    <dependency>
        <groupId>org.jodconverter</groupId>
        <artifactId>jodconverter-local</artifactId>
        <version>4.2.0</version>
    </dependency>
</dependencies>
核心代码
public static void Word2Pdf(String srcPath, String desPath) throws IOException {
    // 源文件目录
    File inputFile = new File(srcPath);
    if (!inputFile.exists()) {
        System.out.println("源文件不存在!");
        return;
    }
    // 输出文件目录
    File outputFile = new File(desPath);
    if (!outputFile.getParentFile().exists()) {
        outputFile.getParentFile().exists();
    }
    // 连接OpenOffice/LibreOffice服务
    OfficeManager officeManager = LocalOfficeManager.builder().officeHome("D:\\Program Files\\OpenOffice 4").install().build();
    try {
        officeManager.start();
        // 转换文档到pdf
        long time = System.currentTimeMillis();
        JodConverter.convert(inputFile).to(outputFile).execute();
        logger.info("文件:{}转换PDF:{}完成,用时{}毫秒!", srcPath, desPath, System.currentTimeMillis() - time);
    } catch (OfficeException e) {
        e.printStackTrace();
        logger.warn("文件:{}转换PDF:{}失败!", srcPath, desPath);
    } finally {
        // 关闭连接
        OfficeUtils.stopQuietly(officeManager);
    }
}

猜你喜欢

转载自blog.csdn.net/zhuiyucanxin/article/details/79563013