具体需求是:针对上传的各种office文件(包括.excel,.doc,.docx等)可以下载亦可以在线预览;
写博客的时候有时无暇顾及一些小细节,给读者带来疑问也很正常,所以在看一些博客的时候,多琢磨,不要着急;
实现涉及技术:
利用openOffice把word、excel、txt等类型的文档转换成pdf;
再借助swftools将pdf转换成swf;
然后利用FlexPaper插件实现在线播放预览;
所以需要借助一些工具,先得做好准备工作:
1.openoffice是Apache下的一个开放免费的文字处理软件
下载地址:http://www.openoffice.org/zh-cn/download/
2.SWFTools是一组用来处理Flash的swf文件的工具包,我们使用它将pdf文件转成swf文件!
下载地址:http://www.swftools.org/download.html
3.FlexPaper是一个开源轻量级的在浏览器上显示各种文档的组件
下载地址:FlexPaper官网下载
注意:现在的官网下载具体地址我也没找到,网上有很多免费的demo,可以下载下来,里面的jsp,js复制过来用就ok了;
4.JODConverter一个Java的OpenDocument文件转换器,在此我们只用到它的jar包
下载地址:JODCConverter下载
注意,如果用jodconverter2.2.1不支持doc,需要替换为2.2.2
下载好后
将所下载的文件(JODConverter除外)进行安装,盘符可随自己设定!需要注意的是在openoffice安装完成后,当我们使用它时,需将它的服务打开。在次我们需要以命令的方式打开:
可以编写一个.bat脚本来运行,注意如果不是默认路径替换成你自己的路径:
cd / cd "Program Files (x86)" cd "OpenOffice 4" cd program soffice -headless -accept="socket,host=127.0.01,port=8100;urp;" -nofirststartwizard
直接执行.bat就行或者手动:
打开cmd窗口,进入openoffice安装盘符,输入以下代码来启动服务:
soffice-headless -accept="socket,host=127.0.0.1,port=8100;urp;"-nofirststartwizard
注意最后一个命令前边的‘—’,可不要写错!服务起不来,项目可是继续不下去的哦.
检查8100有没有被监听:netstat -ano | find /i "8100"
或者查看进程:
说明已经启动;
开发过程:
由于一般当你用到这个功能时候,可能你的上传下载都已经写好了,至于上传下载那些个就不说了,我这里是之前别人写的项目,没有从零开始,
也就不一一叙述了,如果你是新搭建的项目从零开始,那么可以参照https://blog.csdn.net/pangxiao/article/details/78909289还是挺全面的;
我这里直接上项目代码及注意事项:
其中下载的
https://sourceforge.net/projects/jodconverter/files/
lib下面的jar包都搞到项目里面去;
上面是用到的jar;
页面(上传我就不展示了啊):
<table border="0" cellpadding="0" cellspacing="0" class="myTable"> <tbody> <c:forEach items="${aList }" var="item"> <tr> <td> <span class="mySpanFile"> <img alt="" src="${item.tagId }" style="width: 30px;height: 30px;margin: 5px 10px 5px 10px;"> </span> </td> <td style="width: 160px;"> <span class="mySpanFile"> <span style="overflow: hidden; text-overflow: ellipsis;-o-text-overflow: ellipsis;white-space:nowrap;width: 150px;display: block; "> ${item.orgName } </span> </span> <span>(${item.sizeKB }kb)</span> </td> <td style="min-width: 10px;"> <span class="mySpanFile"> <a style="text-decoration:underline;" href="javascript:;" target="_blank" class="preview" data-id="${item.appendixId }">预览</a> </span> </td> <td style="min-width: 10px;" > <span class="mySpanFile"> <a style="margin-left: 15px;text-decoration:underline;" href="javascript:;" class="uploadFile" data-id="${item.appendixId }">下载</a> </span> </td> <td> <span <c:if test="${del=='n' }">style="display: none;"</c:if> class="mySpanFile" > <a href="javascript:;" style="text-decoration:underline;" class="fileDel" data-id="${item.appendixId } " >删除</a> </span> </td> </tr> </c:forEach> </tbody> </table> 点击预览按钮:对应controller:
/** * 预览: * @param id * @param request * @param response * @return */ //@CrossOrigin @RequestMapping(value="preview",method = RequestMethod.GET) public String preview(Integer id,HttpServletRequest request,HttpServletResponse response){ String str= appendixService.preview(id, request); if(str.equals("img")){ return "bjdb/charge/approval/IMGView"; }else{ return "bjdb/charge/approval/documnetView"; } } 其中preview对应实现:
@Override public String preview(Integer id,HttpServletRequest request) { AppendixBean append = appendixBeanMapper.selectByPrimaryKey(id); String parentP = PropertySetting.getValue("default", "global", "attach-path"); String childenP = PropertySetting.getValue("default", "global", "attach-childen-path"); String img = PropertySetting.getValue("default", "global", "image"); String realPath =parentP+childenP; String converfilename=realPath+append.getPath(); HttpSession session = request.getSession(); if(append.getTagId().equals(img)){ session.setAttribute("swfpath", childenP+append.getPath()); return "img"; }else{ DocConverter d; try { d = new DocConverter(converfilename); d.conver(); String swfpath =d.getswfPath().substring(d.getswfPath().indexOf(childenP)); session.removeAttribute("swfpath"); session.setAttribute("swfpath", swfpath); } catch (Exception e) { e.printStackTrace(); } return "file"; } } preview中对应conver工具类:
package com.jky.until; /*import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; import com.jky.util.PropertySetting; *//** * doc docx格式转换 *//* public class DocConverter { private static Log log = LogFactory.getLog(DocConverter.class); private static final int environment = 1;// 环境 1:Windows 2:Linux private String fileString;// (只涉及PDF2swf路径问题) private String outputPath = "";// 输入路径 ,如果不设置就输出在默认 的位置 private String fileName; private File pdfFile; private File swfFile; private File docFile; public DocConverter(String fileString) { ini(fileString); if (log.isDebugEnabled()) { log.debug("转换文件路径" + fileString); } } *//** * 重新设置file * * @param fileString * 32. *//* public void setFile(String fileString) { ini(fileString); } *//** * @param fileString * *//* private void ini(String fileString) { this.fileString = fileString; fileName = fileString.substring(0, fileString.lastIndexOf(".")); docFile = new File(fileString); pdfFile = new File(fileName + ".pdf"); swfFile = new File(fileName + ".swf"); } *//** * 转为PDF * * @param file * *//* private void doc2pdf() throws Exception { if (docFile.exists()) { if (!pdfFile.exists()) { OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1",8100); try { connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); //2018/10/03修改,因为预览 //DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection); converter.convert(docFile, pdfFile); connection.disconnect(); if (log.isDebugEnabled()) { log.debug("pdf转换成功,PDF输出: " + pdfFile.getPath()); } } catch (java.net.ConnectException e) { log.error("swf转换器异常,openoffice 服务未启动", e); throw e; } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { log.error("swf转换器异常,读取转换文件失败(" + docFile + ")", e); throw e; } catch (Exception e) { log.error("swf转换器异常(" + docFile + ")", e); throw e; } } else { if (log.isDebugEnabled()) { log.debug("已经转换为pdf,不需要再进行转化(" + docFile + ")"); } } } else { if (log.isWarnEnabled()) { log.warn("swf转换器异常,需要转换的文档不存在(" + docFile + ")"); } } } *//** * 转换成 swf *//* @SuppressWarnings("unused") private void pdf2swf() throws Exception { Runtime r = Runtime.getRuntime(); if (!swfFile.exists()) { if (pdfFile.exists()) { if (environment == 1) {// windows环境处理 try { String exePath = PropertySetting.getValue("default", "global", "swftools-pdf2swf-path"); Process p = r.exec(exePath + " " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9"); if (log.isDebugEnabled()) { log.debug((loadStream(p.getInputStream()))); } log.error(loadStream(p.getErrorStream())); if (log.isDebugEnabled()) { log.debug(loadStream(p.getInputStream())); log.debug("swf转换成功,文件输出: " + swfFile.getPath()); } if (pdfFile.exists()) { pdfFile.delete(); } } catch (IOException e) { log.error("PDF转换为SWF错误", e); throw e; } } else if (environment == 2) {// linux环境处理 try { Process p = r.exec("pdf2swf" + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9"); if (log.isDebugEnabled()) { log.debug(loadStream(p.getInputStream())); } log.error(loadStream(p.getErrorStream())); if (log.isDebugEnabled()) { log.debug("swf转换成功,文件输出: " + swfFile.getPath()); } if (pdfFile.exists()) { pdfFile.delete(); } } catch (Exception e) { log.error("PDF转换为SWF错误", e); throw e; } } } else { log.error("pdf不存在,无法转换(" + pdfFile.getCanonicalPath() + ")"); } } else { if (log.isDebugEnabled()) { log.debug("swf已经存在不需要转换(" + swfFile.getCanonicalPath() + ")"); } } } static String loadStream(InputStream in) throws IOException { int ptr = 0; in = new BufferedInputStream(in); StringBuffer buffer = new StringBuffer(); while ((ptr = in.read()) != -1) { buffer.append((char) ptr); } return buffer.toString(); } *//** * * 转换主方法 *//* @SuppressWarnings("unused") public boolean conver() { if (swfFile.exists()) { if (log.isDebugEnabled()) { log.debug("swf转换器开始工作,该文件已经转换为 swf"); } return true; } if (environment == 1) { if (log.isDebugEnabled()) { log.debug("swf转换器开始工作,当前设置运行环境 windows"); } } else { if (log.isDebugEnabled()) { log.debug("swf转换器开始工作,当前设置运行环境 linux"); } } try { doc2pdf(); pdf2swf(); } catch (Exception e) { log.error("", e); return false; } if (swfFile.exists()) { if (log.isDebugEnabled()) { log.debug("文件存在(" + swfFile + ")"); } return true; } else { if (log.isWarnEnabled()) { log.warn("文件不存在(" + swfFile + ")"); } return false; } } *//** * 返回文件路径 * * @param *//* public String getswfPath() { if (this.swfFile.exists()) { String tempString = swfFile.getPath(); tempString = tempString.replaceAll("\\\\", "/"); if (log.isDebugEnabled()) { log.debug("最后文件路径为" + tempString); } return tempString; } else { return "文件不存在"; } } *//** * 设置输出路径 * * @param outputPath *//* public void setOutputPath(String outputPath) { this.outputPath = outputPath; if (!outputPath.equals("")) { String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf(".")); if (outputPath.charAt(outputPath.length()) == '/') { swfFile = new File(outputPath + realName + ".swf"); } else { swfFile = new File(outputPath + realName + ".swf"); } } } }*/ import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; import com.jky.util.PropertySetting; public class DocConverter { private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题) private String fileString; private String outputPath = "";// 输入路径,如果不设置就输出在默认位置 private String fileName; private File pdfFile; private File swfFile; private File docFile; public DocConverter(String fileString) { ini(fileString); } // * 重新设置 file @param fileString public void setFile(String fileString) { ini(fileString); } //初始化 @param fileString private void ini(String fileString) { this.fileString = fileString; fileName = fileString.substring(0, fileString.lastIndexOf(".")); docFile = new File(fileString); pdfFile = new File(fileName + ".pdf"); swfFile = new File(fileName + ".swf"); } // 转为PDF @param file private void doc2pdf() throws Exception { if (docFile.exists()) { if (!pdfFile.exists()) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100); try { connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(docFile, pdfFile); // close the connection connection.disconnect(); System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****"); } catch (java.net.ConnectException e) { // ToDo Auto-generated catch block e.printStackTrace(); System.out.println("****swf转换异常,openoffice服务未启动!****"); throw e; } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { e.printStackTrace(); System.out.println("****swf转换器异常,读取转换文件失败****"); throw e; } catch (Exception e) { e.printStackTrace(); throw e; } } else { System.out.println("****已经转换为pdf,不需要再进行转化****"); } } else { System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****"); } } // 转换成swf @SuppressWarnings("unused") private void pdf2swf() throws Exception { Runtime r = Runtime.getRuntime(); if (!swfFile.exists()) { if (pdfFile.exists()) { if (environment == 1)// windows环境处理 { try { // 这里根据SWFTools安装路径需要进行相应更改 String exePath = PropertySetting.getValue("default","global", "swftools-pdf2swf-path"); Process p = r.exec(exePath + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9"); System.out.print(loadStream(p.getInputStream())); System.err.print(loadStream(p.getErrorStream())); System.out.print(loadStream(p.getInputStream())); System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****"); if (pdfFile.exists()) { pdfFile.delete(); } } catch (Exception e) { e.printStackTrace(); throw e; } } else if (environment == 2)// linux环境处理 { try { Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9"); System.out.print(loadStream(p.getInputStream())); System.err.print(loadStream(p.getErrorStream())); System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****"); if (pdfFile.exists()) { pdfFile.delete(); } } catch (Exception e) { e.printStackTrace(); throw e; } } } else { System.out.println("****pdf不存在,无法转换****"); } } else { System.out.println("****swf已存在不需要转换****"); } } static String loadStream(InputStream in) throws IOException { int ptr = 0; //把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder buffer = new StringBuilder(); while ((ptr = reader.read()) != -1) { buffer.append((char) ptr); } return buffer.toString(); } // 转换主方法 public boolean conver() { if (swfFile.exists()) { System.out.println("****swf转换器开始工作,该文件已经转换为swf****"); return true; } if (environment == 1) { System.out.println("****swf转换器开始工作,当前设置运行环境windows****"); } else { System.out.println("****swf转换器开始工作,当前设置运行环境linux****"); } try { doc2pdf(); pdf2swf(); } catch (Exception e) { // TODO: Auto-generated catch block e.printStackTrace(); return false; } if (swfFile.exists()) { return true; } else { return false; } } //返回文件路径 @param s public String getswfPath() { if (swfFile.exists()) { String tempString = swfFile.getPath(); tempString = tempString.replaceAll("\\\\", "/"); return tempString; } else { return ""; } } //设置输出路径 public void setOutputPath(String outputPath) { this.outputPath = outputPath; if (!outputPath.equals("")) { String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf(".")); if (outputPath.charAt(outputPath.length()) == '/') { swfFile = new File(outputPath + realName + ".swf"); } else { swfFile = new File(outputPath + realName + ".swf"); } } } public static void main(String s[]) { DocConverter d = new DocConverter("E:/test/fileTest/06b2af1010ec422bb8a74b34ffbb20ac.docx"); d.conver(); } } 其中DocConverter中对应的路径我的是在配置文件里面配置的,并且没有放在项目之下,数据库里面就存了id和关系;
<?xml version="1.0" encoding="utf-8"?> <setting> <category id="global"> <item key="attach-path" value="E:/test" name="附件在磁盘文件系统上的主目录" /> <item key="swftools-pdf2swf-path" value="C:/Program Files (x86)/SWFTools/pdf2swf.exe " /> <!-- 没有空格还不行 --> <item key="attach-childen-path" value="/fileTest/" name="附件在磁盘文件系统上的子目录" /> </category> <category id="outerNet"> <item key="url" value="http://127.0.0.1:8080" name="外网地址(文件服务器)" /> </category> </setting> value="C:/Program Files (x86)/SWFTools/pdf2swf.exe " exe后面没有空格还不行,这是由于工具类转换的问题;
其实以上做了件什么事情呢,就是将上传到e盘下的文件进行转换先转换成pdf再转换成.swf格式;然后将路径存在session中;返回到前台页面用:
代码运行到上面:点击预览按钮:对应controller,执行成功后将转换成的.swf文件路径放入session然后跳转到前台页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- saved from url=(0014)about:internet --> <%@page contentType="text/html;charset=GBK" %> <% String swfFilePath=session.getAttribute("swfpath").toString(); %> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> <style type="text/css" media="screen"> html, body { height:100%; } body { margin:0; padding:0; overflow:auto; } #flashContent { display:none; } </style> <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/javascript" src="/js/swfobject/swfobject.js"></script> <script type="text/javascript" src="/js/flexpaper_flash_debug.js"></script> <script type="text/javascript"> <!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. --> var swfVersionStr = "10.0.0"; var xiSwfUrlStr = "playerProductInstall.swf"; var swfFile = '<%=swfFilePath%>'; /* var swfFile = 'E:test/fileTest/b65d413d870a446cbb77b9910a385b02.swf'; */ swfFile = encodeURI(swfFile); var flashvars = { SwfFile : escape(swfFile), Scale : 0.6, StartAtPage:2, ZoomTransition : "easeOut", ZoomTime : 0.5, ZoomInterval : 0.2, FitPageOnLoad : true, FitWidthOnLoad : false, PrintEnabled : true, FullScreenAsMaxWindow : false, ProgressiveLoading : true, // PrintToolsVisible : true, // ViewModeToolsVisible : true, // ZoomToolsVisible : true, // FullScreenVisible : true, // NavToolsVisible : true, // CursorToolsVisible : true, // SearchToolsVisible : true, localeChain: "zh_CN" }; var params = { } params.quality = "high"; params.bgcolor = "#ffffff"; params.allowscriptaccess = "sameDomain"; params.allowfullscreen = "true"; var attributes = {}; attributes.id = "FlexPaperViewer"; attributes.name = "FlexPaperViewer"; swfobject.embedSWF( "FlexPaperViewer.swf", "flashContent", "1200", "600", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes); swfobject.createCSS("#flashContent", "display:block;text-align:left;"); </script> </head> <body> <div style="position:absolute;left:10px;top:10px;"> <div id="flashContent"> <p> To view this page ensure that Adobe Flash Player version 10.0.0 or greater is installed. </p> <script type="text/javascript"> var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://"); document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='" + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>"); </script> </div> </div> <!-- <div style="position:absolute;left:750px;top:10px;font-family:Verdana;font-size:9pt;"> <table border="0" width="230"> <tr><th colspan=3>Operations</th></tr> <tr><td>loadSwf</td><td><input type=text style="width:70px;" id="txt_swffile" value="Paper.swf"></td><td><input type=submit value="Invoke" οnclick="getDocViewer().loadSwf($('#txt_swffile').val())"></td></tr> <tr><td>fitWidth</td><td></td><td><input type=submit value="Invoke" οnclick="getDocViewer().fitWidth()"></td></tr> <tr><td>fitHeight</td><td></td><td><input type=submit value="Invoke" οnclick="getDocViewer().fitHeight()"></td></tr> <tr><td>gotoPage</td><td><input type=text style="width:70px;" id="txt_pagenum" value="3"></td><td><input type=submit value="Invoke" οnclick="getDocViewer().gotoPage($('#txt_pagenum').val())"></td></tr> <tr><td>getCurrPage</td><td></td><td><input type=submit value="Invoke" οnclick="alert('Current page:' + getDocViewer().getCurrPage())"></td></tr> <tr><td>nextPage</td><td></td><td><input type=submit value="Invoke" οnclick="getDocViewer().nextPage()"></td></tr> <tr><td>prevPage</td><td></td><td><input type=submit value="Invoke" οnclick="getDocViewer().prevPage()"></td></tr> <tr><td>setZoom</td><td><input type=text style="width:70px;" id="txt_zoomfactor" value="1.30"></td><td><input type=submit value="Invoke" οnclick="getDocViewer().setZoom($('#txt_zoomfactor').val())"></td></tr> <tr><td>searchText</td><td><input type=text style="width:70px;" id="txt_searchtext" value="text"></td><td><input type=submit value="Invoke" οnclick="getDocViewer().searchText($('#txt_searchtext').val())"></td></tr> <tr><td>switchMode</td><td><input type=text style="width:70px;" id="txt_viewmode" value="Tile"></td><td><input type=submit value="Invoke" οnclick="getDocViewer().switchMode($('#txt_viewmode').val())"></td></tr> <tr><td>printPaper</td><td></td><td><input type=submit value="Invoke" οnclick="getDocViewer().printPaper()"></td></tr> </table> <br/><br/> <table border="0" width="230"> <tr><th>Event Log</th></tr> <tr><td><textarea rows=6 cols=28 id="txt_eventlog" style="width:215px;"></textarea></td></tr> <tr><td><input type=text style="width:215px;" id="txt_progress" value=""></td></tr> </table> </div> --> </body> </html>
https://blog.csdn.net/weixin_41524017/article/details/82996057
