轻量级SpringBoot Office文档在线预览框架
框架简介
介绍:基于开源项目KkFileView源码提取出,封装成仅用于 Office文档预览(格式转换) 功能的一个通用组件; 原理是把Word转成PDF,PPT转成PDF,Excel转成HTML;
利用浏览器可以直接打开PDF和HTML的特点实现在线预览;环境安装:目前支持OpenOffice或LibreOffice实现文档格式转换,请自行安装(推荐使用LibreOffice,转出的格式相对较好)
安装 LibreOffice教程: https://www.cnblogs.com/lwjQAQ/p/16505854.html
LibreOffice下载: https://zh-cn.libreoffice.org/
OpenOffice下载: http://www.openoffice.org/
项目运行环境:
jdk1.8SpringBoot2.0
Demo地址:https://github.com/TomHusky/kkfilemini-spring-boot-starter-demo
GitHub:https://github.com/TomHusky/kkfilemini-spring-boot-starter
Gitee:https://gitee.com/luowenjie98/kkfilemini-spring-boot-starter
maven依赖坐标
目前暂未上传maven中央仓库,需要自行下载源码install之后使用
<dependency>
<groupId>io.github.tomhusky</groupId>
<artifactId>office-preview-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
配置说明
| 配置名称 | 解释 | 默认值 |
|---|---|---|
| office.plugin.home | office组件的安装路径 | 默认为LibreOffice / OpenOffice的安装位置 |
| office.plugin.task.timeout | 文件转换的超时时间,超过这个时间则自动转换失败 | 5m |
| office.plugin.server.ports | office组件占用的端口 | 2001,2002 |
| office.cache.enabled | 开启缓存 (true/false) | true |
| office.cache.type | 缓存类型 default(RocksDB),redis(Redisson),jdk(Map) | default |
| office.cache.file.dir | 文档转换的缓存路径,可以填绝对路径,相对路径是项目根路径 | 相对路径office-file文件夹 |
| office.cache.clean.cron | 清理缓存的定时任务表达式,仅在开启缓存时生效 | 0 0 1 * * * |
yml
office:
plugin:
home: C:\\Program Files\\LibreOffice
task:
timeout: 1M
server:
ports: 2001,2002
cache:
enabled: true
type: default
file:
dir: D:\project\demo
clean:
cron: 0 0 1 * * *
properties
office.plugin.home=C:\\Program Files\\LibreOffice
office.plugin.task.timeout=1M
office.plugin.server.ports=2001,2002
office.cache.enabled=true
office.cache.type=default
office.cache.file.dir=officeFile
office.cache.clean.cron=0 0 1 * * *
快速使用
直接注入
@Resource
private KKFileViewComponent kkFileViewComponent;
OfficeFileViewComponent中提供的方法
| 方法名称 | 解释 |
|---|---|
| File convertViewFile(File file) | 直接转换成可以预览的文件 word,ppt转成pdf excel转成html |
| String addFileToCache(File file) | 添加文件到缓存,添加的时候直接转换,返回可以预览的文件编号 |
| void addFileToCache(File file, String fileNo) | 添加文件到缓存,指定文件编号(保证唯一) |
| boolean cacheExistFile(String fileNo) | 判断文件编号是否存在缓存的文件 |
| void viewCacheFile(HttpServletResponse response, String fileNo) | 根据文件编号预览文件,直接使用response输出流;并且response的header加入file-type字段用于判断文件类型(pdf/html) |
代码示例
@Service
public class FileServiceImpl implements FileService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private KKFileViewComponent fileViewComponent;
@Autowired
private ObjectMapper objectMapper;
private final Map<String, FileCacheVo> tempFilePathCache = new ConcurrentHashMap<>();
private static final Set<String> ALLOW_FILE_TYPE = CollUtil.set(false, ".doc", ".docx", ".pdf", ".xlsx", ".xls", ".pptx", ".ppt");
private static final List<FileInfoRespVo> FILE_SET = new CopyOnWriteArrayList<>();
@Override
public FileInfoRespVo uploadFile(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));
if (!ALLOW_FILE_TYPE.contains(fileType)) {
throw new RuntimeException("不支持的文件类型!");
}
try {
String fileNo = IdUtil.getSnowflakeNextIdStr();
File tempFile = File.createTempFile(fileNo, fileType);
FileUtil.writeFromStream(file.getInputStream(), tempFile, true);
FileInfoRespVo fileInfoRespVo = new FileInfoRespVo();
fileInfoRespVo.setFileNo(fileNo);
fileInfoRespVo.setFileName(originalFilename);
fileInfoRespVo.setFileSuffix(fileType);
fileInfoRespVo.setCreateTime(new Date());
FILE_SET.add(fileInfoRespVo);
FileCacheVo fileCacheVo = new FileCacheVo();
fileCacheVo.setFileNo(fileNo);
fileCacheVo.setFileSuffix(fileType);
fileCacheVo.setFileName(fileNo + fileType);
fileCacheVo.setOriginalName(originalFilename);
fileCacheVo.setPath(tempFile.getPath());
// 添加预览文档到缓存
fileViewComponent.addFileToCache(tempFile, fileNo);
tempFilePathCache.put(fileNo, fileCacheVo);
return fileInfoRespVo;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException("上传文件失败");
}
}
@Override
public void viewFile(String fileNo, HttpServletResponse response) {
response.addHeader("access-control-allow-methods", "GET");
response.addHeader("access-control-allow-headers", "Content-Type");
FileCacheVo fileCacheVo = tempFilePathCache.get(fileNo);
if (fileCacheVo == null) {
responseFailure("文件不存在!", response);
return;
}
boolean existFile = fileViewComponent.cacheExistFile(fileNo);
if (!existFile) {
responseFailure("文件已经不存在!", response);
return;
}
// 预览文档
fileViewComponent.viewCacheFile(response, fileNo);
}
private void responseFailure(String msg, HttpServletResponse response) {
response.setContentType("application/json; charset=utf-8");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
try (PrintWriter pw = response.getWriter()) {
String result = objectMapper.writeValueAsString(R.fail(msg));
pw.write(result);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
前端使用方式
注意:viewFile是接入的后端服务自己接口,本组件不直接提供接口
axios.get("http://localhost:8081/officePreview/viewFile?fileNo=" + item.fileNo, {responseType: "blob"}).then(res => {
let type = res.headers['file-type'];
let blob;
if (type === "html") {
blob = new Blob([res.data], {type: 'text/html'});
} else {
blob = new Blob([res.data], {type: 'application/pdf'})
}
let pdfSrc = window.URL.createObjectURL(blob)
window.open(pdfSrc)//新窗口打开,借用浏览器查看文档
}).catch(error => {
alert("预览失败!");
})
轻量级SpringBoot Office文档在线预览框架的更多相关文章
- Java版office文档在线预览
java将office文档pdf文档转换成swf文件在线预览 第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux ...
- Office文档在线预览
工具说明:通过传入文档的Web地址,即可进行Office文档的在线预览. 使用方式: 在http://office.qingshanboke.com地址后,通过url参数传入您想预览的文件路径. 如: ...
- 使用NextCloud搭建私有网络云盘并支持Office文档在线预览编辑以及文件同步
转载自:https://www.bilibili.com/read/cv16835328?spm_id_from=333.999.0.0 0x00 前言简述 描述:由于个人家里的NAS以及公司团队对私 ...
- 快速实现office文档在线预览展示(doc,docx,xls,xlsx,ppt,pptx)
微软:https://view.officeapps.live.com/op/view.aspx?src=(输入你的文档在服务器中的地址):
- Java实现word文档在线预览,读取office文件
想要实现word或者其他office文件的在线预览,大部分都是用的两种方式,一种是使用openoffice转换之后再通过其他插件预览,还有一种方式就是通过POI读取内容然后预览. 一.使用openof ...
- Java+FlexPaper+swfTools 文档在线预览demo
1.概述 主要原理 1.通过第三方工具openoffice,将word.excel.ppt.txt等文件转换为pdf文件 2.通过swfTools将pdf文件转换成swf格式的文件 3.通过FlexP ...
- 基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览
在博客园很多文章里面,曾经有一些介绍Office文档预览查看操作的,有些通过转为PDF进行查看,有些通过把它转换为Flash进行查看,但是过程都是曲线救国,真正能够简洁方便的实现Office文档的预览 ...
- Java+FlexPaper+swfTools仿百度文库文档在线预览系统设计与实现
笔者最近在给客户开发文档管理系统时,客户要求上传到管理系统的文档(包括ppt,word,excel,txt)只能预览不允许下载.笔者想到了百度文库和豆丁网,百度文库和豆丁网的在线预览都是利用flash ...
- [转载]基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览
在博客园很多文章里面,曾经有一些介绍Office文档预览查看操作的,有些通过转为PDF进行查看,有些通过把它转换为Flash进行查看,但是过程都是曲线救国,真正能够简洁方便的实现Office文档的预览 ...
- Print2flash在.NET(C#)64位中的使用,即文档在线预览
转:http://www.cnblogs.com/flowwind/p/3411106.html Print2flash在.NET(C#)中的使用,即文档在线预览 office文档(word,ex ...
随机推荐
- windows下IPv4通信(C++、MFC)
Cilect #include <stdio.h> #include <Ws2tcpip.h> #include <winsock2.h> #define HELL ...
- Qt-udp通信
1 简介 参考视频:https://www.bilibili.com/video/BV1XW411x7NU?p=61 说明:UDP是面向无连接的,客户端并不与服务器不建立连接,直接向服务器发送数据, ...
- 无需搭建环境,零门槛带你体验Open-Sora文生视频应用
本文分享自华为云社区<Open-Sora 文生视频原来在AI Gallery上也能体验了>,作者:码上开花_Lancer. 体验链接:Open-Sora 文生视频案例体验 不久前,Open ...
- react mock数据
为什么要做假数据,因为后端开发接口没有哪么快,此时就需要自己来模拟请求数据. 模拟的数据字段,需要和后端工程师沟通. 创建所需数据的json文件 json-server 此命令可以帮助我们快速创建一个 ...
- for while 要求选慢速的,但是for不卡,while 跟 递归 这两个容易卡
for比while慢,但是for不卡,while跟递归容易卡 int index = 0; bool jump=flase: for( index;index==0;;)/*这个空分号算一个语句*/ ...
- nginx resolver 指定多个DNS (2个DNS)
nginx resolver 指定多个DNS (2个DNS) 直接在 resolver 后边填2个DNS,中间用空格 location / { resolver 223.5.5.5 114.114.1 ...
- 使用 nsenter 排查容器网络问题
需求 我想进入容器中执行 curl 命令探测某个地址的连通性,但是容器镜像里默认没有 curl 命令.我这里是一个内网环境不太方便使用 yum 或者 apt 安装,怎么办? 这个需求比较典型,这里教大 ...
- mysql数据库慢SQL优化
mysql数据库慢SQL优化优化来源: 阿里云 云数据库RDS 慢sql 或者CAT监控系统中的Transaction SQL or URL根据平均时间反馈来排查,决定是否增加索引,或者调整业务逻辑代 ...
- C#.NET与JAVA互通之DES加密V2024
C#.NET与JAVA互通之DES加密V2024 配置视频: 环境: .NET Framework 4.6 控制台程序 JAVA这边:JDK8 (1.8) 控制台程序 注意点: 1.由 ...
- 安装Ingress-Nginx
目前,DHorse(https://gitee.com/i512team/dhorse)只支持Ingress-nginx的Ingress实现,下面介绍Ingress-nginx的安装过程. 下载安装文 ...