Vue.js Download PDF with Axios

In this short article, I'll share how to download PDF with Axios. Let's get started:

Table of Contents

Create a Vue Project and Install Axios

To create a build-tool-enabled Vue project on your machine, run the following command in your command line:

npm init vue@latest

Navigate to vue project and install Axios:

npm install axios

Create Download PDF Component

Go to src/components folder and create FileDownload.vue file. Then open the file and paste this code:

FileDownload.vue
<template>
  <h2>Vue.js Download PDF Using Axios</h2>
  
  <button @click="downloadFile()">Download</button>
</template>

<script>
  import axios from 'axios';
  
  export default {
    methods: {
      downloadFile() {
        axios({
          url: 'http://www.africau.edu/images/default/sample.pdf', // download file link goes here
          method: 'GET',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          responseType: 'blob',
        }).then((res) => {
          var FILE = window.URL.createObjectURL(new Blob([res.data]));
        
          var docUrl = document.createElement('x');
          docUrl.href = FILE;
          docUrl.setAttribute('download', 'sample.pdf');
          document.body.appendChild(docUrl);
          docUrl.click();
        });
      },
    }
  }
</script>

Call the Component

Now just call the component anywhere. I'm going to call in App.vue.

App.vue
<template>
    <FileDownload></FileDownload>
</template>
 
<script>
  import FileDownload from './components/FileDownload.vue';
  
  export default {
    components: {
      FileDownload
    }
  }
</script>

Now run the project and check. That's it. ๐Ÿ˜Š


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.