admin管理员组

文章数量:829180

前端PDF文件转图片方法(你值得收藏)

前端PDF文件转图片方法(你值得收藏)

第一步:先下载pdfjs,网址:PDF下载地址,再引入到项目中,我是标签直接引用的

<script src="pdfjs/build/pdf.js"></script>
<script src="pdfjs/build/pdf.worker.js"></script>

注意:两个都要引进来

第二步:html代码添加两行代码,一个是canvas用来绘图,一个是img用来最后展示转换后的pdf图片

<body><img :src="imgUrl" alt="" width="100%" height="auto"><canvas id="the-canvas" style="display: none"></canvas>
</body>

第三步:js代码块,主要是将paf通过pdfjs插件绘制到canvas,然后再转换为base64格式的图片

//url参数是pdf地址,imgUrl是最后的base64格式图片
showPdf(url) {let _this = this;let imgArr = [];pdfjsLib.workerSrc = 'pdf.worker.js';let loadingTask = pdfjsLib.getDocument(url);// PDFJS.workerSrc = 'pdf.worker.js';// pdfjsLib为undefined可以换成这行// let loadingTask = PDFJS.getDocument(url);// pdfjsLib为undefined可以换成这行loadingTask.promise.then(function(pdf) {console.log('PDF loaded');let pageNum = pdf.numPages;// console.log(pageNum);for (let i=1; i<=pageNum; i++) {pdf.getPage(i).then(function(page) {console.log('Page loaded');let scale = 1;let viewport = page.getViewport(scale);// let canvas = document.getElementById('the-canvas');let canvas = document.createElement("canvas");let context = canvas.getContext('2d');canvas.height = viewport.height;canvas.width = viewport.width;let renderContext = {canvasContext: context,viewport: viewport};let renderTask = page.render(renderContext);renderTask.then(function () {console.log('Page rendered');let imgUrl = canvas.toDataURL('image/jpeg'); //转换为base64if (imgUrl) {imgArr[i-1] = imgUrl;}//pdf全部画完结束后操作if (imgArr.length==pageNum&&!isEmpty(imgArr)) {// let canvas2 = document.createElement("canvas");let canvas2 = document.getElementById('the-canvas');let context2 = canvas2.getContext('2d');canvas2.height = viewport.height*pageNum;canvas2.width = viewport.width;let count = 0;for (let j=0; j<imgArr.length; j++) {let IMG = new Image();IMG.src=imgArr[j];IMG.width = viewport.width;IMG.height = viewport.height;IMG.onload = function () {context2.drawImage(IMG,0,viewport.height*j);count++;//确保所有img渲染结束后操作if (count==pageNum) {let canvas = document.getElementById('the-canvas');//赋值给img_this.imgUrl = canvas.toDataURL('image/jpeg'); }}}}});});}}, function (reason) {console.error(reason);});function isEmpty(arr) {for(let i=0;i<arr.length;i++) {if(!arr[i])return true;}return false;}
}

本文标签: 前端PDF文件转图片方法(你值得收藏)