首先需要创建一个download.js文件;
内容:
export const download = (res, type, filename) => {
// 创建blob对象,解析流数据
const blob = new Blob([res], {
// 如何后端没返回下载文件类型,则需要手动设置:type: 'application/pdf;chartset=UTF-8' 表示下载文档为pdf,如果是word则设置为msword,excel为excel
type: type
})
const a = document.createElement('a')
// 兼容webkit浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
const URL = window.URL || window.webkitURL
// 根据解析后的blob对象创建URL 对象
const herf = URL.createObjectURL(blob)
// 下载链接
a.href = herf
// 下载文件名,如果后端没有返回,可以自己写a.download = '文件.pdf'
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
// 在内存中移除URL 对象
window.URL.revokeObjectURL(herf)
}
然后在api中写入调用下载的接口;
内容:
export const printWord = (id) => {
return request({
url: '/api/xxx/xxx/xxx',
method: 'get',
// 设置返回数据类型,这里一定要设置,否则下载下来的pdf会是空白,也可以是~arraybuffer"
responseType: 'arraybuffer',
params: {
id
}
})
}
最后在vue中引入改接口以及封装的方法;
vue文件内容:
<template>
<el-button type="primary" plain size="small" icon="el-icon-s-tools"
@click="clickPrint()"> 打印
</el-button>
</template>
<script>
import { printWord } from "@/api/xxx/xxx";
import { download } from "@/xxx/download.js";
export default {
props: ['viewRow'],
methods: {
clickPrint() {
printWord(this.viewRow.id).then(res => {
// 获取在response headers中返回的下载文件类型
let type = res.headers['content-type'];
// 获取在response headers中返回的下载文件名 因为返回文件名是通过encodeURIComponent()函数进行了编码,因此需要通过decodeURIComponent()函数解码
let fileName = decodeURIComponent(res.headers['content-disposition']).split('=')[1]
// 调用封装好的下载函数
download(res.data, type, fileName)
})
.catch(response => {
this.$message.error(response);
});
},
}
}
</script>
vue前端打印PDF封装
最新推荐文章于 2024-09-13 11:55:50 发布