admin管理员组

文章数量:1605301

word转pdf需要借助jodconverter和工具LibreOffice。

虽然市面上有很多转换的工具以及技术但是spring boot对LibreOffice进行了整合并且window和linux都支持的。

本文章以window系统为主。只关注代码如何安装自行百度。

1.第一步下载LibreOffice

下载地址下载

下载完成后自行安装,window和linux如何安装教程请自行百度

(linux由于有些字体没有回出现错误,所有linux请自行百度解决)。

2.spring boot2.x(添加jar的依赖)

        <!-- word转pdf所需jar begin -->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-spring-boot-starter</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.libreoffice</groupId>
            <artifactId>ridl</artifactId>
            <version>5.4.2</version>
        </dependency>
        <!-- word转pdf所需jar end -->

3.在application.properties中配置jodconverter信息

jodconverter.local.enabled=true
# 设置LibreOffice主目录
jodconverter.local.office-home=C:/Program Files/LibreOffice
# 开启多个LibreOffice进程,每个端口对应一个进程
jodconverter.local.portNumbers=8100,8101,8102
# LibreOffice进程重启前的最大进程数
jodconverter.local.maxTasksPerProcess=100

4.进行word文件转pdf

    @Resource
    private DocumentConverter documentConverter;

    /**
     * 文件转换
     * @param filepath
     * @return
     * @throws OfficeException
     */
    @RequestMapping("/viewerfile")
    @ResponseBody
    public String toPdf(String filepath, HttpServletRequest request) {
        File word = new File(filepath);
        //截取字符串把word的后缀改为pdf
        String pdfpath=filePath=filePath.substring(0,filePath.lastIndexOf("."))+".pdf";
        File pdf = new File(pdfpath);
        //文件转换
        documentConverter.convert(word).to(pdf).execute();
        return "true";
    }

重要提醒:针对ppt的格式2003版本的后缀为ppt的文件会出现转换异常。把ppt另存为2007版及以上文件后缀为pptx的就可以了。

至此结束!

本文标签: SpringPDFword