(转)libreoffice + jodconverter + Springboot 整合使用将Word转PDF

转:https://www.codeleading.com/article/64074162845/

第一步 安装Libreoffice

https://jingyan.baidu.com/article/91f5db1b38d69b1c7f05e3dc.html

第二步 maven依赖

<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>

第三步 配置DocumentConverter

yml配置

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

或者使用@Bean注解的方式注册

    @Bean(
            initMethod = "start",
            destroyMethod = "stop"
    )
    public OfficeManager officeManager(){
        String os = System.getProperty("os.name").toLowerCase();
        return LocalOfficeManager.builder()
                .officeHome(os.contains("windows") ? FileConst.LIBREOFFICE_PATH_WINDOWS :FileConst.LIBREOFFICE_PATH_LINUX)
                .portNumbers(9080,9081,9089)
                .maxTasksPerProcess(100)
                .build();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({OfficeManager.class})
    public DocumentConverter jodConverter(OfficeManager officeManager) {
        return LocalConverter.make(officeManager);
        //return null;
    }

第四步 使用DocumentConverter

使用@Autowire注入 documentConverter

    @Autowired
    private DocumentConverter documentConverter;

    #使用流的方式转换PDF
    documentConverter.convert(inputStream)
                            .as(fileExtension.compareToIgnoreCase(DefaultDocumentFormatRegistry.DOC.getExtension()) == 0 ? DefaultDocumentFormatRegistry.DOC : DefaultDocumentFormatRegistry.DOCX)
                            .to(outputStream)
                            .as(DefaultDocumentFormatRegistry.PDF)
                            .execute();
    #使用文件方式转换成PDF
                documentConverter
                    .convert(oldFile)
                    .to(file)
                    .execute();

 

posted @ 2022-04-28 17:41  wangle100  阅读(2532)  评论(1编辑  收藏  举报