vue-pdf预览pdf内容动态文字丢失问题(Warning: Error during font loading: The CMap “baseUrl“ parameter must be sp)

vue-pdf无法显示中文的解决方案

vue-pdf是vue中展示pdf文件的常用插件,在pc端和移动端都有较好的显示效果。但如果载入的pdf中有中文,可能会显示不出来或者乱码,控制台中报错如下

Warning: Error during font loading: The CMap “baseUrl” parameter must be specified, ensure that the “cMapUrl” and “cMapPacked” API parameters are provided.

html如下:

 <pdf :src="src"></pdf>

1.首先我们先获取到后端返回流,如请添加图片描述
然后将返回的流数据转换为url

  find(item) {
      billExportPdf({
        id: item.row.id,
      })
        .then((res) => {

          this.src = this.getObjectURL(res);
        })
        .catch((res) => {
          console.log(res);
        });
    },
    // 将返回的流数据转换为url
    getObjectURL(file) {
      console.log(file);
      let url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome

        try {
          url = window.webkitURL.createObjectURL(file);
        } catch (error) {
          console.log(error);
        }
      } else if (window.URL != undefined) {
        // mozilla(firefox)

        try {
          url = window.URL.createObjectURL(file);
        } catch (error) {
          console.log(error);
        }
      }
      return url;
    },

然后发现并不是我们想要的效果,PDF并没有我们想要的数据

请添加图片描述
错误原因:

当PDF文件中有中文的情况下,在引用pdfjs过程中可能会出现中文不显示问题,在console中会报下面的错误,请添加图片描述
解决方法

解决方案也比较简单,在项目中引入“CMapReaderFactory.js”,引入方式如下:

import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";

然后将流数据转换为url,CMapReaderFactory方法在进行处理

   // 将返回的流数据转换为url
    getObjectURL(file) {
      console.log(file);
      let url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome

        try {
          url = window.webkitURL.createObjectURL(file);
        } catch (error) {
          console.log(error);
        }
      } else if (window.URL != undefined) {
        // mozilla(firefox)

        try {
          url = window.URL.createObjectURL(file);
        } catch (error) {
          console.log(error);
        }
      }
      //这里是重点,然后将流数据转换为url,CMapReaderFactory方法在进行处理
      url = pdf.createLoadingTask({ url: url, CMapReaderFactory });
      return url;
    },

接下来就得到了我们想要的数据,如图:

请添加图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值