前言
总所周知,上传word文件,在浏览器使用pdf预览是一个比较好的方案,但使用POI和一些组件搭配使用,那个代码是又臭又长,而且转出来的PDF还有各种问题,效果不好。

我采用的方法,代码优雅一行就行,就是需要依赖组件。
springboot+libraryOffice+jodconverter
废话不多说直接开始:
第一步:导入依赖
pom.xml
<!-- LibreOffice转PDF -->
<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>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
第二步,下载 LibreOffice
链接: libreoffice官网
傻瓜式一键安装,默认安装路径,会在这里

进入这个目录CMD:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

第三步,编写yml文件
# 本地
jodconverter:
local:
enabled: true
max-tasks-per-process: 10
port-numbers: 8100
office-home: C:/Program Files/LibreOffice
第四步,直接使用即可
@Autowired
private DocumentConverter converter;
/**
* 将office文件转换为pdf文件
*
* @param fileType 文件后缀
* @param in 输入流
* @return 输出流
*/
public ByteArrayOutputStream savePdf(String fileType, InputStream in) throws OfficeException {
String starttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
long start = System.currentTimeMillis();
System.out.println("开始将文件转成PDF:" + starttime);
ByteArrayOutputStream out = new ByteArrayOutputStream();
switch (fileType) {
case "doc":
converter.convert(in).as(DefaultDocumentFormatRegistry.DOC).to(out).as(DefaultDocumentFormatRegistry.PDF).execute();
break;
case "docx":
converter.convert(in).as(DefaultDocumentFormatRegistry.DOCX).to(out).as(DefaultDocumentFormatRegistry.PDF).execute();
break;
case "xls":
converter.convert(in).as(DefaultDocumentFormatRegistry.XLS).to(out).as(DefaultDocumentFormatRegistry.PDF).execute();
break;
case "xlsx":
converter.convert(in).as(DefaultDocumentFormatRegistry.XLSX).to(out).as(DefaultDocumentFormatRegistry.PDF).execute();
break;
case "ppt":
converter.convert(in).as(DefaultDocumentFormatRegistry.PPT).to(out).as(DefaultDocumentFormatRegistry.PDF).execute();
break;
case "pptx":
converter.convert(in).as(DefaultDocumentFormatRegistry.PPTX).to(out).as(DefaultDocumentFormatRegistry.PDF).execute();
break;
case "1":
// 还可以将任意数据类型转成HTML
converter.convert(in).as(DefaultDocumentFormatRegistry.PPTX).to(out).as(DefaultDocumentFormatRegistry.HTML).execute();
break;
default:
throw new OfficeException("不支持的文档类型");
}
String stopTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
long stop = System.currentTimeMillis();
System.out.println("结束将文件转成PDF:" + stopTime);
System.out.println("PDF转换耗时:" + (stop - start) + "毫秒");
return out;
}
教程就到这里,就可以正常使用了。
效果:
word:

pdf:

转出来是会又一点点,错位但已经效果很好了。
顺便在这里请教以下大佬们,如果我将LibreOffice 安装到服务器上,我怎么指定我的远程配置,找的几个文章都不好用。

4471

被折叠的 条评论
为什么被折叠?



