Vue Js Download PDF from API:Vue.js is a popular JavaScript framework for building user interfaces. To download a PDF file from an API using Vue.js, you can use the built-in Fetch API or Axios library to make an HTTP request to the API endpoint that returns the PDF file. Once the PDF file is returned from the API, you can use JavaScript’s Blob and URL.createObjectURL methods to create a URL that represents the PDF file. Finally, you can use the HTML5 <a> tag with the download attribute to download the PDF file. With this approach, you can download PDF files from an API using Vue.js
How can I use Vue js download a PDF file from an API?
This is a Vue.js code that demonstrates how to download a PDF file from an API using Axios, a popular JavaScript library for making HTTP requests.
The code defines a Vue.js app with a single button element that triggers a download when clicked. When the button is clicked, the downloadFile
method is called.
Inside the downloadFile
method, an HTTP GET request is made using Axios to the specified URL which points to a PDF file. The responseType
is set to ‘blob’ which instructs Axios to return the response data as a Blob object.
Once the response is received, a new Blob object is created with the response data and a URL for the Blob is created using the window.URL.createObjectURL
method. This URL can be used to create a link to download the file.
Next, a new a
element is created and its href
attribute is set to the URL of the Blob. The download
attribute is also set to the desired file name. This element is then appended to the document body and clicked programmatically using the link.click()
method.
This causes the browser to initiate a download of the PDF file with the specified name.
Note that the example code uses a dummy PDF file hosted on the w3.org website, but you can modify the URL to download your own PDF file from your API.
Vue Js Download PDF from API Example
<div id="app">
<button @click="downloadFile">Download File</button>
</div>
<script type="module">
const app = Vue.createApp({
methods: {
downloadFile() {
axios({
url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
method: 'GET',
responseType: 'blob',
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'dummy.pdf');
document.body.appendChild(link);
link.click();
});
},
},
});
app.mount('#app');
</script>