首頁 > 軟體

vue如何將base64流資料轉成pdf檔案並在新頁面開啟

2023-02-08 22:00:31

將base64流資料轉成pdf檔案並在新頁面開啟

參考了很多寫法,最終這種方法可以實現。

具體實現方法:

將下面這兩個方法寫在vue中,直接呼叫viewPdf函數,傳參為要轉換的base64流資料

    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(/[nr]/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' })
    },

base64轉二進位制檔案流並顯示

1.判斷base型別 這裡提供圖片和pdf

  function base64FileHeaderMapper(fileBase64) {
    let fileHeader = new Map();
    //獲取不同檔案的檔案頭前3個字作為判斷依據
    fileHeader.set("/9j", "jpeg");
    fileHeader.set("iVB", "png");
    // fileHeader.set("Qk0", "BMP")
    // fileHeader.set("SUk", "TIFF")
    fileHeader.set("JVB", "pdf");
    // fileHeader.set("UEs", "OFD")
    let res = "";
    //遍歷map中所提及的檔案頭特徵
    fileHeader.forEach((v, k) => {//IE不支援箭頭函數  相容IE需要改寫
      if (k == fileBase64.substr(0, 3)) {
        res = v;
      }
    });
    //如果不在map中返回unknown file
    if (res == "") {
      res = "unknown file";
    }
    //否則返回map中的value值
    return res;
  }

2.base轉二進位制檔案流

  function base64ToBlob(code, type) {
    code = code.replace(/[nr]/g, "");
    let raw = window.atob(code);
    let rawLength = raw.length;
    let uint8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; i++) {
      uint8Array[i] = raw.charCodeAt(i);
    }
    if ("pdf" === type) {
      return new Blob([uint8Array], { type: "application/pdf" });
    } else {
      return new Blob([uint8Array], { type: "image/jpeg" });
    }
  }

3.填坑

base64 字串中不含 data:application/pdf;base64,

否則 window.atob(code);解碼報錯,不解碼也無法載入pdf

4.完整程式碼

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>base轉二進位制</title>
</head>

<body>
  <div style="width: 100vw;height: 100vh">
    <iframe width="100%" height="100%" src="" frameborder="0" id="iframe"></iframe>
  </div>
  <script>
    let iframe = document.getElementById("iframe")
    let base = "JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVhdG9yIChNb3ppbGxhLzUuMC..."; //base64不完整
    let s = base64FileHeaderMapper(base);
    let blob = base64ToBlob(base, s);
    iframe.src = URL.createObjectURL(blob);

    function base64FileHeaderMapper(fileBase64) {
      let fileHeader = new Map();
      //獲取不同檔案的檔案頭前3個字作為判斷依據
      fileHeader.set("/9j", "jpeg");
      fileHeader.set("iVB", "png");
      // fileHeader.set("Qk0", "BMP")
      // fileHeader.set("SUk", "TIFF")
      fileHeader.set("JVB", "pdf");
      // fileHeader.set("UEs", "OFD")
      let res = "";
      //遍歷map中所提及的檔案頭特徵
      fileHeader.forEach((v, k) => {//箭頭函數IE不支援 相容IE需改寫
        if (k == fileBase64.substr(0, 3)) {
          res = v;
        }
      });
      //如果不在map中返回unknown file
      if (res == "") {
        res = "unknown file";
      }
      //否則返回map中的value值
      return res;
    }

    function base64ToBlob(code, type) {
      code = code.replace(/[nr]/g, "");
      let raw = window.atob(code);
      let rawLength = raw.length;
      let uint8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; i++) {
        uint8Array[i] = raw.charCodeAt(i);
      }
      if ("pdf" === type) {
        return new Blob([uint8Array], {
          type: "application/pdf"
        });
      } else {
        return new Blob([uint8Array], {
          type: "image/jpeg"
        });
      }
    }
  </script>
</body>

</html>

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com