借助 libreoffice,word 转 pdf 体验

2020-12-04

libreoffice 官网

https://zh-cn.libreoffice.org/

软件下载镜像:

https://mirrors.cloud.tencent.com/libreoffice/libreoffice/stable/

软件安装略过,custom 方式,指定目录。

 

1、使用 jodconverter.jar,新建 maven 项目,添加 pom 依赖,写 java 代码把 docx 转 pdf

pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>constxiong</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>jodconverter</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.2</version>
        </dependency>
    </dependencies>

    <build>

    </build>
</project>

 

java 代码:

package constxiong;

import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.LocalOfficeManager;
import org.jodconverter.office.OfficeException;

import java.io.File;

/**
 * 测试 jodconverter
 * @author constxiong
 */
public class Test {

    public static void main(String[] args) throws OfficeException {
        LocalOfficeManager officeManager = LocalOfficeManager.builder().officeHome("E:\\install\\LibreOffice").install().build();
        //启动OpenOffice服务
        officeManager.start();
        //执行转换
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(new File("E:/ppdf/test.docx"), new File("E:/ppdf/test-jar.pdf"));
        //停止服务
        officeManager.stop();
    }

}

 

2、借助命令行 soffice 转换 docx 到 pdf

soffice --headless --convert-to pdf 源文件 --outdir 导出目录 "-env:UserInstallation=file:///用户工作临时目录"

soffice --headless --convert-to pdf E:/ppdf/test.docx --outdir E:/ppdf/ "-env:UserInstallation=file:///E:/ppdf/temp/"


ps:

ConstXiong 备案号:苏ICP备16009629号-3