java實現在線預覽功能,需要用到 jacob.dll jacob.jar 預覽pdf所需js pdfobject.min.js
將上傳文件轉為pdf保存。
<div class="control-group"> <label class="control-label">文件:</label> <div class="controls"> <input type="file" name="file" id="ck_attach_path" style="width:98%;"/> </div> </div>
后台保存文件並將文件轉換為pdf
@RequiresPermissions("ha01:haHyjhb:edit") @RequestMapping(value = "save") public String save(HaHyjhb haHyjhb, @RequestParam MultipartFile file,Model model, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException { haHyjhb.setBh(hybh); String xdlj = request.getSession().getServletContext().getRealPath("userfiles")+"\\hy"+haHyjhb.getLx()+"\\"+dateStr+"\\"+hybh+"\\"; String path = ""; if(!file.isEmpty()){ HaHyzlb haHyzlb = new HaHyzlb(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設置日期格式 String filename= df.format(new Date()); // 保存在服務器的隨機文件名 //材料編號 haHyzlb.setClhb(filename); haHyzlb.setHybh(hybh); xdlj=xdlj.replaceAll("\\\\", "/"); haHyzlb.setLj(xdlj); haHyzlb.setCllx("0"); String aa[]=file.getOriginalFilename().split("[.]"); String fileName =filename+"."+aa[aa.length-1]; haHyzlb.setClywjm(file.getOriginalFilename()); haHyzlb.setClmc(fileName); //保存文件 publicUtils.saveFile(file, xdlj,filename, request, response); haHyzlbService.save(haHyzlb); }else{ request.setAttribute("msg", "未選擇需上傳的文件"); } haHyjhbService.save(haHyjhb); addMessage(redirectAttributes, "保存會議計划成功"); } return "redirect:"+Global.getAdminPath()+"/ha01/haHyjhb/?repage"; }
public static void saveFile(@RequestParam MultipartFile file,String xdlj,String filename, HttpServletRequest request, HttpServletResponse response) { String path = ""; String pdfname= filename + ".pdf"; // 裝換成pdf文件的名稱 String refilename= ""; // 上傳文件的名稱 if(!file.isEmpty()){ //獲取上傳文件的原名稱 refilename=file.getOriginalFilename(); String aa[]=refilename.split("[.]"); filename=filename+"."+aa[aa.length-1]; xdlj=xdlj.replaceAll("\\\\", "/"); File fpath = new File(xdlj); if(!fpath.exists()){ fpath.mkdirs(); } try { MultipartFile mfile = file; if(mfile!=null){ File localFile = new File(xdlj+filename); path = localFile.getPath(); try { mfile.transferTo(localFile);//將上傳文件寫到服務器上指定的文件 ToPDF top=new ToPDF(); top.convert2PDF(xdlj+filename, xdlj+pdfname); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("msg", refilename+"上傳失敗"); } } else{ request.setAttribute("msg", "未選擇需上傳的文件"); } }
轉換pdf工具類
package com.thinkgem.jeesite.modules.bc.bc01.web; import java.io.File; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComFailException; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; public class ToPDF { private static final int wdFormatPDF = 17; private static final int xlTypePDF = 0; private static final int ppSaveAsPDF = 32; private static final int msoTrue = -1; private static final int msofalse = 0; /*jacob配置 * 把jacob.dll放入 Java\jdk1.5.0_06\jre\bin目錄下. 把jacob.jar放入 Java\jdk1.5.0_0\jre\lib\ext*/ //直接調用這個方法即可 public boolean convert2PDF(String inputFile, String pdfFile) { String suffix = getFileSufix(inputFile); File file = new File(inputFile); if(!file.exists()){ System.out.println("文件不存在!"); return false; } if(suffix.equals("pdf")){ System.out.println("PDF not need to convert!"); return false; } if(suffix.equals("doc")||suffix.equals("docx")||suffix.equals("txt")){ return word2PDF(inputFile,pdfFile); }else if(suffix.equals("ppt")||suffix.equals("pptx")){ return ppt2PDF(inputFile,pdfFile); }else if(suffix.equals("xls")||suffix.equals("xlsx")){ return excel2PDF(inputFile,pdfFile); }else{ System.out.println("文件格式不支持轉換!"); return false; } } public static String getFileSufix(String fileName){ int splitIndex = fileName.lastIndexOf("."); return fileName.substring(splitIndex + 1); } public boolean word2PDF(String inputFile,String pdfFile){ ActiveXComponent app = null; Dispatch doc = null; boolean result=true; try{ //打開word應用程序 app = new ActiveXComponent("Word.Application"); //設置word不可見 app.setProperty("Visible", false); //獲得word中所有打開的文檔,返回Documents對象 Dispatch docs = app.getProperty("Documents").toDispatch(); //調用Documents對象中Open方法打開文檔,並返回打開的文檔對象Document doc = Dispatch.call(docs, "Open", inputFile, false, true ).toDispatch(); Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF //word保存為pdf格式宏,值為17 ); result= true; }catch(Exception e){ result= false; }finally { if (doc != null) { Dispatch.call(doc, "Close"); } if (app != null) { app.invoke("Quit"); } } return result; } public boolean excel2PDF(String inputFile,String pdfFile){ ActiveXComponent app = null; Dispatch excel = null; boolean result=true; try{ app = new ActiveXComponent("Excel.Application"); app.setProperty("Visible", false); Dispatch excels = app.getProperty("Workbooks").toDispatch(); excel = Dispatch.call(excels, "Open", inputFile, false, true ).toDispatch(); Dispatch.call(excel, "ExportAsFixedFormat", xlTypePDF, pdfFile ); result= true; }catch(Exception e){ result= false; }finally { if (excel != null) { Dispatch.call(excel, "Close"); } if (app != null) { app.invoke("Quit"); } } return result; } public boolean ppt2PDF(String srcFilePath, String pdfFilePath){ ActiveXComponent app = null; Dispatch ppt = null; boolean result=true; try { ComThread.InitSTA(); app = new ActiveXComponent("PowerPoint.Application"); Dispatch ppts = app.getProperty("Presentations").toDispatch(); // 因POWER.EXE的發布規則為同步,所以設置為同步發布 ppt = Dispatch.call(ppts, "Open", srcFilePath, true,// ReadOnly true,// Untitled指定文件是否有標題 false// WithWindow指定文件是否可見 ).toDispatch(); Dispatch.call(ppt, "SaveAs", pdfFilePath, 32); //ppSaveAsPDF為特定值32 result=true; // set flag true; } catch (ComFailException e) { result=false; } catch (Exception e) { result=false; } finally { if (ppt != null) { Dispatch.call(ppt, "Close"); } if (app != null) { app.invoke("Quit"); } ComThread.Release(); } return result; } }
預覽文件
<c:if test="${haHyjhb.cllist ne null and haHyjhb.cllist.size() ne 0}"> </br ><h4>會議文件列表</h4></br > <table id="contentTable" class="table table-striped table-bordered table-condensed"> <thead> <tr> <th>文件名</th> <th>預覽</th> </tr> </thead> <tbody> <c:forEach items="${haHyjhb.cllist}" var="haHyjhb"> <tr> <td>${haHyjhb.clywjm }</td> <td><a href="javascript:void(0);" onclick="filescan('${haHyjhb.id}')">預覽</a></td> </tr> </c:forEach> </tbody> </table> </c:if>
function filescan(fileid){ top.$.jBox.open("iframe:${ctx}/ha01/haHyjhb/scan?id="+fileid, "文件預覽",800,$(top.document).height()-100,{ buttons:{"確定":"ok", "關閉":true}, submit:function(v, h, f){ }, loaded:function(h){ $(".jbox-content", top.document).css("overflow-y","hidden"); }, closed:function (){ } }); }
<%@ page contentType="text/html;charset=UTF-8" %> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head> <title>資料信息管理</title> <style type="text/css"> html,body,#content{ width: 100%; height: 100%; margin: 0; padding: 0; } </style> <script type="text/javascript"> window.onload = function (){ //項目名稱 var filepath="${pageContext.request.contextPath}/"+"${saMyclbClxx.lj}".split("/dxzjzx_wz/")[1]; var name="${saMyclbClxx.clmc}"; var a=name.split("."); var hzm=a[a.length-1];//后綴名 var wjm=name.split("."+hzm)[0];//文件名 if(hzm=="txt"||hzm=="doc"||hzm=="docx"||hzm=="xls"||hzm=="xlsx"||hzm=="ppt"||hzm=="pptx"||hzm=="pdf"){ filepath = filepath+wjm+".pdf"; PDFObject.embed(filepath, "#content" ); //var success = new PDFObject({ url:filepath ,pdfOpenParams: { scrollbars: '0', toolbar: '0', statusbar: '0'}}).embed("content1"); }else if(hzm=="png"||hzm=="jpeg"||hzm=="gif"||hzm=="jpg"){ $("#content").html("<img style='background-size:contain|cover;width:100%;height: auto;' src='"+filepath+name+"' id='ylimg'/>"); }else if(hzm=="wav"||hzm=="mp3"||hzm=="midi"||hzm=="wma"||hzm=="swf"||hzm=="flv"||hzm=="wmv"||hzm=="asf"||hzm=="asx"||hzm=="mid"||hzm=="rm"||hzm=="rmvb"||hzm=="mp4"||hzm=="mov"||hzm=="avi"||hzm=="ram"){ $("#content").html("<video src='"+filepath+name+"' controls='controls'></video>"); }else{ alert("該文件格式不支持預覽"); } } </script> </head> <body> <ul class="nav nav-tabs"> </ul><br/> <form:form id="inputForm" modelAttribute="saSqmyxxb" action="${ctx}/sa01/saSqmyxxb/save" method="post" class="form-horizontal"> <sys:message content="${message}"/> <div id="content"></div> </form:form> <script type="text/javascript" src='${ctxStatic}/js/pdfobject.min.js'></script> </body> </html>