Vue converts base64 stream data into a pdf file and opens it in a new page

After referring to many writing methods, this method can finally be realized.

The specific implementation method: write the following two methods in vue, directly call the viewPdf function, and pass the parameter as the base64 stream data to be converted

    viewPdf(content) {
      if (!content) {
        this.$message.error('暂无意见')
        return
      }
      const blob = this.base64ToBlob(content)
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob)
      } else {
        const fileURL = URL.createObjectURL(blob)
        window.open(fileURL)
      }
    },
    base64ToBlob(code) {
      code = code.replace(/[\n\r]/g, '')
      // atob() 方法用于解码使用 base-64 编码的字符串。
      const raw = window.atob(code)
      const rawLength = raw.length
      const uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: 'application/pdf' })
    },

Guess you like

Origin blog.csdn.net/luobo2345/article/details/122499168