项目需求是要在页面中直接浏览pdf文件

1.网上比较普遍的方法是pdfobject.js和pdf.js

2.pdfobject.js使用比较简单,但ie兼容性不太好,手机端不支持,不清楚ios,我的手机是安卓

3.pdf.js手机,pc都可以兼容性比较好,传说可以兼容到ie9以上。但我的ie9并不可以,里面使用了es6,但ie不支持,如果配置了babel等可能可以但没试过

总结:如果项目需求只有PC端并不需要兼容ie9以下,可以直接使用pdfobject.js,非常简单。如果移动端也同样需要,建议直接使用pdf.js

以下为具体使用方法

pdfobject.js:

官网地址:https://pdfobject.com/

兼容性:

参考链接: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地址的方式打开项目