由于项目的功能需要看了一下文件预览的功能实现,主要是看office的word,excel,ppt这些的在线预览。
比较常见的是以下两种:
一、通过iframe直接引用微软提供的方法(最简单)
<iframe src='https://view.officeapps.live.com/op/view.aspx?src=http://storage.xuetangx.com/public_assets/xuetangx/PDF/1.xls' width='100%' height='100%' frameborder='1'>
</iframe>
在 https://view.officeapps.live.com/op/view.aspx?src= 后边添加需要预览的内容
问题:1、必须可以访问网络,https://view.officeapps.live.com/op/view.aspx
2、预览资源是有网络资源,本地资源不可以,或者找到本地资源转换网络资源的方法
二:OpenOffice实现前端在线预览
思路:把需要在线预览PDF、excle、ppt、word文件转换成pdf,然后页面展示的是pdf
问题:需要安装OpenOffice(环境准备麻烦,其实也不麻烦。) http://www.openoffice.org/zh-cn/download/
大家可以根据自己的情况选择,由于我的情况是不能访问外网,所以选择了openoffice的方式。
下面简单的说下怎么实现
1、安装openoffice
windows版的不多说,就是下载之后,运行就行,还是说下启动:找到安装目录,
运行→cmd,输入:
cd C:Program Files (x86)OpenOffice 4program
回车
再输入
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
回车就可以了
接下来说下,linux版的,https://www.cnblogs.com/goodcheap/p/7929986.html,这个写的具体,可以参考一下
此处需要提醒的host后面的ip,如果不是本机访问,请不要写127.0.0.1,请写机器对应的ip!!!!否则下面的请求会找不到服务
另外需要注意的是中文乱码问题,原因是linux没有那些字体,所以需要拷贝字体到liunx
(1)用vim /etc/fonts/fonts.conf,可以看到系统字体文件的目录
(2)将windows系统字体文件拷贝到此目录下
(3)重建Linux字体索引
mkfontscale
mkfontdir
fc-cache
重启openoffice。。。
pom.xml
<!--openoffice --><dependency><groupId>org.artofsolving.jodconverter</groupId><artifactId>jodconverter-core</artifactId><version>3.0-beta-4</version></dependency><dependency><groupId>com.artofsolving</groupId><artifactId>jodconverter</artifactId><version>2.2.2</version></dependency>jodconverter.jar一定要是2.2.2版本的,其他版本的不能解析2007版的文件,会报转换错误https://download.csdn.net/download/duanqiaocanyue2012/10849582
代码部分:
public class OfficePDFUtils { private static final Logger logger = LoggerFactory.getLogger(OfficePDFUtils.class); private static String[] docFile = {".txt", ".doc", ".docx", ".wps", ".xls", ".xlsx", ".et", ".ppt", ".pptx", ".dps"};// office办公软件格式 public static boolean office2PDF(String ip, int port, String sourceFile, String destFile) { try { File inputFile = new File(sourceFile); if (!inputFile.exists()) { logger.info("找不到源文件"); return false;// 找不到源文件, 则返回-1 } // 如果目标路径不存在, 则新建该路径 File outputFile = new File(destFile); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } // connect to an OpenOffice.org instance running on port 8100 OpenOfficeConnection connection = new SocketOpenOfficeConnection(ip, port); connection.connect(); // convert DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); // close the connection connection.disconnect(); logger.info("路径:" + destFile); return true; } catch (ConnectException e) { logger.warn("ConnectException", e); } return true; } /** * 可解析的文件 * * @author tang * @method isConvertible * @param fileName * @return * @return boolean */ public static boolean isConvertible(String fileName) { String after = StringUtils.extractAfter(fileName, "."); for (String type : docFile) { if (type.contains(after)) { return true; } } return false; } }