1.先下载openoffice,官网下载Apache OpenOffice - Official Download
觉得官网下载慢的可以进我的主页下载Apache_OpenOffice_4.1.6_install_zh-CN.rar_springboot集成openoffice-互联网文档类资源-CSDN下载
下完之后直接安装就行
2.在pom.xml加入以下配置
<!--springboot支持包,里面包括了自动配置类 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-spring-boot-starter -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.2.2</version>
</dependency>
<!--jodconverter 本地支持包 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-local -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.2.2</version>
</dependency>
3.在application.yml加入配置(在最后面加入就行)
jodconverter:
local:
enabled: true
max-tasks-per-process: 10
port-numbers: 8100
office-home: C:/Program Files (x86)/OpenOffice 4
4.核心代码controller层。
/**
* 文件预览
*
* @param fileName 文件名
* @param funcType 功能类型
* @param uuidName uuid
* @param response
* @throws IOException
*/
@ApiOperation(value = "/previewFile", httpMethod = "POST", notes = "文件预览")
@GetMapping(value = "previewFile")
public void preview(
@RequestParam("fileName") String fileName,@RequestParam("funcType") String funcType,@RequestParam("uuidName") String uuidName,HttpServletResponse response
) throws IOException {
String realPath = root + funcType + "/" + uuidName;
if (!org.springframework.util.StringUtils.isEmpty(realPath)){
File file = new File(realPath);//需要转换的文件
try {
String[] strings = fileName.split("\\.");
//默认转pdf,excel转html
String suffix = ".pdf";
if("xlsx".equals(strings[strings.length - 1]) || "xls".equals(strings[strings.length - 1])){
suffix = ".html";
}
String tmpPath = tmpFileRoot + funcType + "/" + strings[0] + suffix;
File tmpFile = new File(tmpPath);
//不存在-文件转化
//if(!tmpFile.exists()){
converter.convert(file).to(tmpFile).execute();
//}
//使用response,将pdf文件以流的方式发送到前端
ServletOutputStream outputStream = response.getOutputStream();
InputStream in = new FileInputStream(tmpFile);// 读取文件
// copy文件
IOUtils.copy(in, outputStream);
in.close();
outputStream.close();
tmpFile.delete();
//return FileUtil.toHtmlString(tmpFile,tmpPath);
} catch (Exception e) {
e.printStackTrace();
}
}
//return "查看失败";
}
5.总结一下:openoffice4.1.6 word,png,pptx格式的转成pdf的格式是正常的,但是excel的话只能格式有点乱,所以就转成html吧。
后续会对这转换代码做些性能优化的地方。