Vue 图片、PDF预览(Blod数据类型)

Vue 图片、PDF预览(Blod数据类型)

简单的PDF/图片预览

请求接口

需要将后端返回的文件转为文件流
这里的请求用的axios封装的 也可以用原生的 注意设置responseType: "blob"

axios.request({
	headers: { "content-type": "multipart/form-data" },
	  url: URL,//请求数据的接口 这里根据个人需求修改
	  method: "get",
	  withCredentials: true,
	  timeout: 120000,//请求响应时间
	  responseType: "blob"//MDN api参考 https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType
	}).then(function(response) {
	  let reader = new window.FileReader();
	  let data = response.data || JSON.parse(response.request.responseText);
	  reader.readAsArrayBuffer(data);
	  reader.onload = function(e) {
	    const result = e.target.result;
	    // const contentType = data.type;
	    // 生成blob图片/PDF,需要参数(字节数组, 文件类型)
	    const blob = new Blob([result], { type: "application/pdf" });
	    // 使用 Blob 创建一个指向类型化数组的URL 
	    //MDN api参考 https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
		try {
	        that.pdfUrl = window.URL.createObjectURL(blob);
	    } catch (error) {
	        console.log(error);
	    }
  	};
}).catch(() => {
  this.$message.error("预览失败!");
});

html

 <div :style="{ height: '80vh', minHeight: '600px', margin: '8px 0px' }">
  <iframe
    :src="pdfUrl"
    id="previewPdf"
    frameborder="0"
    style="width: 100%; height: 100%"
  ></iframe>
</div>

图片预览

参考:点击链接 MDN讲解比较详细
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Vue中的PDF并打印后端数据,可以按照以下步骤进行操作: 1. 安装相应的依赖:首先,我们需要使用vue-pdf库来实现PDF和打印功能。可以使用npm或yarn进行安装,命令如下: ``` npm install vue-pdf 或者 yarn add vue-pdf ``` 2. 引入vue-pdf组件:在Vue的组件中引入之前安装的vue-pdf组件,可以通过import来导入它,并在components中注册它。例如: ```javascript import pdfViewer from 'vue-pdf'; export default { components: { pdfViewer, }, // ... } ``` 3. 获取后端数据:使用Vue中的axios或者fetch等方法调用后端API,获取需要打印的PDF数据。例如,使用axios发送GET请求获取数据: ```javascript import axios from 'axios'; export default { data() { return { pdfData: null, // 存储PDF数据 }; }, mounted() { axios.get('后端API地址') .then(response => { this.pdfData = response.data; // 存储获取到的PDF数据 }) .catch(error => { console.error('获取PDF数据失败', error); }); }, // ... } ``` 4. 渲染PDF:在Vue的模板中,使用vue-pdf组件来渲染PDF。将获取的PDF数据通过v-bind绑定到vue-pdf组件的src属性上。例如: ```html <div> <pdf-viewer :src="pdfData"></pdf-viewer> </div> ``` 5. 打印PDFvue-pdf组件内置了打印功能,只需要将vue-pdf组件的print按钮绑定到一个方法,点击时触发打印功能即可。例如: ```html <div> <pdf-viewer :src="pdfData" ref="pdfViewer"></pdf-viewer> <button @click="printPDF">打印</button> </div> ``` ```javascript methods: { printPDF() { this.$refs.pdfViewer.print(); // 调用vue-pdf组件的打印功能 }, }, ``` 这样,我们就可以实现Vue中的PDF和打印后端数据的功能。记得根据实际情况修改后端API地址以及对数据的处理方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值