vue使用canvas渲染pdf

1.原生方法

<div>
	<div class="bottom" style="position: fixed;right: 0">
	  <input class="pdf-zoom" type="submit" value="+" @click="zoomPdf(1)"/>
	</br>
	<input class="pdf-zoom" type="submit" value="-" @click="zoomPdf(0)"/>
</div>
	<div id="canvasEle"></div>
</div>

pdfContent: {
       canvasEle: '', // 渲染pdf的元素
       detail: '', // pdf详情
       scale: 1 // 放缩比例
     },
     
     this.pdfContent['canvasEle'] = document.getElementById("canvasEle");
         this.pdfContent['detail'] = res.data;
         this.loadPdf(this.pdfContent, 0);
    /**
    * pdf放大/缩小
    */
   zoomPdf(num) {
     const pObjs = this.pdfContent.canvasEle.childNodes;
     for (let i = pObjs.length - 1; i >= 0; i--) { // 一定要倒序,正序是删不干净的,可自行尝试
       this.pdfContent.canvasEle.removeChild(pObjs[i]);
     }
     if (num) {
       this.pdfContent.scale = this.pdfContent.scale + 0.5;
     } else {
       this.pdfContent.scale >  1 ? this.pdfContent.scale = this.pdfContent.scale - 0.5 : ''
     }
     this.loadPdf(this.pdfContent);
   },
   /**
    * 加载pdf
    */
   async loadPdf(pdfContent, flag){
     const pdfData = atob(pdfContent.detail)
     pdfjsLib.GlobalWorkerOptions.workerSrc ='https://cdn.jsdelivr.net/npm/pdfjs-dist@2.4.456/build/pdf.worker.js';
     const loadingTask = pdfjsLib.getDocument({ data: pdfData, });
     const pdf = await loadingTask.promise;
     for (let i = 1; i < pdf.numPages + 1; i++) {
       const page = await pdf.getPage(i);
       let viewport = page.getViewport({ scale: pdfContent.scale });
       this.proportion = this.clientWidth / viewport.width;
       if (flag === 0) {
         this.pdfContent.scale = this.pdfContent.scale * this.proportion;
         viewport = page.getViewport({ scale: pdfContent.scale });
       }
       let canvas = document.createElement('canvas');
       let context = canvas.getContext('2d');
       canvas.height = viewport.height;
       canvas.width = viewport.width;
       const renderContext = {
         canvasContext: context,
         viewport,
       };
       pdfContent.canvasEle.appendChild(canvas);
       page.render(renderContext);
     }
   }

2.使用vue-pdf

(1)安装
npm install --save vue-pdf
(2)基本使用
<template>
<div class="pdf">
  <pdf 
    ref="pdf"
    :src="pdfUrl">
  </pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
  name: 'Pdf',
  components:{
      pdf
  },
  data(){
      return {
          pdfUrl:"http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf",
      }
  }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值