(轉)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();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章