js將PDF轉為base64格式,並在將base64格式PDF回顯在頁面中


js將PDF轉為base64格式

<!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>Document</title>
</head>
<body>
  <input type="file" onchange='handelChange(this)'>
</body>
</html>
<script>
  function handelChange (e) {
    console.log(e.files)
    var file = new File(e.files,"r");
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      // base64格式PDF
      console.log(reader.result);
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
  }
</script>

base64格式PDF回顯在頁面中

<template>
  <div>
    <div>pdf轉為base64,並回顯</div>
    <pdf v-for="i in numPages" :key="i" :src="src" :page="i" ref="myPdfComponent"></pdf>
  </div>
</template>
<script>
// data為后端給的base64格式的pdf
import { data } from "./tempData";
import pdf from 'vue-pdf'
// 解決部分文字不顯示的問題
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
export default {
  data () {
    return {
      src: '',
      numPages: 0,
      page: 1,
      currentPage: 0
    };
  },
  components: {
    pdf
  },
  methods: {
     getUrl () {
      return new Promise(resolve => {
        let da = data.fileGongjiao
        resolve(da)
      })
    },
  },
  mounted () {
    // 獲取到base64的pdf
    this.getUrl()
      .then((da) => {
        let datas = 'data:application/pdf;base64,' + da
        this.src = pdf.createLoadingTask({ url: datas, CMapReaderFactory });
        this.src.promise.then(pdf => {
          this.numPages = pdf.numPages;
        });
      })
  }
}
</script>

******注:

*****base64為去掉開頭格式的base64 ,如‘JVBERi0xLjMNJeLjz9MNCjcgMCBvICAgICAgICAgICAgICAgICAgDQoyMSAwIG9.........................................(此處省略)’,

*****不包含 'data:application/........................(此處省略)'

 

參考 https://blog.csdn.net/yuanmengdage/article/details/111871993

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM