Vue.js +pdf.js 处理响应pdf文件流数据,前端转图片预览不可下载

使用场景及原因

      <div id="app" v-cloak>
<p><a @click="showAgreementBook">预览产品说明书</a></p>
<div class="pdfList"></div>
</div> <!--由于axios默认发送请求时,数据格式是Request Payload,并非我们常用的Form Data格式,后端未必能正常获取到,所以在发送之前,需要使用qs模块对其进行处理。-->
<script src="js/lib/qs-6.5.1.min.js"></script>
<script src="js/lib/axios-0.19.2.min.js"></script>
<script src="js/lib/vue-2.6.11.min.js"></script>
<script src="js/lib/pdf.js"></script>
<!-- HTML中直接引入vue.js 文件,IE下显示不正常,而且还报错:**[Vue warn]: Error in v-on handler: "ReferenceError: “Promise”未定义"**-->
<script src="js/lib/polyfill.min.js"></script>
<!-- <script src = "https://polyfill.io/v2/polyfill.min.js"></script> -->
<script>
var app = new Vue({
el: "#app",
data: {
insBookData: '', // 协议说明书文件流
},
mounted:funciton(){
this.instructionBook('MC002')
},
methods: {
// 获取协议说明书文件流
instructionBook: function (code) {
var _this = this
axios({
method: 'post',
url: 'XXXX',
data: Qs.stringify({prodCd: code}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
}).then(function (res) {
_this.insBookData = 'data:application/pdf;base64,' + res.data.ITReq
})
},
// base64 转blob ,用作处理IE兼容
dataURItoBlob: function (base64Data) {
var byteString;
if (base64Data.split(',')[0].indexOf('base64') >= 0)
byteString = atob(base64Data.split(',')[1]); //base64 解码
else
byteString = unescape(base64Data.split(',')[1]);
var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0]; //mime类型 -- image/png
var ia = new Uint8Array(byteString.length); //创建视图
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], {
type: mimeString
});
return blob;
},
// 点击按钮 预览操作
showAgreementBook: function () {
// for IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var blob = this.dataURItoBlob(this.insBookData)
window.navigator.msSaveOrOpenBlob(blob);
} else {
var pdfList = document.querySelector('.pdfList')
pdfList.innerHTML = ''
var loadingTask = pdfjsLib.getDocument(this.insBookData);
loadingTask.promise.then(function (pdf) {
var pages = pdf.numPages // 获取pdf文件页数
for (var i = 1; i <= pages; i++) {
pdf.getPage(i).then(function (page) {
var scale = 1.3;
var viewport = page.getViewport({scale: scale});
var canvas = document.createElement('canvas') // 生成canvas画布
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
}
pdfList.appendChild(canvas) // 追加canvas元素至页面中
page.render(renderContext); // 渲染
});
}
});
}
}
}
});
</script>
上一篇:设计模式总结篇系列:建造者模式(Builder)


下一篇:pdf.js浏览中文pdf乱码的问题解决