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);
      }
    }

    原文作者:weixin_41652328
    原文地址: https://blog.csdn.net/weixin_41652328/article/details/122567051
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