通過pdf.js實現伺服器端pdf檔案的預覽
阿新 • • 發佈:2018-12-27
一、這裡簡單介紹通過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進行實現
三、實現效果如下圖:上邊的按鈕可以進行下載和列印