vue中将base64流数据转成pdf文件可打印

vue中将base64流数据转成pdf文件可打印

这次后端返参不是oss那边传回来的,而是传给我一串base64编码的字符串,让我去生成可打印的pdf,返参如下所示。

返参base64编码

一、base编码转为pdf方法

  • atob() 方法可用于解码base-64 编码的字符串,再通过Blob将Uint8Array数组转换成pdf类型的文件对象
    // content是base64格式
    viewPdf(content) {
      console.log("content",content);
      const blob = this.base64ToBlob(content);
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob);
      } else {
        const fileURL = URL.createObjectURL(blob);
        window.open(fileURL);//打开ppf文件
      }
    },
    base64ToBlob(code) {
      code = code.replace(/[\n\r]/g, '');// 检查base64字符串是否符合base64编码
      // atob() 方法用于解码使用 base-64 编码的字符串。
      const raw = window.atob(code);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
      // 将解码后的逐个字符转换成Unicode序号,放入Unit8Array数组
        uInt8Array[i] = raw.charCodeAt(i);
      }
      // 通过Blob将Uint8Array数组转换成pdf类型的文件对象
      return new Blob([uInt8Array], { type: 'application/pdf' });
    },

二、打印方法

  • 再写个打印方法,调接口获取返回的base64编码字符串,再去调用上面base64转为pdf的方法
	// 点击打印
    handlePrint() {
      let params = {
        deliveryNoteNoList: this.deliveryNoteNoList
      };
      this.$requestFn("POST", this.$url.dispatch.printDeliveryNote, params).then((res) => {
        if(res && res.deliverNoteBase64List[0]){
          this.viewPdf(res.deliverNoteBase64List[0]);
        }
      });
    },
  • 接着就可实现效果了,如下图所示
    base64编码转成pdf预览
    这个方法我实现过了,可以实际运用的,如果还有其他方法,希望大家可以留言,一起交流一下hhh
posted @ 2023-03-09 15:06  葉謙虛  阅读(1957)  评论(0编辑  收藏  举报