Springboot集成OpenOffice实现各类文件转PDF,在线预览

一、下载安装OpenOffice

Springboot集成OpenOffice,首先计算机环境是需要OpenOffice的。

官网下载地址Apache OpenOffice - Official Download

下载完成双击exe文件进行安装

需要先解压缩再进行安装,解压缩可以修改路径
安装时有典型安装和自定义安装。典型安装默认装在C盘,自定义安装可修改安装位置

安装完成后进入到安装目录,再进入到program文件

在输入栏输入cmd再回车,进入命令行窗口

在命令行窗口内输入以下语句进行启动:

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

二、Springboot项目集成OpenOffice

pom文件中先导入相关依赖:

        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-spring-boot-starter</artifactId>
            <version>4.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.2</version>
        </dependency>

yml配置文件:

jodconverter:
  local:
    enabled: true
    office-home: C:\Program Files (x86)\OpenOffice 4 #安装路径
    max-tasks-per-process: 10
    port-numbers: 8100 #端口号

由于我代码中将用户上传的文件、以及转换后的文件都存储在计算机上,所以我配置了两个地址

file:
  source_path: D:/sourceFiles/
  target_path: D:/targetFiles/

编写控制器进行实现:

import com.wk.convert.config.FileProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jodconverter.DocumentConverter;
import org.jodconverter.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;


@Slf4j
@RestController
@RequestMapping()
@Api(tags = "文件")
public class FileController {

    @Autowired
    private DocumentConverter converter;


   
    @SneakyThrows
    @ApiOperation(value = "文件预览")
    @PostMapping("/viewPDF")
    public void viewPDF(HttpServletResponse response, @RequestPart("multipartFile") MultipartFile multipartFile) {
        File targetFile = getPDFFile(multipartFile);
        if (targetFile == null) return;
        // 返回前端预览
        String pdfPath = targetFile.getAbsolutePath();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = Files.newInputStream(new File(pdfPath).toPath());
            IOUtils.copy(in, outputStream);
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "文件转换PDF")
    @PostMapping("/toPDF")
    public ResponseEntity<InputStreamResource> toPDF(HttpServletRequest request, HttpServletResponse response, @RequestPart("multipartFile") MultipartFile multipartFile) throws IOException, OfficeException {
        File targetFile = getPDFFile(multipartFile);
        if (targetFile == null) return null;

        // 返回文件
        InputStream inputStream = Files.newInputStream(new File(targetFile.getAbsolutePath()).toPath());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + targetFile.getName());
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));
    }


    private File getPDFFile(MultipartFile multipartFile) throws IOException, OfficeException {
        if (multipartFile.isEmpty()) {
            log.info("文件为空");
            return null;
        }

        File file1 = new File(FileProperties.SOURCE_PATH);
        if (!file1.exists()) file1.mkdir();
        File file2 = new File(FileProperties.TARGET_PATH);
        if (!file2.exists()) file2.mkdir();

        String originalFilename = Objects.requireNonNull(multipartFile.getOriginalFilename());
        String fileName = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6) + "_" + originalFilename.split("\\.")[0];

        File sourceFile = new File(FileProperties.SOURCE_PATH + fileName + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1));
        try (FileOutputStream fos = new FileOutputStream(sourceFile)) {
            fos.write(multipartFile.getBytes());
        }
        File targetFile = new File(FileProperties.TARGET_PATH + fileName + ".pdf");
        converter.convert(sourceFile).to(targetFile).execute();
        return targetFile;
    }


}

文件配置类 

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FileProperties {

    public static String SOURCE_PATH;


    public static String TARGET_PATH;


    @Value("${file.source_path}")
    public void setSourcePath(String sourcePath) {
        SOURCE_PATH = sourcePath;
    }


    @Value("${file.target_path}")
    public void setTargetPath(String targetPath) {
        TARGET_PATH = targetPath;
    }
}

附上简单前端代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>File Converter</title>
</head>
<body>
<h1>Converter</h1>

<br>
<form action="/viewPDF" method="post" enctype="multipart/form-data">
    <label>文件预览:</label>
    <input type="file" name="multipartFile" accept="application/*">
    <button type="submit">submit</button>
</form>

<br>
<form action="/toPDF" method="post" enctype="multipart/form-data">
    <label>文件转PDF:</label>
    <input type="file" name="multipartFile" accept="application/*">
    <button type="submit">submit</button>
</form>


</body>
</html>

实现效果:

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以帮你解决这个问题。首先,你需要在Linux系统中安装OpenOffice。然后,你可以使用Java的ProcessBuilder类来执行OpenOffice的命令行换操作。下面是一个简单的Spring Boot示例代码,可以将Word文档换为PDF: ```java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; @Service public class WordToPdfConverter { public void convert(String inputPath, String outputPath) throws IOException { List<String> command = new ArrayList<String>(); command.add("/usr/bin/soffice"); // OpenOffice安装路径 command.add("--headless"); command.add("--convert-to"); command.add("pdf"); command.add("--outdir"); command.add(outputPath); command.add(inputPath); ProcessBuilder builder = new ProcessBuilder(); builder.command(command); builder.redirectErrorStream(true); Process process = builder.start(); try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } ``` 在这个示例中,我们使用ProcessBuilder类来启动OpenOffice的命令行换功能。我们将输入文档和输出目录作为参数传递给该方法。最后,我们使用waitFor()方法等待换进程的完成。 你可以将这个示例代码集成到你的Spring Boot应用程序中,以提供WordPDF换服务。当然,你还需要实现一些安全措施来确保只有授权用户才能访问该服务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值