使用pdf.js实现前端页面预览pdf文档,解决了跨域请求
pdf.js主要包含两个库文件,一个pdf.js和一个pdf.worker.js,,一个负责API解析,一个负责核心解析
官网地址:http://mozilla.github.io/pdf.js/
下载pdf.js插件
解压后有 web 和 build 两个文件夹 如图
运行示例 将解压后的文件直接仍到项目路径下
访问 ip:port/文件夹名称/web/viewer.html
显示的是 web 文件夹下的compressed.tracemonkey-pldi-09.pdf
修改默认打开PDF
我们只用修改viewer.js文件中的pdf路径参数即可:
var DEFAULT_URL = ‘09.pdf’;
如果pdf文件与viewer.html不在一层目录中,改成相对路径即可:
var DEFAULT_URL = ’ ../doc/ 09.pdf’;
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
获取服务器上的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
原文链接:https://blog.csdn.net/l_ai_yi/article/details/82388497
PDF.js默认好像是不能跨域请求
将viewer.js 中的错误提示注释掉即可
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里。