Java項目開發PDF在線瀏覽/預覽功能完整流程和代碼(基於pdf.js實戰demo)

前言
項目中使用到了PDF在線瀏覽功能,故記錄下來,供大家參考。

開發步驟:
1、下載pdf.js插件包
到官網下載 pdf.js 插件並解壓 (地址: http://mozilla.github.io/pdf.js/ )

 

點下載

 

下載後得到一個壓縮包,解壓

將解壓後的文件名稱修改爲 pdfJs (也可直接用上面的名稱 pdfjs-2.0.943-dist)

2、項目中PDF功能開發
1)將pdfJs文件夾放到項目js路徑中,比如我的放在 WebContent/scripts/pdfJs

2)添加頁面觸發在線瀏覽PDF按鈕事件,點擊查看按鈕,會打開一個在線PDF的預覽頁面

 

在線瀏覽效果:

 

3)點擊瀏覽之後,新打開一個PDF在線瀏覽窗口:
js代碼:

function viewPdfDocument(pdfname,userEmail){debugger;

     if(userEmail!=""&&userEmail!=undefined&&userEmail!=null&&userEmail!=" "){
    	
    	 window.open(basePath+"/scripts/pdfJs/web/viewer.html?file="
    			 +encodeURIComponent(basePath+"/quick/pdfStreamHandeler.do?fileName="+ pdfname +".pdf"));
     }else{
    	 //layer.msg("請先登錄");
    	 // 判斷是否登錄
         // 沒有登錄則打開登錄彈窗
    	 //$("#login-layer").find("input[type='hidden']").val(callbackUrl);
    	 console.log("callbackUrl=="+callbackUrl);
    	 $("#login-layer #callbackUrlPath").val(callbackUrl);
    	 $("#login-layer #callbackUrlPath2").val(callbackUrl);
         layer.open({
           type: 1,
           title: '登錄',
           area: ['350px', '380px'],
           skin: 'layui-gray',
           shadeClose: true,
           content: $('#login-layer'),
           success: function (layero, index) { 
        	   $().layer_drag();
           }
         });
     }
}

前端的核心代碼就這一行:

window.open(basePath+"/scripts/pdfJs/web/viewer.html?file="
    			 +encodeURIComponent(basePath+"/quick/pdfStreamHandeler.do?fileName="+ pdfname +".pdf"));

window.open(url):打開一個新的窗口
其中,

  • "/scripts/pdfJs/web/viewer.html?file="是默認固定訪問路徑,viewer.html頁面pdf.js插件自帶默認訪問的頁面,後面接一個參數file表示文件路徑文件流
  • "/quick/pdfStreamHandeler.do?fileName="+ pdfname +".pdf",請求到Java後端獲取PDF文件流。
  • encodeURIComponent:是對請求路徑進行編碼,反正Java後端不能識別特殊字符,因爲pdfname可能存在中文空格、括號之類的

這樣代碼就能在線瀏覽後端提供給這個頁面的PDF文件流。

注:如果PDF文件是這直接放在項目代碼裏的,比如放在resources目錄下的話,就可以直接提供pdf的文件文件項目路徑給這個file參數即可。如果是放在D盤之類的文件路徑或是通過調用接口獲得PDF的,是不能這放在file參數後面的,要讀取爲文件流然後傳給file參數。

 

encodeURIComponent(basePath+"/quick/pdfStreamHandeler.do?fileName="+ pdfname +".pdf"),請求到Java後端controller獲取PDF文件流。


4)Java後端PDF文件流獲取.
後端Java全部核心代碼就這個方法,獲取到PDF的流即可:

/**
	 * 預覽pdf文件,獲取PDF需要瀏覽的PDF文件流
	 * @author chunlynn
	 * @param request
	 * @param response
	 * @param fileName
	 */
	@RequestMapping(value = "/pdfStreamHandeler", method = RequestMethod.GET)
	public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response, String fileName) {

		String urlPath = "";
		response.reset();
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			logger.debug("==================pdf處理開始==================");
			//寫入操作日誌start-------------------
			User user = (User) request.getSession().getAttribute("LOGON_USER");
			ProductOperLog log = new ProductOperLog();
			log.setUserId(user.getId());
			log.setFileName(fileName);
			logger.debug("==================操作日誌記錄start==================");
			switch (fileName) {
			case "zlyjjb.pdf": {
				urlPath = dataCenterURIPdf + pdfurl_zlyjjb + URLEncoder.encode(pdfurl_zlyjjb_name, "UTF-8") + ".pdf?"
						+ "access_token=" + TokenSingleton.getInstance().getAccessToken();
				logger.debug("==================pdf處理拼接路徑1,urlPath==" + urlPath);
				log.setOperIndex((short) 0);
				break;
			}
			case "zzjgzlfxbg.pdf": {
				urlPath = dataCenterURIPdf + pdfurl_zzjgzlfxbg + URLEncoder.encode(pdfurl_zzjgzlfxbg_name, "UTF-8")
						+ ".pdf?" + "access_token=" + TokenSingleton.getInstance().getAccessToken();
				logger.debug("==================pdf處理拼接路徑2,urlPath==" + urlPath);
				log.setOperIndex((short) 1);
				break;
			}
			}
			log.setOperType((short) 0);
			productOperLogManageService.saveProductLog(log);
			//寫入操作日誌 end--------------------

			System.out.println("請求PDF路徑:" + urlPath);
			os = response.getOutputStream();
              //獲得PDF文件流,核心代碼
			InputStream is = HttpUtil.getInputStream(urlPath);
			System.out.println("獲取流結束。。。。");
			bis = new BufferedInputStream(is);
			int i = 0;
			while ((i = bis.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}

		} catch (Exception e) {
			logger.error("pdf處理出現異常:" + e.getMessage() + "; ");
			
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

核心代碼:

@RequestMapping(value = "/pdfStreamHandeler", method = RequestMethod.GET)
	public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response, String fileName) {

		String urlPath = "";
		response.reset();
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			logger.debug("==================pdf處理開始==================");
			urlPath = dataCenterURIPdf + pdfurl_zlyjjb + URLEncoder.encode(pdfurl_zlyjjb_name, "UTF-8") + ".pdf?"
						+ "access_token=" + TokenSingleton.getInstance().getAccessToken();
			logger.debug("==================pdf處理拼接路徑1,urlPath==" + urlPath);
	

			System.out.println("請求PDF路徑:" + urlPath);
			os = response.getOutputStream();
            //獲得PDF文件流
			InputStream is = HttpUtil.getInputStream(urlPath);
			System.out.println("獲取流結束。。。。");
			bis = new BufferedInputStream(is);
			int i = 0;
			while ((i = bis.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}

		} catch (Exception e) {
			logger.error("pdf處理出現異常:" + e.getMessage() + "; ");
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

後端Java的controller獲取到PDF文件流後,寫回到Response裏去了,頁面上就能響應PDF流,然後預覽PDF了。
瀏覽效果:

 

整個前後端代碼過程介紹完成。

如果對你有幫助,可以打賞一下哈,謝謝,左側欄目“關於我”有微信讚賞二維碼。讚賞時可以留言留下QQ或微信加好友(可以提供在線指導)。

 

本文爲博主chunlynn原創,轉載請註明出處https://blog.csdn.net/chenchunlin526/article/details/83269416

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章