天天看點

JAVAWEB實作線上預覽PDF

一、場景再現

 由于項目上傳pdf檔案後要實作線上預覽(點選PDF)

JAVAWEB實作線上預覽PDF

二、實作方法

 HTML:(傳檔案路徑)

<a  οnclick="openFile('${WDLJTEMP}','${WDBHTEMP}',this);return false;" href="JavaScript:void(0);return false;" target="_blank" rel="external nofollow"  wjhz="${fn:toLowerCase(wdBean.get('WDHZ'))}"
           

JS:

function openFile(filePath,wdbh,obj){
    var hzm = filePath.substring(filePath.lastIndexOf('.')+1);
if('pdf'===hzm){
    var url= ctx + '/upload/preview.do?method=pdfPreviw&filePath='+filePath;
    var name="blankPrint";                           //網頁名稱,可為空;
    var iWidth=window.screen.availWidth/2;                          //彈出視窗的寬度;
    var iHeight=window.screen.availHeight/2;                        //彈出視窗的高度;
    var iTop = (window.screen.availHeight-30-iHeight)/2;       //獲得視窗的垂直位置;
    var iLeft = (window.screen.availWidth-10-iWidth)/2;           //獲得視窗的水準位置;
    window.open(url,name,'resizable=yes,height='+iHeight+',innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft);
	}
}
           

JAVA:

@SuppressWarnings("unused")
	public void pdfPreviw(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String filePath=request.getParameter("filePath");
		String str= new String(filePath.getBytes("ISO8859-1"), "UTF-8"); 
		String path=request.getSession().getServletContext().getRealPath(str);
		response.setContentType("application/pdf;charset=UTF-8");
		response.setHeader("Content-Disposition",
				"inline; filename=print.pdf");
		OutputStream out = null;
		
		try {
			out =response.getOutputStream();
			InputStream in = new FileInputStream(path);
			int len=0;
			byte [] buffer = new byte[1024];
			while((len=in.read(buffer))>0)
				out.write(buffer, 0, len);
				out.flush();
				in.close();
				out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}