pdf.js在线预览效果
1.引入两个主要js文件
<script src="../js/pdf.js"></script> <script src="../js/pdf.worker.js"></script>
2.主要js代码
let container = document.getElementById("container"); let popId = document.getElementById("pop"); let childs = popId.childNodes; for(let i = childs.length - 1; i >= 0; i--) { popId.removeChild(childs[i]); } container.style.display = "block"; let url = 'http://192.168.0.176:8020/project/HQS20190811104441.pdf'; // let url = 'http://192.168.0.176:8020/project/2019_PDF.pdf'; pdfjsLib.workerSrc = '../js/pdf.worker.js'; pdfjsLib.getDocument(url).then(function getPdfHelloWorld(pdf) { // let $pop = $('#pop'); let $pop = document.getElementById("pop"); let shownPageCount = pdf.numPages < 50 ? pdf.numPages : 50;//设置显示的编码 //async/await解决PDF页面异地问题 let getPageAndRender = async function (pageNumber) { let popWidth = document.getElementById("pop").offsetWidth; let page = await pdf.getPage(pageNumber) let scale = 2; let viewport = page.getViewport(scale); let $canvas = document.createElement("canvas"); //判断当前弹框的宽度小于PDF文件的宽度时,将viewport和scale的值重新2倍赋值 if( popWidth < viewport.width){ scale = popWidth / viewport.width * 2; viewport = page.getViewport(scale); } $canvas.width = viewport.width*2; $canvas.height = viewport.height*2; $canvas.style.width = viewport.width+'px'; $canvas.style.height = viewport.height+'px'; $pop.appendChild($canvas); let content = $canvas.getContext('2d'); content.scale(2,2); page.render({ canvasContext: content, viewport: viewport }); if (pageNumber < shownPageCount) { pageNumber++; getPageAndRender(pageNumber); } }; getPageAndRender(1) });
3.组件
<div id="container"> <el-scrollbar class="page-component__scroll"> <div id="pop"></div> </el-scrollbar> </div>
4.效果如下: