項目需求是要在頁面中直接瀏覽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地址的方式打開項目