一、下载安装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>
实现效果: