vue实现后端base64pdf的放大缩小打印及下载

记录后端传回base64格式的pdf文件时,前端浏览下载的实现。
首先引入
import pdf from 'vue-pdf'
import PDFJS from 'pdfjs-dist'

template代码

<template>
  <div style="background-color:white;height:100%;">
    <div class="v-viewbtns">
      <div style="position:relative">
        <button @click="scaleAdd">放大</button>
        <button @click="scaleReduce">缩小</button>
        <button @click="pdfPrintAll">打印</button>
        <button @click="downloadPDF">下载</button>
      </div>
    </div>
    <div class="pdfList">
      <pdf v-for="i in numPages" :key="i" ref="myPdfComponent" :src="pdfSrc" :page="i" />
    </div>
  </div>
</template>

得到并解析后端返回值res,得到pdf对象,页数,pdfsrc。

async getPageNum(res) { 
      var decodedBase64 = atob(res.busData.data.busdata)
      var pdf = await PDFJS.getDocument({data: decodedBase64}) //pdf对象
      this.numPages = pdf.numPages
      this.data64 = res.busData.data.busdata
      this.pdfSrc = `data:application/pdf;base64,${this.data64}`
    },

得到pdfsrc后即可用<pdf>标签预览pdf文件了。

放大及缩小

    scaleAdd() {
      if (this.scale == 300) return
      this.scale += 10
      for (var i in this.$refs.myPdfComponent) {
        this.$refs.myPdfComponent[i].$el.style.width = parseInt(this.scale) + '%'
      }
    },
    scaleReduce() {
      if (this.scale == 100) {
        return
      }
      this.scale += -10
      for (var i in this.$refs.myPdfComponent) {
        this.$refs.myPdfComponent[i].$el.style.width = parseInt(this.scale) + '%'
      }
    },

打印直接使用 .print()方法

    pdfPrintAll() {
        this.$refs.myPdfComponent[0].print()
    },

利用dataURLtoBlob进行下载

fileDownload:function (data, fileName) {
      debugger
      function dataURLtoBlob(dataurl){
        var bstr = atob(dataurl)
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: 'pdf' });
      }

      let blob = dataURLtoBlob(data);
      let filename = "文件名称.pdf";
      if (typeof window.navigator.msSaveBlob !== "undefined") {
        window.navigator.msSaveBlob(blob, filename);
      } else {
        var blobURL = window.URL.createObjectURL(blob);
        // 创建隐藏<a>标签进行下载
        var tempLink = document.createElement("a");
        tempLink.style.display = "none";
        tempLink.href = blobURL;
        tempLink.setAttribute("download", filename);
        if (typeof tempLink.download === "undefined") {
          tempLink.setAttribute("target", "_blank");
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
      }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值