在线pdf文档在线预览

时间:2021-09-09
本文章向大家介绍在线pdf文档在线预览,主要包括在线pdf文档在线预览使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

后台

 1  @RequestMapping("getPdfStreamFromRootPath")
 2     public void getPdfStreamFromRootPath(HttpServletRequest request,HttpServletResponse response) throws IOException{
 3         //附件路径
 4         //String configPath = configproperties.getProperty("file.upload");
 5         String configPath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
 6         String filePath = RequestUtil.getString(request, "filePath");
 7         // 判断文件是否存在
 8         File file = new File(configPath + File.separator + filePath);
 9         if (!file.exists()) {
10             writeResultMessage(response.getWriter(), new ResultMessage(ResultMessage.Fail, "文件不存在!"));
11             return;
12         }
13         response.setContentType("application/pdf;charset=UTF-8");
14         BufferedInputStream in = null;
15         OutputStream out = null;
16         try {
17             in = new BufferedInputStream(new FileInputStream(file));
18             out = response.getOutputStream();
19             byte[] b = new byte[10*1024];        //10k
20             int i;
21             while ((i = in.read(b)) != -1) {
22                 out.write(b, 0, i);
23             }
24             out.flush();
25         } catch (FileNotFoundException e) {
26             e.printStackTrace();
27         } catch (IOException e) {
28             e.printStackTrace();
29         } finally {
30             try {
31                 if (in != null) {
32                     in.close();
33                 }
34                 if (out != null) {
35                     out.close();
36                 }
37             } catch (IOException e) {
38                 e.printStackTrace();
39             }
40         }
41     }
42 }

前端js

 1 function fileViewOnline(filePath){
 3     $("#fileOnlineView").show();
 4     $('#fileOnlineView').dialog({
 5         title: "在线预览",
 6         width: 1100,
 7         height: 800,
 8         left: 150,
 9         closed: false,
10         cache: false,
11         modal: true
12     });
13     var url =__ctx + '/js/pdfView/web/viewer.html?file='+encodeURIComponent(__ctx+'/Util/FileDownUploadController/getPdfStreamFromRootPath.ht?filePath='+filePath);
14     $("#pdf_page").attr("src",url);
15 }

html

1 <div id="fileOnlineView" style="height:700px;">
2     <iframe id ="pdf_page" name ="pdf_page" style="width:99.5%;height:99%;">
3     </iframe>
4 </div>

原文地址:https://www.cnblogs.com/yy-hang/p/15246320.html