记录一下,实现各种文档在线预览的功能

本文介绍了一种在线预览文档的方法,包括将各种格式的文档(如Word、Excel和PowerPoint)转换为PDF,以便在网页上进行预览。讨论了文件路径处理、中文参数解码和异常处理等问题。

首先是通过方法把对应的文档编译成为对应的pdf文件,然后再浏览器打开对应的pdf文件。从而实现预览效果;

但要注意的是,预览打开的url存在中文问题,我这边始终存在因为转义,而提示无法找到对应的pdf文件的问题。最后是再文档编译的时候使用文档再数据库对应的ID作为pdf名称编译出来,然后打开。

一下是后台对应的代码;

这里提供两张编译方式,我所使用的是编译成pdf文件。另一种是编译成html文件。

要注意的是,需要再WEB-INF下面加上classes包,内容在附件中(这些内容必不可少;是代码在编译时用到的配置文件);

 

package ths.project.EnterService.util.attachments.web;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.aspectj.weaver.patterns.HasMemberTypePattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.JsonArray;
import com.sun.org.apache.bcel.internal.generic.NEW;

import ths.jdp.core.dao.base.Paging;
import ths.jdp.core.model.FormModel;
import ths.jdp.project.web.LoginCache;
import ths.project.EnterService.user.service.UserAccountRelationService;
import ths.project.EnterService.util.attachments.service.AttachmentsService;
import ths.project.EnterService.util.toPdf.Excel2Pdf;
import ths.project.EnterService.util.toPdf.PowerPoint2Pdf;
import ths.project.EnterService.util.toPdf.WordToPdf;

/**
 * 附件在线预览
 * 
 * @author xwy
 * @since 2019-3-8
 */
@Controller
@RequestMapping("/attachments")
public class AttachmentsController {

	@Autowired
	private AttachmentsService attachmentsService;
	

	/**
	 * 在线预览 查询表单对应的附件信息
	 * @param fileName
	 * forcePreview 强制转换
	 */
	@RequestMapping("/file")
	public ModelAndView file(@RequestParam String ext,String business_key,Paging<Map<String, Object>> pageInfo, HttpServletRequest request){
		ModelAndView result = new ModelAndView("attachments/file");
		Map<String,Object> map=new HashMap<String,Object>();
		Paging<Map<String, Object>> dateMap = new Paging<Map<String, Object>>();
		map.put("BUSINESS_KEY", business_key);
		map.put("EXT", ext);
		dateMap=attachmentsService.getBusinesskey(pageInfo,map);
		result.addObject("pageInfo",dateMap);
        return result;
	}
	
	/**
	 * 在线预览
	 * @param fileName
	 * forcePreview 强制转
	 */
	@RequestMapping("/previewToPdf")
	public ModelAndView previewToPdf(@RequestParam String fileid,String forcePreview,HttpServletRequest request){
		ModelAndView result = new ModelAndView("attachments/showPdf");
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("FILE_ID", fileid);
		map=attachmentsService.getFileid(map);
		String path=(String)map.get("FILE_NAME");
		String name=(String)map.get("FILE_PATH");
//		
		String filePath=request.getRealPath("attachments")+"\\"+path;//获取文件绝对路径
		File f = new File(request.getRealPath("attachments")+"\\"+fileid+".pdf");//判断文件是否已经生成
        boolean hasToPDF = f.exists();
//        result.addObject("path",ajaxToChinse(path.substring(0,path.lastIndexOf("."))+".pdf"));//展示路径 name+"\\"+
        result.addObject("fileid",fileid);
		if("force".equals(forcePreview)||!hasToPDF){//查看是否已经存在编译好的;如果是强制转换 则转换,或者没有转换*/
			 try{
			    ToPdf( filePath,filePath,request.getRealPath("attachments")+"\\"+fileid+".pdf");
//这里进行编译对应的文档
			}catch(Exception e){
				result.addObject("path","");//清空路径
				result.addObject("error", "异常:"+e.getMessage());
			} 
		}
			result.addObject("path",fileid+".pdf");
        return result;
	}
	/**
	 * 文件转换 方便实现在线预览
	 * @param filePath
	 * @param path
	 */
	public void ToPdf(String filePath,String path,String paths) throws Exception{
		System.out.println("开始文件类型转换,文件原始路径:"+filePath);
		String fileExt = path.substring(path.lastIndexOf(".") + 1).toLowerCase();//文件后缀
		if("doc".equals(fileExt) || "docx".equals(fileExt)){
			WordToPdf.wordToOther(filePath,"pdf",paths);
		} else if("xls".equals(fileExt) || "xlsx".equals(fileExt)){
			Excel2Pdf.convertFile(filePath, "pdf");
		} else if("ppt".equals(fileExt) || "pptx".equals(fileExt)){
			PowerPoint2Pdf.convertFile(filePath, "pdf");
		}else{
			throw new Exception("不支持在线预览");
		}
	}
	
	//ajax 中文传参之后解码
			public String ajaxToChinse(String code){
				String val1 = null;
		    	String val2 = null;
				if(code!=null && !("").equals(code)){
					try {
						val1= URLDecoder.decode(code, "UTF-8");
						val2= URLDecoder.decode(val1, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				return val2;
			}
}

  

 

转载于:https://www.cnblogs.com/xwy-bk/p/10501616.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值