使用pdf.js實現前端頁面預覽pdf文檔,解決了跨域請求

pdf.js主要包含兩個庫文件,一個pdf.js和一個pdf.worker.js,,一個負責API解析,一個負責核心解析javascript

官網地址:http://mozilla.github.io/pdf.js/css

  • 下載pdf.js插件

 

  • 解壓後有 web 和 build 兩個文件夾 如圖 

   

 

  • 運行示例  將解壓後的文件直接仍到項目路徑下

         

 

 

   訪問 ip:port/文件夾名稱/web/viewer.html 
  顯示的是 web 文件夾下的compressed.tracemonkey-pldi-09.pdf html

  

 

 

  •       修改默認打開PDF 

  

咱們只用修改viewer.js文件中的pdf路徑參數便可:
var DEFAULT_URL = ‘09.pdf’;
若是pdf文件與viewer.html不在一層目錄中,改爲相對路徑便可:
var DEFAULT_URL = ’ ../doc/ 09.pdf’;java

viewer.html能夠經過頁面參數傳值的方式加載pdf文件,好比咱們想打開09.pdf文件的話,只須要這樣:
先把viewer.js中的參數修改成空:
var DEFAULT_URL = 」;
而後把url改寫爲參數傳值:
http://127.0.0.1:8080/pdfjs/web/viewer.html?file=09.pdf
若是pdf文件與viewer.html不在一層目錄中,改爲相對路徑便可:
http://127.0.0.1:8080/pdfjs/web/viewer.html?file=../doc/09.pdf
參考地址https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#file

jquery

  • 獲取服務器上的PDF文件 

  

經過頁面參數傳值的方式加載pdf文件
file的值須要URLEncode編碼 指向服務器端
例如:
http://xxxxx.com:89/demo/fileupdownfud=1&rid=4&isweb=1&iswebshow=1&dbid=01&filepath=fj_ob_item/Y201809/11.pdf
URLEncode編碼:爲
http%3A%2F%2Fxxxx.com%3A89%2Fdemo%2Ffileupdown%3Ffud%3D1%26rid%3D4%26isweb%3D1%26iswebshow%3D1%26dbid%3D01%26filepath%3Dfj_ob_item%2FY201809%2F11.pdf
訪問地址爲:
http://127.0.0.1:8080/pdfjs/web/viewer.html?file=http%3A%2F%2Fxxxx.com%3A89%2Fdemo%2Ffileupdown%3Ffud%3D1%26rid%3D4%26isweb%3D1%26iswebshow%3D1%26dbid%3D01%26filepath%3Dfj_ob_item%2FY201809%2F11.pdf
————————————————
版權聲明:本文爲CSDN博主「三年二班Pit」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/l_ai_yi/article/details/82388497git

PDF.js默認好像是不能跨域請求 github

 

 

 

 

 將viewer.js 中的錯誤提示註釋掉便可web

try {
var viewerOrigin = new URL(window.location.href).origin || 'null';
if (HOSTED_VIEWER_ORIGINS.indexOf(viewerOrigin) >= 0) {
return;
}
var fileOrigin = new URL(file, window.location.href).origin;
//跨域請求錯誤提示
//if (fileOrigin !== viewerOrigin) {
//throw new Error('file origin does not match viewer\'s');
//}
} catch (ex) {
var message = ex && ex.message;
PDFViewerApplication.l10n.get('loading_error', null, 'An error occurred while loading the PDF.').then(function (loadingErrorMessage) {
PDFViewerApplication.error(loadingErrorMessage, { message: message });
});
throw ex;
}

跨域

 

  • 服務端代碼
