文章
问答
冒泡
word文档转pdf方案实战

最近遇到一个场景,需要将word文档转成pdf,之前接触过poi,itext(旧版本)等技术实现,遇到复杂格式,效果都不太好,最近经过调研,发现使用开源包jodconverter基于Apache OpenOfficeLibreOffice来做转换效果比其他的技术方案效果很好,经过实践,基于LibreOffice的转换效果比Apache OpenOffice效果会更好,后者在转换方面会存在格式错乱的问题。

以下基于LibreOffice做个简单的使用说明。

环境

操作系统:ubuntu20

jdk版本:jdk11

jodconverter库:https://github.com/jodconverter/jodconverter

安装libreoffice

apt-get install -y libreoffice

创建java项目(maven)

pom.xml配置

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

上面的引用是基于LibreOffice库,如果是基于OpenOffice库,则需要引入另外的依赖jodconverter-local,具体可以看jodconverter的github主页说明。

代码逻辑

public static void wordToPdfByJodConverter() throws OfficeException {
    File inputFile = new File(testFilePath + "123.docx");
    File outputFile = new File(testFilePath + "123.pdf");

    LocalOfficeManager officeManager = LocalOfficeManager
            .builder()
            .install()
            .portNumbers(2002, 2003, 2004, 2005, 2006)
            .maxTasksPerProcess(5)
            .build();
    try {
        // Start an office process and connect to the started instance (on port 2002).
        officeManager.start();

        // Convert
        JodConverter
                .convert(inputFile)
                .to(outputFile)
                .execute();
    } finally {
        // Stop the office process
        OfficeUtils.stopQuietly(officeManager);
    }

    System.out.println("转换完成");
}

执行上述逻辑,就可以完成word到pdf的转换了。

问题

1)转换字体缺失

这其中可以会遇到转换乱码的问题,那是因为操作系统缺失字体导致。

直接从windows系统字体库中拷贝过来,目录位置应该是在C:\Windows\Fonts,拷贝这些文件到ubuntu系统目录下/usr/share/fonts/windows-fonts/windows-fonts这是自定义的,然后执行命令:

sudo mkfontscale
sudo mkfontdir
sudo fc-cache -fv

其他说明

jodconverter当然不仅仅可以将word转成pdf,它可以做很多的事情,具体可以查看jodconverter的文档:https://github.com/jodconverter/jodconverter/wiki/Getting-Started

java

关于作者

justin
123456
获得点赞
文章被阅读