问题
I have an api which returns a pdf file. I'm trying to display this in vue.js and found the vue-pdf component which looks like it should do the job. Here's the project on github
I'm able to call the API and get the binary response but I've not been able to convert the binary data into something which the vue-pdf library can display.
The documentation for the :src prop is here
My vue code is below with a few of the failed attempts commented out.
<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>
I realise that for my example I could just set src to the URL of the api but ultimately it will need authorisation headers adding and chaining with OAuth calls so it needs to be an api call.
I also want to display the pdf side by side with some data from another api call so using the trick of dynamically creating an anchor tag loaded with the data and .click() 'ing it won't work for me.
回答1:
First change your expected responseType
to "blob":
return axios.get(`${process.env.VUE_APP_API_INTRANET}/pdf`, {
responseType: "blob"
})
Also convert the binary response to a Blob and then generate an object url:
.then(response => {
console.log("Success", response);
const blob = new Blob([response.data]);
const objectUrl = URL.createObjectURL(blob);
this.pdfsrc = objectUrl;
})
Don't forget to use revokeObjectURL when finished with it to avoid memory leaks.
来源:https://stackoverflow.com/questions/65255649/load-pdf-from-server-and-embed-in-vue-app