vue-pdf 通过文件流预览pdf文件

88 篇文章 1 订阅
76 篇文章 0 订阅

前端预览pdf功能,后端返回文件流的形式

1 首先,下载vue-pdf

npm install vue-pdf -D

2 其次,模板里面引入vue-pdf

import pdf from ‘vue-pdf’

3 html:

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

4 相关js:

// 初始化获取pdf文件
getPdfCode (index) {
	this.$set(this.loading, index, true) // iview的按钮懒加载
	axios({
		method: 'get',
		url: process.env.VUE_APP_BASE_API + `/crm/crm/contract/preview/${this.contractID}`,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': 'Bearer ' + this.$util.getCookie('Admin-Token')
		},
		responseType: 'blob' //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置!!!
	}).then(res => {
		this.fileStream = res
		this.src  = this.getObjectURL(res.data); // 将返回的数据流转换为url
		this.previewContract = true
		this.$set(this.loading, index, false)
	})
},

// 将返回的流数据转换为url
getObjectURL(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) {

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

    }
  }
  return url;
}

完成以上几步就可以预览pdf

实现下载pdf
实现分页显示pdf

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值