在web页面预览PDF文件

先说说基本思路:

1、点击某个文件名称的连接时获取到文件序号,即保存在文件表中的主键序号;

2、通过AJAX将序号传入到后台,从文件表中查询文件信息,并使用openOffice将文档转成PDF文件;

3、将文件流输出到web页面。

再说说我本地的环境:

1、文件上传之后会在数据库中插入一条数据,用来记录文件的基本信息,如文件名称、保存路径、文件大小,上传人,上传时间等;

2、openOffice的安装前面的文章已经说得很清楚了,有需要的可以看一下!

3、我这里是点击文件名称时获取文件名称判断是不是doc文档,若是,就转PDF。若是图片或PDF文件就直接预览。否则,提示下载。

4、服务器端必须安装openOffice,客户端必须安装Adobe公司的PDF阅读器。若安装其他的PDF阅读器,如福昕,可能会出现不能预览只能下载的情况。

具体代码如下:

1、鼠标点击时获取文件信息并判断文件类型:

$("table>tbody>tr>td>a.fileDown").live("click",function(){
	var fileid=jQuery.trim($(this).attr("fileId"));//文件序号
	if(fileid!=""){
		//1、判断文件是否为doc文件、pdf文件
		var fileName = $(this).text();//获取文件名称
		var sign = validateDocType(fileName);
		if(sign>0){//说明是可以打开的文件
			//2、在新的选项卡中打开
			buildTab("openDocInPdf.jsp?fid="+fileid+"&sign="+sign,fileName);
 			return false;
		}else{
			//不是word/pdf/图片文档,那么不打开进行提醒
			if(confirm('当前文档不是word、pdf文档,不允许打开!\n是否进行下载?')){
				fileDownload(fileid);
			}
		}
	}
});

/**
 * 该方法通过文档的后缀名判断文件类型
 * @param fileName:含有后缀名的文档
 * @return sign:0-表示不是可以用pdf打开的文档 1-word文档 2-pdf文件 3-图片
 * **/
function validateDocType(fileName){
	if(isempty(fileName)){ return 0;}
	if((/(?:doc|docx)$/i.test(fileName))){
		return 1;
	}else if((/(?:pdf)$/i.test(fileName))){
		return 2;
	}else if((/(?:jpg|gif|png|jpeg|bmp)$/i.test(fileName))){
		return 3;
	}else{
		return 0;
	}
}

2、openDocInPdf.jsp的body中什么内容都不要写,直接加载JS即可。

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
	var fid = '${param.fid}';
	var sign = '${param.sign}';//1-word文档 2-pdf文件 3-图片
	$(function(){
		if(sign=="1" || sign=="2"){
			var src="fileRouter!openDocInPdf.action?id="+fid+"&flag=2&time="+new Date().getTime();
			//alert(document.getElementsByTagName("body").length+"\n"+src);
			$("body").html("<iframe  width='100%' height='100%' src='"+src+"' />");
		}else if(sign=="3"){//说明是图片
			getFileInfoInAjax(fid);
		}
	});
	
	//该方法用来加载图片信息
	function getFileInfoInAjax(fid){
		$.ajax({
			type:"POST",
			async:false,
			data:{"id":fid,"flag":"1","time":new Date().getTime()},
			dataType:"text",
			url:"fileRouter!openDocInPdf.action",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert("加载错误,错误原因:\n"+errorThrown);
			},
			success:function(serverData){
				var data2 = serverData.toString();
				if((data2+"").indexOf("fail")>-1){//说明是错误信息
					data2 = data2.replace("fail","");
				}else{
					//alert("返回的数据:"+serverData);
					var data = $.parseXML(serverData);
					var fileid = $(data).find("fileid").text();//文件序号
					var filename = $(data).find("filename").text();//文件名
					var filepath = $(data).find("filepath").text();//文件路径
					filepath = filepath.replace("D:","");
					$("body").html("<img src='"+filepath+"' width='100%' height='100%'/>");
				}
			}
		});
	}
</script>

3、action处理:

/**
 * 注意:该方法需要安装openOffice并将openOffice设置为开机自启动的服务
 * **/    
/**
 * 该方法用来加载并显示文件
 * @param id:文件序号
 * @param flag:文件类型 1-图片格式 2-office格式
 * */
