Sometimes, we want to download a PDF file with Vue.js.
In this article, we’ll look at how to download a PDF file with Vue.js.
How to download a PDF file with Vue.js?
To download a PDF file with Vue.js, we can create an object URL from the PDF blob response, assign the URL as the value of the href
property of an anchor element.
And them we call anchor’s click
method to download it.
For instance, we write
<script>
//...
export default {
//...
methods: {
async downloadFile() {
const response = await this.$http.get(this.appApiPath + "/testpdf", {
responseType: "arraybuffer",
});
const blob = new Blob([response.data], { type: "application/pdf" });
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = "test.pdf";
link.click();
},
},
//...
};
</script>
to call $http.get
with the PDF URL where $http.get
is the Axios get
method.
We set responseType
to 'arraybuffer'
to download the response as an array buffer.
Next, we convert the response to a blob with the Blob
constructor.
Then we create a link with createElement
.
Then we set its href
property to the object URL created from createObjectURL
called with blob
.
And then we set link.download
to the file name of the downloaded file.
Finally, we call click
to download it.
Conclusion
To download a PDF file with Vue.js, we can create an object URL from the PDF blob response, assign the URL as the value of the href
property of an anchor element.
And them we call anchor’s click
method to download it.