我有一个返回 pdf 文件的 api。我试图在 vue.js 中显示它,并发现 vue-pdf 组件看起来应该可以完成这项工作。这是github上的项目 https://github.com/FranckFreiburger/vue-pdf
我能够调用 API 并获取二进制响应,但我无法将二进制数据转换为 vue-pdf 库可以显示的内容。
:src 属性的文档在这里 https://github.com/mozilla/pdf.js/blob/8ff1fbe7f819513e7d0023df961e3d223b35aefa/src/display/api.js#L117
我的 vue 代码如下,其中注释掉了一些失败的尝试。
<template>
<pdf :src="pdfsrc"></pdf>
</template>
<script>
import pdf from "vue-pdf";
import axios from "axios";
export default {
components: {
pdf
},
data() {
return {
pdfsrc: null
};
},
created() {
return axios
.get(`${process.env.VUE_APP_API_INTRANET}/pdf`, {
responseType: "application/pdf"
})
.then(response => {
console.log("Success", response);
// 1
// this.pdfsrc = new Blob([response.data]);
// 2
//this.pdfsrc = response.data;
//3
// for (var i = 0; i < response.data.length; ++i) {
// this.pdfsrc.push(response.data.charCodeAt(i) & 0xff);
// }
//4
this.pdfsrc = new Uint8Array(response.data);
})
.catch(console.error); //
}
};
</script>
我意识到,对于我的示例,我可以将 src 设置为 api 的 URL,但最终它需要添加授权标头并与 OAuth 调用链接,因此它需要是一个 api 调用。
我还想将 pdf 与来自另一个 api 调用的一些数据并排显示,因此使用动态创建加载数据的锚标记的技巧并 .click() 'ing 它对我不起作用。
首先改变你的预期responseType
到“斑点”:
return axios.get(`${process.env.VUE_APP_API_INTRANET}/pdf`, {
responseType: "blob"
})
还将二进制响应转换为Blob https://developer.mozilla.org/en-US/docs/Web/API/Blob然后生成一个对象网址 https://developer.mozilla.org/fr/docs/Web/API/URL/createObjectURL:
.then(response => {
console.log("Success", response);
const blob = new Blob([response.data]);
const objectUrl = URL.createObjectURL(blob);
this.pdfsrc = objectUrl;
})
不要忘记使用revokeObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL完成后以避免内存泄漏。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)