public String openDocInPdf() throws Exception{
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	String result="";
	try{
		//1、校验是否登录
		Object userInfo = request.getSession().getAttribute("userInfo");
		if(userInfo==null) throw new TspException("用户信息获取失败,userInfo=null");
		
		//2、获取文件序号
		Integer id = Integer.parseInt(request.getParameter("id"));
		Integer flag = Integer.parseInt(request.getParameter("flag"));
		
		//3、获取文件路径
		com.wjl.ExecSQL execSQL = (com.wjl.ExecSQL) com.wjl.SpringApplicationContextHolder.getSpringBean("ExecSQL");//获取ExecSQL的bean
		List<Object[]> fileList = execSQL.selectQuery2("select top 1 ID,[filepath],[filename] from S_FILE where ID="+id+";");
		if(fileList!=null && fileList.size()>0){
			Object[] obj = fileList.get(0);
			String fileid = obj[0].toString();//文件序号
			String filePath = obj[1].toString();//文件路径
			String fileName = obj[2].toString();//文件名称
			logger.debug("请求路径:" + ServletActionContext.getServletContext().getRealPath(""));
			logger.debug("文件编号:" + fileid);
			logger.debug("文件名称:" + fileName);
			logger.debug("文件路径:" + filePath);
			
			//4、校验文件自否存在
			if(!(filePath.indexOf("bfp")>-1)){//说明不在指定的文件存储的物理盘符上,而是存在webRoot下
				filePath = request.getRealPath("/")+filePath;
			}
			
			File loadFile = new File(filePath);
			if(!loadFile.exists()){
				throw new TspException("没有找到您需要的资源:" + fileName+" !");
			}
			
			if(flag==2){//说明是office文件
				//4、校验pdf文件是否存在
				String pdfName = loadFile.getName();//获取文件的名称
				pdfName = pdfName.substring(0,pdfName.lastIndexOf(".")+1)+"pdf";
				String pdfFilePath = loadFile.getParentFile().getAbsolutePath()+File.separator+pdfName;
				File pdfFile = new File(pdfFilePath);
				if(!pdfFile.exists()){//pdf文件不存在,那么需要进行转换,将当前文档转成pdf
					//5、生成pdf文件
			         officeToPdf(loadFile,pdfFile);
				}
				//6、加载pdf文件至页面
				response.setContentType("application/pdf");
				FileInputStream in = new FileInputStream(pdfFile);
				OutputStream out = response.getOutputStream();
				byte[] b = new byte[1024];
				while ((in.read(b)) != -1) {
					out.write(b);
				}
			
				out.flush();
				in.close();
				out.close();
			}else{
				StringBuffer fileStr = new StringBuffer();
				fileStr.append("<file>")
    			.append("<result>successed</result>")
    			.append("<fileid>"+fileid+"</fileid>")
    			.append("<filename>"+fileName+"</filename>")
    			.append("<filepath>"+filePath+"</filepath>" )
    			.append("</file>");
				result = fileStr.toString();
			}
		}
	}catch(TspException e){
		writeLogger("以PDF格式打开文件",e);
		e.printStackTrace();
		result="fail"+e.getMessage();
	}finally{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
		response.getWriter().write(result);
		response.getWriter().flush();
		response.getWriter().close();
	}
	return null;
}

/**
 * 该方法用来转成PDF文件
 * @param inputFile:转变成pdf文件的文件
 * @param outputFile:PDF文件对象
 * */
public void officeToPdf(File inputFile,File outputFile) {   
    // 链接 一个运行在8100端口的OpenOffice.org 实例  
    OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);   
    try {   
        connection.connect();   //进行连接
        // 创建一个converter对象并转换格式
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);   
        converter.convert(inputFile, outputFile);   
    } catch (ConnectException cex) {   
        cex.printStackTrace();   
    } finally {   
        if (connection != null) {   
            connection.disconnect(); //关闭连接  
            connection = null;   
        }   
    }   
}

/**
 * 该方法用来往日志文件中写日志信息
 * @author wjl
 * @date 2016-5-1
 * @param msg:提醒信息
 * @param e:需要写入的错误信息
 * */
public void writeLogger(String msg,Exception e){
	logger.error("---------------------------------------------------------------------\r\n");
	logger.error(msg+"时发生异常:\n");
	logger.error("时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\r\n");//记录时间
	logger.error("错误信息:\r\n");
	logger.error(e, e);
	logger.error("---------------------------------------------------------------------\r\n");
}

猜你喜欢

转载自1017401036.iteye.com/blog/2296850