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 {
     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,

修改之后,在此点击打印按钮,发现已经正常了:

原文地址:https://www.cnblogs.com/xiaoyaoxingchen/p/10894035.html