直接上代码:
当然,你要先下载 pdf.js ,直接百度搜索,下载之后减压,解压的文件重新命名为 pdf,将该文件夹直接放在根目录 public 下就OK,
<iframe v-if="isFull" :src="url" frameborder="0" style="width: 100%; height: 100%"></iframe>
// pdf文件预览,接口的配置文件
export function getStrData (parameter) {
return request({
url: '/report/pdf/getPdf',
method: 'post',
data: parameter,
responseType: 'blob' //重要,一定要加
})
}
// 获取 url 文件,这里的写法:'/pdf/web/viewer.html?file=',因为是 plblic ,所以路径不用写public,写上是会报错的,找不到路径。
getStrData(this.pdfQueryParam).then((res) => {
console.log(res)
this.url = '/pdf/web/viewer.html?file=' + encodeURIComponent(this.getObjectURL(res))
}),
// 获取 pdf 文件地址
getObjectURL(file) {
var binaryData = [];
binaryData.push(file);
let url = null;
if (window.createObjectURL !== undefined) { // basic
url = window.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
} else if (window.webkitURL !== undefined) { // webkit or chrome
try {
url = window.webkitURL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
} catch (error) {
}
} else if (window.URL !== undefined) { // mozilla(firefox)
try {
url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
} catch (error) {
}
}
return url;
},
后端返回的数据结构是:
Blob {size: 375808, type: "application/pdf"}