您好,欢迎来到年旅网。
搜索
您的当前位置:首页SpringBoot文件转换实现(word到pdf)

SpringBoot文件转换实现(word到pdf)

来源:年旅网

SpringBoot文件转换实现

方案

jodconverter+libreoffice

前置条件

需要安装 LibreOfficePortable

pom 文件

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

配置文件

jodconverter.local.enabled=true
jodconverter.local.office-home=${user.dir}\\LibreOfficePortable\\App\\libreoffice
jodconverter.local.office-home-linux=${user.dir}\\LibreOfficePortable\\App/libreoffice
jodconverter.local.portNumbers=9080,9081,90
jodconverter.local.maxTasksPerProcess=100

配置类

JodConverterConfig

package org.example.fileconvertdemo.config;

import org.jodconverter.DocumentConverter;
import org.jodconverter.LocalConverter;
import org.jodconverter.office.LocalOfficeManager;
import org.jodconverter.office.OfficeManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.stream.Collectors;

//@RefreshScope
@Configuration
public class JodConverterConfig {

    @Value("${jodconverter.local.office-home:E:/LibreOfficePortable/App/libreoffice}")
    private String officeHome;
    @Value("${jodconverter.local.office-home-linux:/home///}")
    private String officeHomeLinux;
    @Value("${jodconverter.local.portNumbers:9080,9081,90}")
    private String portNumbers;
    @Value("${jodconverter.local.maxTasksPerProcess:100}")
    private String maxTasksPerProcess;

    @Bean(
            initMethod = "start",
            destroyMethod = "stop"
    )
    public OfficeManager officeManager(){
        String os = System.getProperty("os.name").toLowerCase();
        // 设置libreoffice的安装路径,Windows或Linux
//        return LocalOfficeManager.builder()
//                .officeHome("E:\\LibreOfficePortable\\App\\libreoffice")
//                .portNumbers(9080,9081,90)
//                .maxTasksPerProcess(100)
//                .build();
        String[] split = portNumbers.split(",");
        int[] intArray = new int[split.length];

        // 遍历 String 数组并转换为 int
        for (int i = 0; i < split.length; i++) {
            intArray[i] = Integer.parseInt(split[i]);
        }
        return LocalOfficeManager.builder()
                .officeHome(os.contains("windows") ? officeHome : officeHomeLinux)
                .portNumbers(intArray)
                .maxTasksPerProcess(Integer.parseInt(maxTasksPerProcess))
                .build();
    }

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

}

控制层

FileConvertController

package org.example.fileconvertdemo.controller;

import org.example.fileconvertdemo.service.FileConvertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/convert")
public class FileConvertController {

    @Autowired
    public FileConvertService fileConvertService;

    @PostMapping("/convert")
    public ResponseEntity<byte[]> convertDocument(@RequestParam("file") MultipartFile file) {
        return fileConvertService.convertDocument(file);
    }

}

业务接口

package org.example.fileconvertdemo.service;

import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

public interface FileConvertService {

    ResponseEntity<byte[]> convertDocument(MultipartFile file);

}

业务实现

package org.example.fileconvertdemo.service.impl;

import org.example.fileconvertdemo.service.FileConvertService;
import org.jodconverter.DocumentConverter;
import org.jodconverter.LocalConverter;
import org.jodconverter.document.DefaultDocumentFormatRegistry;
import org.jodconverter.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

@Service
public class FileConvertServiceImpl implements FileConvertService {

    @Autowired
    private DocumentConverter documentConverter;

    public ResponseEntity<byte[]> convertDocument(MultipartFile file) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("temp", getFileExtension(Objects.requireNonNull(file.getOriginalFilename())));
            file.transferTo(tempFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        File outputPdf = new File(tempFile.getAbsolutePath().replace(getFileExtension(file.getOriginalFilename()), ".pdf"));
        try (FileInputStream inputStream = new FileInputStream(tempFile);
             FileOutputStream outputStream = new FileOutputStream(outputPdf)) {

            String contentType = file.getContentType();
            if (contentType.equals("application/msword") ||
                    contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
                // 处理 .doc 和 .docx 文件
                documentConverter.convert(inputStream)
                        .as(DefaultDocumentFormatRegistry.DOCX) // 使用 DOCX
                        .to(outputStream)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            } else if (contentType.equals("application/vnd.ms-excel") ||
                    contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                // 处理 .xls 和 .xlsx 文件
                documentConverter.convert(inputStream)
                        .as(DefaultDocumentFormatRegistry.XLSX) // 使用 XLSX
                        .to(outputStream)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            } else if (contentType.equals("text/plain")) {
                // 处理 .txt 文件
                documentConverter.convert(inputStream)
                        .as(DefaultDocumentFormatRegistry.TXT) // 使用 XLSX
                        .to(outputStream)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            } else if (contentType.equals("application/vnd.ms-powerpoint") || contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
                // 处理 .ppt 文件
                documentConverter.convert(inputStream)
                        .as(DefaultDocumentFormatRegistry.PPT) // 使用 XLSX
                        .to(outputStream)
                        .as(DefaultDocumentFormatRegistry.PDF)
                        .execute();
            } else {
                // 处理其他类型
//                throw new IllegalArgumentException("Unsupported file type: " + contentType);
                // 对于其他类型,直接返回原文件
                byte[] fileBytes = Files.readAllBytes(tempFile.toPath());
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Disposition", "inline; filename=\"" + file.getOriginalFilename() + "\"");
                headers.add("Content-Type", contentType);
                return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
            }
        } catch (IOException | OfficeException e) {
            throw new RuntimeException(e);
        }

        byte[] pdfBytes = new byte[0];
        try {
            pdfBytes = Files.readAllBytes(outputPdf.toPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "inline; filename=\"converted.pdf\"");
        headers.add("Content-Type", "application/pdf");

        return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
    }

    private String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf('.'));
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务