一、下載PDFJS
官網:http://mozilla.github.io/pdf.js/getting_started/#download

二、拖入項目中
將安裝包放入到項目中public文件夾下

三、頁面中使用
1.直接使用
window.open('/pdf/web/viewer.html?file=' + path);//path是文件的全路徑地址
2.通過iframe新頁面使用
<template>
<div class="main-page-container">
<div class="pdf_container">
<iframe
:src="`pdf/web/viewer.html?file=${pdfUrl}`"
class="pdf-window"
width="100%"
height="100%"
frameborder="0"
></iframe>
</div>
</div>
</template>
<script>
export default {
name: "ReportView",
data() {
return {
pdfUrl: ""
};
}
};
</script>
<style lang="less" scoped>
.pdf_container{
width: 100%;
height: calc(100% - 90px);
}
</style>
四、問題總結
1.解決跨域問題
報錯 "file origin does not match viewer's"
解決: 直接注釋掉web/viewer.js中的這幾行,不去判斷跨域即可
// var fileOrigin = new URL(file, window.location.href).origin; // if (fileOrigin !== viewerOrigin) { // throw new Error("file origin does not match viewer's"); // }
2.pdfjs中身份認證
通過這種方式訪問:'/pdf/web/viewer.html?file=' + path,如何在請求后端pdf文檔時,在請求頭中加入token驗證呢?
解決:找到build下的pdf.js文件,加上請求頭token的設置代碼即可
var params = Object.create(null); var rangeTransport = null, worker = null; // 添加設置token代碼 params['httpHeaders'] = { "Authentication": window.localStorage.getItem('TOKEN') }
3.去掉pdf預覽頂部的下載等按鈕
解決:找到web下viewer.html文件,找到相對應的控件設置行內樣式 visibility: hidden 即可

4.分段加載
對於一些比較大的pdf文件,我們需要做到分段加載,否則會使界面卡死
解決:
1)找到web下viewer.js文件,將disableAutoFetch、disableStream均改為true

2)找到build/pdf.js文件,尋找DEFAULT_RANGE_CHUNK_SIZE配置項,並修改為65536*16
![]()
五、參考鏈接
https://www.cnblogs.com/linjiangxian/p/13730954.html#_label1
https://www.freesion.com/article/22081445732/
