vue接收后端传来的pdf文件流,前端调用预览PDF
完全不需要插件几句代码就搞定了,这里就不废话了直接上代码!直接起飞!!!懂得都懂香就完事!有问题评价export function getFile(id) {return request({url: 'api/File/Download?id=' + id,method: 'get',headers: { 'Content-Type': 'application/x-www-form-urlenc
·
我的业务场景是需要解析后端的PDF文件流,然后预览最后可以打印出来就完事!
完全不需要插件几句代码就搞定了,这里就不废话了直接上代码!
直接起飞!!!懂得都懂香就完事!有问题评价
export function getFile(id) {
return request({
url: 'api/File/Download?id=' + id,
method: 'get',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
responseType: 'arraybuffer', //一定要设置响应类型,否则页面会是空白pdf
})
}
Service.getFile('f73a66091a124b338205c16389841487').then(result => {
//const binaryData = [];
//binaryData.push(result);
//console.log(binaryData);
//获取blob链接
// var pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
// window.open(pdfUrl);
const binaryData = [];
binaryData.push(result.data);
//获取blob链接
let pdfUrl = window.URL.createObjectURL(
new Blob(binaryData, { type: "application/pdf" })
);
if (pdfUrl) {
this.handlePrint(pdfUrl);
}
})
增加一个在本页直接跳出打印的方法
handlePrint(pdf) {
if (document.getElementById("print-iframe")) {
document.body.removeChild(document.getElementById("print-iframe"));
}
//判断iframe是否存在,不存在则创建iframe
let iframe = document.getElementById("print-iframe");
if (!iframe) {
iframe = document.createElement("IFRAME");
let doc = null;
iframe.setAttribute("src", pdf);
iframe.setAttribute("id", "print-iframe");
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.close();
iframe.contentWindow.focus();
}
iframe.contentWindow.print();
},
更多推荐
已为社区贡献1条内容
所有评论(0)