Java实现在线预览功能

java

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>

 

以上是 Java实现在线预览功能 的全部内容, 来源链接: utcz.com/z/391198.html

回到顶部