相关链接
工具库-基于LibreOffice实现文档操作_liumapp的博客-优快云博客
LibreOffice 安装_头发浓密的程序员的博客-优快云博客
1 安装 LibreOffice
请参考链接
LibreOffice 安装_头发浓密的程序员的博客-优快云博客
需要记住 LibreOffice 安装主目录
2 pom 依赖
<dependency>
<groupId>com.liumapp.workable.converter</groupId>
<artifactId>workable-converter</artifactId>
<version>v1.2.0</version>
</dependency>
3 配置文件 application.yml
com:
liumapp:
workable-converter:
libreofficePath: "/Applications/LibreOffice.app/Contents" # LibreofficePath 安装主目录
4 controller 代码
@Controller
@RequestMapping("/viewfile")
public class ViewPdfController {
@Autowired
private AttachmentsService attachmentsService;
@RequestMapping(value = "/pdf", method = RequestMethod.GET)
@ResponseBody
@Validated
public void downloadFile(@RequestParam(value = "address") String address, HttpServletResponse response) throws IOException, ConvertFailedException {
attachmentsService.libreOfficeOnlinePreview(address, response);
}
}
5 attachementService 代码
public void libreOfficeOnlinePreview(String url, HttpServletResponse response) throws Exception {
//获取文件类型
String[] str = SmartStringUtil.split(url, "\\.");
if (str.length == 0) {
throw new Exception("文件格式不正确");
}
String suffix = str[str.length - 1];
if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
&& !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")) {
throw new Exception("文件格式不支持预览");
}
PdfUtils.wordToPdf(url, response);
}
6 PdfUtils 代码
package com.ieslab.pdfview.service.fileservice;
import com.liumapp.workable.converter.WorkableConverter;
import com.liumapp.workable.converter.core.ConvertPattern;
import com.liumapp.workable.converter.exceptions.ConvertFailedException;
import com.liumapp.workable.converter.factory.CommonConverterManager;
import com.liumapp.workable.converter.factory.ConvertPatternManager;
import org.jodconverter.document.DefaultDocumentFormatRegistry;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
/**
* @version V1.0
* @Title:
* @Package com.ieslab.pdfview.service.fileservice
* @Description: TODO
* @author: zongmoumou
* @date 2020/10/13
*/
public class PdfUtils {
public static void wordToPdf(String address, HttpServletResponse response) throws IOException, ConvertFailedException {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String tempFilePath = "temp-" + uuid + ".pdf";
WorkableConverter converter = new WorkableConverter();
ConvertPattern pattern = ConvertPatternManager.getInstance();
// 处理本地文件
// pattern.streamToStream(new FileInputStream(address), new FileOutputStream(tempFilePath));
// 处理网络文件
pattern.streamToStream(FileConvertUtil.getInputStream(address), new FileOutputStream(tempFilePath));
pattern.setSrcFilePrefix(DefaultDocumentFormatRegistry.DOCX);
pattern.setDestFilePrefix(DefaultDocumentFormatRegistry.PDF);
converter.setConverterType(CommonConverterManager.getInstance());
boolean result = converter.convert(pattern.getParameter());
if (result) {
outputPdf(tempFilePath, response);
File file = new File(tempFilePath);
if (file != null) {
file.delete();
}
}
}
private static void outputPdf(String filePath, HttpServletResponse response) throws IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
ServletOutputStream out = null;
FileInputStream in = null;
try {
in = new FileInputStream(new File(filePath));
String[] dir = filePath.split("/");
String fileName = dir[dir.length - 1];
// 设置响应类型为html,编码为utf-8,处理相应页面文本显示的乱码
response.setContentType("application/octet-stream");
// 设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
out = response.getOutputStream();
// 读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (FileNotFoundException e) {
} finally {
response.flushBuffer();
try {
out.close();
in.close();
} catch (NullPointerException e) {
} catch (Exception e) {
}
}
}
}
7 FileConvertUtil 代码
public static InputStream getInputStream(String filePath) throws IOException {
// 创建URL
filePath = getEncodeUrl(filePath).replaceAll("\\+", "%20");
InputStream inputStream = null;
// 创建URL
URL url = new URL(filePath);
// 试图连接并取得返回状态码
URLConnection urlconn = url.openConnection();
urlconn.connect();
HttpURLConnection httpconn = (HttpURLConnection) urlconn;
int httpResult = httpconn.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
inputStream = urlconn.getInputStream();
}
return inputStream;
}