项目需求是要在页面中直接浏览pdf文件javascript
1.网上比较广泛的方法是pdfobject.js和pdf.jshtml
2.pdfobject.js使用比较简单,但ie兼容性不太好,手机端不支持,不清楚ios,个人手机是安卓java
3.pdf.js手机,pc均可以兼容性比较好,传说能够兼容到ie9以上。但个人ie9并不能够,里面使用了es6,但ie不支持,若是配置了babel等可能能够但没试过jquery
总结:若是项目需求只有PC端并不须要兼容ie9如下,能够直接使用pdfobject.js,很是简单。若是移动端也一样须要,建议直接使用pdf.jsios
如下为具体使用方法git
pdfobject.js:es6
官网地址:https://pdfobject.com/github
兼容性:web
参考连接:http://www.jq22.com/jquery-info649跨域
<div id="example1"></div> script src="js/pdfobject.js"></script> <script>PDFObject.embed("pdf/sample-3pp.pdf", "#example1");</script>
pdf.js
官网:http://mozilla.github.io/pdf.js/
线上有不少使用方法博客
如下为个人使用方法
1.下载 -> 解压后本身新建了文件夹pdfView,把bulid和web文件夹放进去。
2.使用
因为pdf.js须要使用以http://或者https://开头的服务器地址
因此下载了xampp来构建环境
装好后开启xampp的apach
把pfdView放到xampp的htdocs中
在浏览器中输入http://localhost/pdfView/web/viewer.html,出现pdf文件就显示成功了
3.在项目中使用
把pfdView整个放入项目文件中
在html中使用ifram,这样就能显示了
<iframe style="width: 100%;height:100%;" frameborder=”no” border=”0″ id="pdfContainer" src="http://localhost/pdfView/web/viewer.html?file=http://localhost/sample-3pp.pdf"></iframe>
须要注意的是pdf.js不支持跨域,因此file后面的域名和viewer.html的域名要相同
修改file后面的值就能够修改pdf文件
4.因为域名不必定是固定的,为了测试和线上方便,不须要手动改域名,因此用js给ifram的src动态赋值
function getPDFurl(filePath) { //获取pdf连接并赋值 if (!window.location.origin) { //兼容ie9中不支持window.location.origin情況 window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); } var currentWWWOrigin = window.location.origin; var filePath = filePath || 'sample-3pp.pdf' var pdfSrc = currentWWWOrigin + '/pdfView/web/viewer.html?file=' + currentWWWOrigin + '/' + filePath; // pdf文件拼接成pdf.js须要的路径 $("#pdfContainer").attr("src", pdfSrc); // 将路径填充到iframe的src里面 }
以上所有流程结束啦
使用服务器的方式,localhost或者ip地址的方式打开项目