vue移动端项目渲染pdf步骤

第一步:引入pdf包 

import pdf from "vue-pdf-signature";,这里不引入vue-pdf的包后面再做解释

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

(CMapReaderFactory)解决汉字空白的问题

第二步:页面的component注册pdf组件

components: {
    pdf
},

第三步:页面放置pdf盒子       

 <!-- 有查询pdf结果显示的盒子 -->

<pdf :src="pdfSrc"></pdf>    // pdfSrc为pdf包处理过后的预览链接

第四步:页面请求加载pdf之前可以写一个loading的方法,这里用的vant提示,无需要可不写

slowLoading() {
    var _this = this
    const toast = Toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: "正在生成您的权益单,请稍等...",
                className: "loading"
            });
    let tips = [
            '正在生成您的权益单,请稍等...', 
            '权益单文档生成时间较长,请耐心等待', 
             '您可以选择年度查询']
    let strlen = tips.length;
    _this.tipTimer = setInterval(() => {
        let index = Math.floor(Math.random() * strlen);
        toast.message = tips[index];
    }, 3000);
}

第五步:引入处理pdf下载的方法

// _this.pdfUrl是后端返回的pdf链接
// _this.pdfSrc声明空变量对处理的过的pdf链接进行接收绑定给页面的pdf组件的src属性

loadPdf() {
    var _this = this;
    _this.pdfDownloadUrl = _this.pdfUrl + "?isDownload=1";
    console.log(_this.pdfDownloadUrl);
    _this.pdfSrc = pdf.createLoadingTask({
        url: _this.pdfUrl,
        // 没有生效,需要确认原因并修改
        onProgress: function (status) {
            let ratio = status.loaded / status.total;
            console.log("加载进度.." + ratio);
        },
        //cMapUrl: `https://cdn.jsdelivr.net/npm/pdfjs-dist@^2.5.207/cmaps/`,
        cMapPacked: true,
        CMapReaderFactory
    });

    //加载完PDF后对缓存进行清除
    for (var key in require.cache) {
        if (key.indexOf('bcmap') >= 0) {
            delete require.cache[key];
        }
    }

    // _this.pdfSrc = _this.loadingTask;
    // console.log(_this.pdfSrc, 'src');
    _this.pdfSrc.promise.then(pdf => {
        console.log(pdf)
        console.log("pdf 加载成功...");
        Toast.clear();
        clearInterval(_this.tipTimer);
    },
        err => {
            console.log("rejected: ", err);
            clearInterval(_this.tipTimer);
            Toast.clear();
            Toast.fail({
                message: '权益单生成失败,请重试',
                forbidClick: true,
                duration: 2,
            });
        });
},
reloadPdf() {
      this.slowLoading();
      this.loadPdf()
},

this.reloadPdf()

vue-pdf的插件在使用的过程中是连连踩坑的,基本遇到3个问题:
1、PDF中文不显示
2、PDF签章没显示出来
3、第二次打开PDF的时候会遇到PDF空白的问题

问题1,通过引入CMapReaderFactory.js解决问题,但是这会引起问题3的出现

问题2,pdf签章不显示出来

//pdf.worker.js

if (data.fieldType === 'Sig') {

  data.fieldValue = null;

    //注释此行代码即可

  //_this3.setFlags(_util.AnnotationFlag.HIDDEN);

}

问题3,页面空白

CMapReaderFactory文件中加一行delete代码,加载完语言文件后清除缓存就好了

import { CMapCompressionType } from 'pdfjs-dist-sign/es5/build/pdf.js'

// see https://github.com/mozilla/pdf.js/blob/628e70fbb5dea3b9066aa5c34cca70aaafef8db2/src/display/dom_utils.js#L64

export default function() {

	this.fetch = function(query) {
		 /* webpackChunkName: "noprefetch-[request]" */
		return import('./buffer-loader!pdfjs-dist-sign/cmaps/'+query.name+'.bcmap').then(function(bcmap) {
			//加载完语言文件后清除缓存
			delete require.cache[require.resolve('./buffer-loader!pdfjs-dist-sign/cmaps/'+query.name+'.bcmap')];
			return {
				cMapData: bcmap.default,
				compressionType: CMapCompressionType.BINARY,
			};
		});
	}
};

vue-pdf的包是需要上面这么处理的,但是我在网上get到这么一个包,是其他人在vue-pdf包的基础上做的改善,所以不想麻烦的宝贝可以直接下载我最开始说的那个包就OK了(vue-pdf-signature)

pdf分页显示操作

<div class="m-vue-pdf">
      <div v-show="loaded">
        <Pdf
          v-for="index in numPages"
          :key="index"
          :src="pdfUrl"
          :page="index"
        />
      </div>
</div>

import Pdf from "vue-pdf";

data () {
    return {
      numPages: null,
      loaded: false,
      // 可引入网络文件或者本地文件
      pdfUrl: '' // 如果引入本地pdf文件,需要将pdf放在public文件夹下,引用时使用绝对路径(/:表示public文件夹)
    }
  },

components: {
    Pdf,
},

async created () {
    await this.getDetailAgreementMethods()
    this.loadPdf()
},

methods: {
    /**
* @description: 用户协议详情
*/
    async getDetailAgreementMethods () {
      try {
        let req = {
          id: this.id
        }
        let res = await getDetailAgreementApi(req)
        if (res.code == 200) {
          this.pdfUrl = res.data.url;
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 上下滚动pdf加载
    loadPdf () {
      this.pdfUrl = Pdf.createLoadingTask(this.pdfUrl)
      this.pdfUrl.promise.then(pdf => {
        this.$nextTick(() => {
          this.numPages = pdf.numPages // pdf总页数
          this.loaded = true
        })
      })
    }
}

<style scoped lang="less">
.m-vue-pdf {
  overflow: hidden;
}
</style>

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值