背景
之前一直是用户点击下载word文件到本地,然后使用office或者wps打开。需求优化,要实现可以直接在线预览,无需下载到本地然后再打开。
随后开始上网找资料,网上资料一大堆,方案也各有不同,大概有这么几种方案:
1.word转html然后转pdf
2.Openoffice + swftools + Flexmapper + jodconverter
3.kkFileView
分析之后最后决定使用Openoffice+PDF.js方式实现
环境搭建
1.安装Openoffice,下载地址:http://www.openoffice.org/download/index.html
安装完成之后,cmd进入安装目录执行命令:soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard
2.PDF.js,下载地址:http://mozilla.github.io/pdf.js/
下载之后解压,目录结构如下:
代码实现
编码方面,分前端后:
后端:java后端使用openoffice把word文档转换成pdf文件,返回流
前端:把PDF.js解压后的文件加到项目中,修改对应路径,PDF.js拿到后端返回的流直接展示
后端
项目使用springboot,pom文件添加依赖
com.artofsolving
jodconverter
2.2.1
org.openoffice
jurt
3.0.1
org.openoffice
ridl
3.0.1
org.openoffice
juh
3.0.1
org.openoffice
unoil
3.0.1
application.properties配置openoffice服务地址与端口
openoffice.host=127.0.0.1
openoffice.port=8100
doc文件转pdf文件
importjava.io.BufferedInputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.net.ConnectException;importjavax.servlet.http.HttpServletResponse;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importcom.xxx.utils.Doc2PdfUtil;
@Controller
@RequestMapping("/doc2PdfController")public classDoc2PdfController {
@Value("${openoffice.host}")privateString OpenOfficeHost;
@Value("${openoffice.port}")privateInteger OpenOfficePort;private Logger logger = LoggerFactory.getLogger(Doc2PdfController.class);
@RequestMapping("/doc2pdf")public voiddoc2pdf(String fileName,HttpServletResponse response){
File pdfFile= null;
OutputStream outputStrea