//跨域請求
String s0 = "C:11.pdf" response.setHeader("Access-Control-Allow-Origin", "*"); File file = new File(s0); response.setContentLength((int) file.length()); response.setHeader( "Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));// 設置在下載框默認顯示的文件名
response.setContentType("application/octet-stream");// 指明response的返回對象是文件流 // 讀出文件到response // 這裏是先須要把要把文件內容先讀到緩衝區 // 再把緩衝區的內容寫到response的輸出流供用戶下載
FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); OutputStream outputStream = response.getOutputStream(); byte buffer[] = new byte[1024]; int len = 0; while ((len = bufferedInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } // 人走帶門
bufferedInputStream.close(); outputStream.flush(); outputStream.close();

案例二:服務器

@{ Layout = null; } <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>testPdf</title>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/pdfjs2/build/pdf.js"></script>
    <style type="text/css"> .lightbox { position: fixed; top: 0px; left: 0px; height: 100%; width: 100%; z-index: 7; opacity: 0.3; display: block; background-color: rgb(0, 0, 0); display: none;
        } .pop, iframe { position: absolute; left: 50%; top: 0; width: 893px; height: 100%; margin-left: -446.5px; z-index: 9;
        }
    </style>

    <script type="text/javascript">
        function showPdf(isShow) { var state = ""; if (isShow) { state = "block"; } else { state = "none"; } var pop = document.getElementById("pop"); pop.style.display = state; var lightbox = document.getElementById("lightbox"); lightbox.style.display = state; } function close() { showPdf(false); } function pd(dd) { $("#" + dd)[0].contentWindow.print(); } </script>
</head>
<body>
    <ul>
        <li><a href="../pdfjs2/web/viewer.html?file=../DownFile/430000447746159F19030038催繳通知書.pdf" target="pdfContainer" onclick="showPdf(true)">0001_pdf</a></li>
        <li><a href="../pdfjs2/web/viewer.html?name=../DownFile/430000447746159F19030038事前告知書.pdf" target="pdfContainer" onclick="showPdf(true)">0002_pdf</a></li>
    </ul>
    <div class="lightbox" id="lightbox"></div>
    <div id="pop" class="pop" style="display: none;">
        <a href="javascript:close()" style=" position: absolute; right: -90px; display: inline-block; width: 80px; height: 30px; " id="close">關閉</a> @*<a href="#" onclick="pd('pdfContainer')" style=" position:absolute; right :-90px; display :inline-block; width :80px; height: 30px;">打印</a>*@ <iframe src="" frameborder="0" id="pdfContainer" name="pdfContainer"></iframe>

    </div>
</body>
</html>

案例三:

直接使用iframe

 <iframe id="pdf_page_1" name="pdf_page"  style="width:795px;height:789px" frameborder="0" ></iframe>

賦值顯示:

param = "chId=" + $("#chId").val() + "&unitId=" + unId; pdfurl = "/OverrunPunishment/ApprovedBookData?" + param; //pdfurl爲文件流,使用encodeURIComponent()函數可把字符串做爲 URI 組件進行編碼。
    $("#pdf_page_1").attr('src', "../pdfjs/web/viewer.html?file=" + encodeURIComponent(pdfurl) + "");

後臺將pdf文檔轉文件流方法:

public string ApprovedBookData(string chId, string unitId) { InstrumentInfo instr = new InstrumentInfo(); string name = ""; FileStream fs = null; if (Request.Cookies["LoginValue"] == null) Response.Redirect("../Login/LoginPage"); try { instr = ApprovedDataUtil.ExportPdfText(chId, unitId); string path = instr.fileName.Replace("\\", "/"); fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//讀取生成的pdf文件
                byte[] buffer = new byte[fs.Length]; fs.Position = 0; fs.Read(buffer, 0, (int)fs.Length); Response.Clear(); Response.AddHeader("Content-Length", fs.Length.ToString()); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "inline;FileName=抄告文書.pdf"); Response.BinaryWrite(buffer); Response.OutputStream.Flush(); Response.OutputStream.Close(); name = fs.Name; fs.Close(); } catch (Exception ex) { CSysCfg.WriteLog("獲取文書異常:" + ex.Message); } return name; }

 注:獲取流時,須要用encodeURIComponent將url轉換成encode編碼,放在file裏。

相關文章
相關標籤/搜索