框架简介

介绍:基于开源项目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.8 SpringBoot2.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

在线试用地址:https://tools.go996.cn/docView/

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文档在线预览框架的更多相关文章

  1. Java版office文档在线预览

    java将office文档pdf文档转换成swf文件在线预览 第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux ...

  2. Office文档在线预览

    工具说明:通过传入文档的Web地址,即可进行Office文档的在线预览. 使用方式: 在http://office.qingshanboke.com地址后,通过url参数传入您想预览的文件路径. 如: ...

  3. 使用NextCloud搭建私有网络云盘并支持Office文档在线预览编辑以及文件同步

    转载自:https://www.bilibili.com/read/cv16835328?spm_id_from=333.999.0.0 0x00 前言简述 描述:由于个人家里的NAS以及公司团队对私 ...

  4. 快速实现office文档在线预览展示(doc,docx,xls,xlsx,ppt,pptx)

    微软:https://view.officeapps.live.com/op/view.aspx?src=(输入你的文档在服务器中的地址):

  5. Java实现word文档在线预览,读取office文件

    想要实现word或者其他office文件的在线预览,大部分都是用的两种方式,一种是使用openoffice转换之后再通过其他插件预览,还有一种方式就是通过POI读取内容然后预览. 一.使用openof ...

  6. Java+FlexPaper+swfTools 文档在线预览demo

    1.概述 主要原理 1.通过第三方工具openoffice,将word.excel.ppt.txt等文件转换为pdf文件 2.通过swfTools将pdf文件转换成swf格式的文件 3.通过FlexP ...

  7. 基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览

    在博客园很多文章里面,曾经有一些介绍Office文档预览查看操作的,有些通过转为PDF进行查看,有些通过把它转换为Flash进行查看,但是过程都是曲线救国,真正能够简洁方便的实现Office文档的预览 ...

  8. Java+FlexPaper+swfTools仿百度文库文档在线预览系统设计与实现

    笔者最近在给客户开发文档管理系统时,客户要求上传到管理系统的文档(包括ppt,word,excel,txt)只能预览不允许下载.笔者想到了百度文库和豆丁网,百度文库和豆丁网的在线预览都是利用flash ...

  9. [转载]基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览

    在博客园很多文章里面,曾经有一些介绍Office文档预览查看操作的,有些通过转为PDF进行查看,有些通过把它转换为Flash进行查看,但是过程都是曲线救国,真正能够简洁方便的实现Office文档的预览 ...

  10. Print2flash在.NET(C#)64位中的使用,即文档在线预览

    转:http://www.cnblogs.com/flowwind/p/3411106.html Print2flash在.NET(C#)中的使用,即文档在线预览   office文档(word,ex ...

随机推荐

  1. css 透明气泡效果

    css body { background:#333333; } .login-card { text-align:center; width:430px; height:430px; margin: ...

  2. .NET Core Configuration 配置项知识点一网打尽!

    控制台项目中,演示示例 1.自定义 Dictionary Config  内存字典模式 dotnet add package Microsoft.Extensions.Configuration IC ...

  3. memoization(计算属性-记忆组件)

    连续两次相同传参,第二次会直接返回上次的结果,每次传参不一样,就直接调用函数返回新的结果,会丢失之前的记录,并不是完全记忆,可以在它的参数中传入state数据从而实现了类似Vue中的计算属性功能 # ...

  4. C#.NET 读取PFX私钥证书并导出PEM格式私钥

    项目nuget引用 BouncyCastle. 读取证书 X509Certificate2 x509 = new X509Certificate2(lblPfxPath.Text, txtPfxPwd ...

  5. Java与React轻松导出Excel/PDF数据

    前言 在B/S架构中,服务端导出是一种高效的方式.它将导出的逻辑放在服务端,前端仅需发起请求即可.通过在服务端完成导出后,前端再下载文件完成整个导出过程.服务端导出具有许多优点,如数据安全.适用于大规 ...

  6. 聊一聊 Monitor.Wait 和 Pluse 的底层玩法

    一:背景 1. 讲故事 在dump分析的过程中经常会看到很多线程卡在Monitor.Wait方法上,曾经也有不少人问我为什么用 !syncblk 看不到 Monitor.Wait 上的锁信息,刚好昨天 ...

  7. typroa破解

    Typora 一款 Markdown 编辑器和阅读器 风格极简 / 多种主题 / 支持 macOS,Windows 及 Linux 实时预览 / 图片与文字 / 代码块 / 数学公式 / 图表 目录大 ...

  8. C++面向对象多级菜单向Arduino的移植

    前段时间写了一篇文章<C++面向对象语言自制多级菜单>,文中指出了可以将HeleMenu库进行移植,现已完成技术思路,特此记录. 一.特性 基本与上一篇文章指出的一致,只是将菜单显示和响应 ...

  9. 图片接口JWT鉴权实现

    图片接口JWT鉴权实现 前言 之前做了个返回图片链接的接口,然后没做授权,然后今天键盘到了,也是用JWT来做接口的权限控制. 然后JTW网上已经有很多文章来说怎么用了,这里就不做多的解释了,如果不懂的 ...

  10. Android 7 修改启动动画和开机声音

    背景 在修改开机音量的时候,发现找不到对应的声音功能调用. 因此了解了一下安卓的开机声音是如何实现的. 安卓4~安卓7 都可以这么做. 参考: https://blog.csdn.net/chen82 ...