通过pdf.js实现服务器端pdf文件的预览

一、这里简单介绍通过pdf.js进行预览pdf文件的方法,兼容火狐,谷歌,ie9+,实现方法如下:

1、首先去官网下载pdf.js及相关文件,官网下载路径:http://mozilla.github.io/pdf.js/getting_started/#download 


2、下载之后找到viewer.js文件,打开之后找到下图这段代码:


DEFAULT_URL这个变量本来存的是文件夹里.pdf文件的默认路径,使用的时候需要将里面的值清空,上图改过之后的结果

3、将build和web这两个文件夹的文件复制到项目

4、可以把上面两个文件夹里面多余的文件删掉,主要包括.map文件和默认的.pdf文件,如下图所示圈起来的文件可以不要


二、实现方法为前端代码和后台Java代码结合

1、前端页面代码如下

<html>
  <head>
  	<base href="<%=basePath%>">
        <title>My JSP 'index.jsp' starting page</title>
	<script src="<%=basePath%>plugin/jquery.min1.11.1.js"></script>
	<script type="text/javascript">  
	 	$(function(){
	 		$("#pdfIframe").attr("src","<%=basePath%>plugin/pdfjs/web/viewer.html?file="+ encodeURIComponent("<%=basePath%>/showPdf.do"));
	    });  
	</script>  
  </head>
  <body>
  	<iframe id="pdfIframe" width="100%" height="100%"></iframe>  
  </body>
</html>

viewer.html即为项目引用pdf.js文件夹中viewer.html的路径

2、后台代码如下:

@Controller
public class ShowPdfController  {
    @RequestMapping({ "/showPdf.do" })
    public String showPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            // 网络pdf文件全路径
            String pdfUrl ="https://hljjp.oss-cn-hangzhou.aliyuncs.com/epdfimg/stu_grade_2017121450829122_185125_20171214142015.pdf";
            URL url = new URL(pdfUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5*1000);
            InputStream inputStream = conn.getInputStream();
            response.setHeader("Content-Disposition", "attachment;fileName=结业.pdf");
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(inputStream), outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

代码写好之后可以通过调用页面js进行实现

三、实现效果如下图:上边的按钮可以进行下载和打印



猜你喜欢

转载自blog.csdn.net/tao111369/article/details/79714154