openoffice实现pdf上传文件预览功能
2015-12-03 08:47
477 查看
今天在项目中遇到了一个需要预览上传文件的需求,上传的文件格式主要有word文档和Excel表格以及pdf文档,客户要求能够上传后打开预览查看文件内容,由此在其他项目借鉴了一下别人写的预览功能,觉得很不错特此保留下来以备以后留用,也给需要的朋友分享一下。
1.先下载操作系统对应的openoffice并且安装 地址:https://www.openoffice.org/download/other.html
openoffice 主要目的是将文档转换为pdf文档.
2. windows 下 启动 openoffice 占用默认端口8100
cd C:\Program Files (x86)\OpenOffice 4\program(你电脑上openoffice的安装路径)
执行 soffice -headless -accept="socket,host=127.0.0.1,port=8111;urp;" -nofirststartwizard
3.导入项目中预览功能需求要用的jar包:
ezmorph-1.0.5.jar
jodconverter-2.2.2.jar
jodconverter-cli-2.2.2.jar
morph-1.1.1.jar
juh-3.0.1.jar
jurt-3.0.1.jar
ridl-3.0.1.jar
unoil-3.0.1.jar
xstream-1.3.1.jar
4.写一个转换类DocConverter.java
/** * doc docx格式转换 */ public class DocConverter extends BaseAdminAction { 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; private String ctx; HttpServletResponse response; 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"); } /** * 转换主方法成为html */ @SuppressWarnings("unused") public void convertoHtml(String ctxDir, String save_path, String file_name) { if (StringUtils.isNotBlank(ctxDir)) { ctx = ctxDir; } String _save_path = ""; if (StringUtils.isNotBlank(save_path)) { if (save_path.endsWith(".doc")) { _save_path = save_path.replaceAll(".doc", ""); } else if (save_path.endsWith(".docx")) { _save_path = save_path.replaceAll(".docx", ""); } else if (save_path.endsWith(".xls")) { _save_path = save_path.replaceAll(".xls", ""); } else if (save_path.endsWith(".xlsx")) { _save_path = save_path.replaceAll(".xlsx", ""); } else if (save_path.endsWith(".ppt")) { _save_path = save_path.replaceAll(".ppt", ""); } else if (save_path.endsWith(".pptx")) { _save_path = save_path.replaceAll(".pptx", ""); } } toHtmlString(new File(ctx + "/" + save_path), ctx + "/" + _save_path, file_name, ctx); } /** * 将office文档转换成html文档 * * @param docFile 需要转换的office文档 * @param filepath 转换之后html的存放路径 * @return 转换之后的html文件 */ public static File convert(File docFile, String filepath, String file_name, String ctx) { // 创建保存html的文件 File htmlFile = new File(ctx + "/filesview/upload/" + file_name + ".html"); // 创建Openoffice连接 OpenOfficeConnection con = new SocketOpenOfficeConnection(8111); try { // 连接 con.connect(); } catch (ConnectException e) { System.out.println("获取OpenOffice连接失败..."); e.printStackTrace(); } // 创建转换器 DocumentConverter converter = new OpenOfficeDocumentConverter(con); // 转换文档问html converter.convert(docFile, htmlFile); // 关闭openoffice连接 con.disconnect(); return htmlFile; } /** * 将office转换成html文件,并且获取html文件代码。 * * @param docFile 需要转换的文档 * @param filepath 文档中图片的保存位置 * @return 转换成功的html代码 */ public static String toHtmlString(File docFile, String filepath, String file_name, String ctx) { // 转换word文档 File htmlFile = convert(docFile, filepath, file_name, ctx); // 获取html文件流 StringBuffer htmlSb = new StringBuffer(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile))); while (br.ready()) { htmlSb.append(br.readLine()); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // HTML文件字符串 String htmlStr = htmlSb.toString(); String docImgPath = "/view/upload"; // 返回经过清洁的html文本 return clearFormat(htmlStr, docImgPath); } /** * 清除一些不需要的html标记 * * @param htmlStr 带有复杂html标记的html语句 * @return 去除了不需要html标记的语句 */ protected static String clearFormat(String htmlStr, String docImgPath) { // 获取body内容的正则 String bodyReg = "<BODY .*</BODY>"; Pattern bodyPattern = Pattern.compile(bodyReg); Matcher bodyMatcher = bodyPattern.matcher(htmlStr); if (bodyMatcher.find()) { // 获取BODY内容,并转化BODY标签为DIV htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV").replaceAll("</BODY>", "</DIV>"); } // 调整图片地址 htmlStr = htmlStr.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + docImgPath + "/"); // 把<P></P>转换成</div></div>保留样式 // content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)", // "<div$2</div>"); // 把<P></P>转换成</div></div>并删除样式 htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>"); // 删除不需要的标签 htmlStr = htmlStr.replaceAll( "<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>", ""); // 删除不需要的属性 htmlStr = htmlStr .replaceAll( "<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>", "<$1$2>"); return htmlStr; } }
5.编写二个预览页面一个展示office类型文件一个展示pdf文件
office文件预览页面public_office_view.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="${ctx}/commons/scripts/jquery.js"></script> <style type="text/css"> .ico { background: url(images/ico_preview.png) no-repeat; } .down { background-position: -96px 0; width: 9px; height: 10px; display: inline-block; margin: 0; } .btn_down{ width: 60px; padding-left: 6px; font-size: 15px; } .btn_gray{ padding: 0; cursor: pointer; float: right; line-height: 21px; border-radius: 3px; text-align:center; border: 1px solid #888; color: #000000; color: #000000!important; background-color: #ccc; background: -moz-linear-gradient(top,#fff 0%,#ebebeb 90%,#F3F3F3 100%); background: -webkit-linear-gradient(top,#fff 0%,#ebebeb 90%,#F3F3F3 100%); } a{ text-decoration: none; } .divtop{ height:50px; border-bottom: 1px solid #ddd; margin: 5px; } .divtitle{ font-size: 26px; white-space: nowrap; font-weight: bold; color: #000; } </style> </head> <body> <div> <div class="divtop"> <span class="divtitle">${file_name}</span> <a href="${ctx}/${save_path}" class="btn_gray btn_down"><span class="ico down"></span>下载</a> </div> <div class="divcontent"> ${html} </div> </div> </body> </html>
PDF预览页面public_pdf_view.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${ctx}/commons/scripts/jquery.js"></script> <script type="text/javascript" src="${ctx}/commons/scripts/pdfobject.js"></script> <style type="text/css" media="screen"> html, body { height:100%; } body { margin:0; padding:0; overflow:auto; } #flashContent { display:none; } </style> <style type="text/css"> .ico { background: url(images/ico_preview.png) no-repeat; } .down { background-position: -96px 0; width: 9px; height: 10px; display: inline-block; margin: 0; } .btn_down{ width: 60px; padding-left: 6px; font-size: 15px; } .btn_gray{ padding: 0; cursor: pointer; float: right; line-height: 21px; border-radius: 3px; text-align:center; border: 1px solid #888; color: #000000; color: #000000!important; background-color: #ccc; background: -moz-linear-gradient(top,#fff 0%,#ebebeb 90%,#F3F3F3 100%); background: -webkit-linear-gradient(top,#fff 0%,#ebebeb 90%,#F3F3F3 100%); } a{ text-decoration: none; } .pTip{ text-align:center; font-size:20px; } .divtitle{ font-size: 26px; white-space: nowrap; font-weight: bold; color: #000; } </style> <title>${file_name}</title> </head> <body> <div> <!-- <div class="divtop"> --> <%-- <span class="divtitle">${file_name}</span> --%> <%-- <a href="${ctx}/${save_path}" class="btn_gray btn_down"><span class="ico down"></span>下载</a> --%> <!-- </div> --> <p class="pTip">您没有安装AdobeReader或者该浏览器不支持pdf在线预览,请你下载AdobeReader或者换用其他浏览器! <a href="http://pan.baidu.com/share/link?shareid=4108323986&uk=959541513" target="_blank" class="btn_gray btn_down" style="float:none;padding:5px;"><span class="ico down"></span>下载AdobeReader</a> </p> </div> <script type="text/javascript">//<![CDATA[ $(document).ready(function(){ window.onload = function (){ var success = new PDFObject({ url: "${ctx}/${save_path}"}).embed(); }; }); //]]></script> </body> </html>
6.编写异步请求的处理Action添加如下方法代码:
public class CsAjaxAction { /** * 附件PDF预览 * * @author Guoyulong * @date 2015年3月17日下午6:13:35 * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward viewPdfByClue(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaBean dynaBean = (DynaBean) form; String id = (String) dynaBean.get("id"); String ctxDir = getServlet().getServletContext().getRealPath( File.separator); if (!ctxDir.endsWith(File.separator)) { ctxDir = ctxDir + File.separator; } if (StringUtils.isBlank(id)) { String msg = "传入参数有误"; super.renderJavaScript(response, "alert('" + msg + "');history.back();"); return null; } ClueAccusation clueAccusation = new ClueAccusation(); clueAccusation.setId(Long.valueOf(id)); clueAccusation = super.getFacade().getClueAccusationService() .getClueAccusation(clueAccusation); if (null != clueAccusation) { String saveDirectory = ctxDir + clueAccusation.getSave_path(); String converfilename = saveDirectory.replaceAll("\\\\", "/"); File file = new File(converfilename); if (!file.exists()) { String msg = "文件不存在,不能在线查看!"; super.renderJavaScript(response, "alert('" + msg + "');window.close();"); return null; } request.setAttribute("save_path", clueAccusation.getSave_path()); request.setAttribute("file_name", clueAccusation.getFile_name()); return new ActionForward("/_public_pdf_view.jsp"); } else { String msg = "文件不存在,不能在线查看!"; super.renderJavaScript(response, "alert('" + msg + "');history.back();"); return null; } } /** * 附件预览Excel * * @author Guoyulong * @date 2015年3月17日下午6:14:31 * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward viewOfficeByClue(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaBean dynaBean = (DynaBean) form; String id = (String) dynaBean.get("id"); String ctxDir = getServlet().getServletContext().getRealPath( File.separator); if (!ctxDir.endsWith(File.separator)) { ctxDir = ctxDir + File.separator; } if (StringUtils.isBlank(id)) { String msg = "传入参数有误"; super.renderJavaScript(response, "alert('" + msg + "');history.back();"); return null; } ClueAccusation clueAccusation = new ClueAccusation(); clueAccusation.setId(Long.valueOf(id)); clueAccusation = super.getFacade().getClueAccusationService() .getClueAccusation(clueAccusation); if (null != clueAccusation) { String saveDirectory = ctxDir + clueAccusation.getSave_path(); String converfilename = saveDirectory.replaceAll("\\\\", "/"); File file = new File(converfilename); if (!file.exists()) { String msg = "文件不存在,不能在线查看!"; super.renderJavaScript(response, "alert('" + msg + "');window.close();"); return null; } DocConverter d = new DocConverter(converfilename); String save_name = clueAccusation.getFile_name(); String _save_name = ""; if (StringUtils.isNotBlank(save_name)) { if (save_name.endsWith(".doc")) { _save_name = save_name.replaceAll(".doc", ""); } else if (save_name.endsWith(".docx")) { _save_name = save_name.replaceAll(".docx", ""); } else if (save_name.endsWith(".xls")) { _save_name = save_name.replaceAll(".xls", ""); } else if (save_name.endsWith(".xlsx")) { _save_name = save_name.replaceAll(".xlsx", ""); } else if (save_name.endsWith(".ppt")) { _save_name = save_name.replaceAll(".ppt", ""); } else if (save_name.endsWith(".pptx")) { _save_name = save_name.replaceAll(".pptx", ""); } } File file2 = new File(ctxDir + "/filesview/upload/" + _save_name + ".html"); if (!file2.exists()) {// 如果没有在进行生成html d.convertoHtml(ctxDir, clueAccusation.getSave_path(), _save_name); } String html = ""; String os_name = System.getProperty("os.name"); if (os_name.toLowerCase().contains("windows")) { html = FileUtils.readFileToString(new File(ctxDir + "/filesview/upload/" + _save_name + ".html"), "GBK"); } else { html = FileUtils .readFileToString(new File(ctxDir + "/filesview/upload/" + _save_name + ".html"), "utf-8"); } if (html.contains("<IMG SRC=\"")) { html = html.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + "filesview/upload/"); } request.setAttribute("file_name", clueAccusation.getFile_name()); request.setAttribute("save_path", clueAccusation.getSave_path()); request.setAttribute("html", html); return new ActionForward("/_public_office_view.jsp"); } else { String msg = "文件不存在,不能在线查看!"; super.renderJavaScript(response, "alert('" + msg + "');history.back();"); return null; } } }
7.调用我们前面的写好的方式预览文件:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functionsx" prefix="fnx"%> <%@ taglib uri="http://struts.apache.org/tags-html-el" prefix="html-el" %> <%@ taglib uri="http://struts.apache.org/tags-logic-el" prefix="logic-el" %> <%@ taglib uri="http://struts.apache.org/tags-bean-el" prefix="bean-el"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>${naviString}</title> <link href="${ctx}/manager/css/global.css" rel="stylesheet" type="text/css" /> <link href="${ctx}/manager/css/methods.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="position"> <h3>测试文件预览</h3> </div> <div class="searchlist"> <html-el:form action="/all/Test.do"> <html-el:hidden property="method" value="save" /> <div class="subtitle02"> 主体信息 </div> <table width="100%" border="0" cellpadding="5" cellspacing="1" class="rtab2"> <tr> <th width="19%">名称:</th> <td>${fn:escapeXml(af.map.title)}</td> </tr> <tr> <th align="right">内容:</th> <td>${fn:escapeXml(af.map.clue_content)}</td> </tr> <tr> <th width="19%">部门:</th> <td colspan="3">${fn:escapeXml(af.map.ys_dept_name)}</td> </tr> <tr> <th width="19%">时间:</th> <td colspan="3"> <fmt:formatDate value="${af.map.ys_date}" pattern="yyyy-MM-dd" /> </td> </tr> <c:if test="${af.map.is_answer eq 1 or af.map.is_answer eq 2}"> <tr> <th align="right">处理内容:</th> <td> ${fn:escapeXml(af.map.answer_content)} </td> </tr> </c:if> <c:if test="${af.map.is_deal eq 'true'}"> <tr> <th align="right"><span style="color: #f00;">*</span>办理内容:</th> <td> <html-el:textarea styleId="answer_content" property="answer_content" rows="12" cols="65"/> </td> </tr> </c:if> <c:if test="${af.map.is_deal eq 'false'}"> <tr> <th align="right"><span style="color: #f00;">*</span>不办理理由:</th> <td> <html-el:textarea styleId="answer_content" property="answer_content" rows="12" cols="65"/> </td> </tr> </c:if> <tr id="trFile"> <th width="15%" class="title_item" nowrap="nowrap">材料附件:</th> <td colspan="2" width="85%"> <c:if test="${not empty af.map.file_name}"> <span> <c:if test="${fn:endsWith(af.map.save_path, '.doc') or fn:endsWith(af.map.save_path, '.docx') or fn:endsWith(af.map.save_path, '.xls') or fn:endsWith(af.map.save_path, '.xlsx')}"> <a href="${ctx}/CsAjax.do?method=viewOfficeByClue&id=${af.map.id}" target="_blank">在线预览</a> </c:if> <c:if test="${fn:endsWith(af.map.save_path, '.pdf')}"> <a href="${ctx}/CsAjax.do?method=viewPdfByClue&id=${af.map.id}" target="_blank">在线预览</a> </c:if> <c:if test="${fn:endsWith(af.map.save_path, '.txt')}"> <a href="${ctx}/${af.map.save_path}" target="_blank">在线预览</a> </c:if> <a href="${ctx}/${af.map.save_path}">${fn:escapeXml(af.map.file_name)}</a><br /> </span> </c:if> </td> </tr> </table> <table width="100%" border="0" align="center" cellpadding="5" cellspacing="1" class="tbl_list"> <tr> <td align="center"> <c:if test="${not empty af.map.is_deal}"> <html-el:button property="button" styleClass="websub" styleId="btn_submit" value="提 交" /></c:if> <input name="button2" type="button" class="websub" id="button2" value="返 回" onclick="history.back();"/></td> </tr> </table> </html-el:form> </div> <script type="text/javascript" src="${ctx}/commons/scripts/jquery.js"></script> <script type="text/javascript" src="${ctx}/commons/scripts/validator.js"></script> <script type="text/javascript" src="${ctx}/commons/scripts/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ var f = document.forms[0]; $("#answer_content").attr("datatype","Require").attr("msg","处理内容必须填写"); // 提交 $("#btn_submit").click(function(){ if(Validator.Validate(f, 1)){ $("#btn_submit").attr("value", "正在提交...").attr("disabled", "true"); $("#btn_reset").attr("disabled", "true"); $("#btn_back").attr("disabled", "true"); f.submit(); } }); }); </script> </body> </html>
表单上传文件以后就可以实现预览了。
PDF预览JAR.rar (2 MB)
下载次数: 1
相关文章推荐
- Linux查看系统硬盘内存及开机信息的命令
- Linux操作系统常用命令
- 如何读取properties文件中属性
- openwrt:ubus
- Apache Mahout 简介
- OpenStack里使用Nova Docker Driver需要注意的细节
- Nginx+tomct 动静分离实现负载均衡
- Photoshop特效设计提高班-张辛-专题视频课程
- 基于Tomcat7、Java、WebSocket的服务器推送聊天室
- OpenAM不能使用IP地址访问
- 一、Linux目录结构
- linux shell数据重定向(输入重定向与输出重定向)详细分析
- linux shell数据重定向(输入重定向与输出重定向)详细分析
- 手把手教你最小化安装CentOS64及共享宿主机文件设置
- Linux学习笔记(二)系统常用命令和一些概念
- Linux学习笔记(一)系统分区及挂载点
- 嵌入式Linux内核制作
- tomcat启动startup后,一闪而过
- mac(osx)配置apache+mysql+php+phpmyadmin
- Tomcat 详解