vue-pdf的使用方法及解決在線打印預覽亂碼


最近在用vue做項目的時候,頁面中需要展示后端返回的PDF文件,於是便用到了vue-pdf,其使用方法為 :

npm install --save vue-pdf

官網地址:https://www.npmjs.com/package/vue-pdf

不多說了,直接上代碼:

<template>
  <div>
    <div class="parent">
      <button @click="$refs.pdf.print()">打印</button>
      <pdf ref="pdf" :src="src" :page='currentPage' @progress='getProgress' @page-loaded="currentPage=$event" @loaded="loadPdfHandler"></pdf>
    </div>
    <el-pagination background layout="prev, pager, next" :page-size="1" :total="numPages" @current-change="changePage">
    </el-pagination>
  </div>
</template>

<script>
  import pdf from 'vue-pdf'
  const src = pdf.createLoadingTask('./static/bm.pdf');
  export default {
    data() {
      return {
        src,
        numPages: 100,
        currentPage: 1
      }
    },
    methods: {
      changePage(page) {
        this.currentPage = page;
      },

      getProgress(e) {
        console.log('加載進度:',e);
      },

      loadPdfHandler(){
        console.log('PDF加載完成啦');
      }
    },
    mounted() {
      this.src.then(pdf => {
        this.numPages = pdf.numPages;
      });
    },
    components: {
      pdf
    },
  }

</script>

<style scoped>
  .parent {
    width: 1000px;
    margin: 0 auto;
  }
</style>

代碼中引用了element-UI中的分頁,可以將PDF文件分頁展示在頁面中,但是在點擊打印按鈕時,卻出現了亂碼:

 

 最后通過尋找答案,發現原始的打印頁面,PDF格式亂碼,主要是因為PDF里使用了自定義字體,不能識別,其解決方案為:

需要修改 node_moduls 中 vue-pdf 安裝包的 pdfjsWrapper.js 文件

其中pdfjsWrapper.js為我修改后的文件,pdfWrapper1.js為原始未修改過的文件。

其修改可參考以下鏈接:

git-hup地址:https://github.com/FranckFreiburger/vue-pdf/pull/130/commits/253f6186ff0676abf9277786087dda8d95dd8ea7,

修改之后,在此點擊打印按鈕,發現已經正常了:

 


免責聲明!

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



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