Search code examples
javascriptlaravelvue.jsaxiosdompdf

Laravel, Vue.js | blank pdf getting downloaded via axios request


I've been trying to download a PDF from my Laravel application via axios, but the file that's getting downloaded is an empty pdf.

I am using DomPdf to create pdf and download.js to download it below is my code.

Note:: it works just fine if I try to download it without ajax request.

Laravel,

return PDF::loadView('print', compact('bill'))->download($bill->number.'.pdf'); Javascript

``axios.get(`/bills/${id}/print` {
responseType: 'blob',Accept: 'application/pdf'
})
.then(response => {
  const download = require('@/download');
  // @ is just an alias for my root js directory.
  download(response.data, `file.pdf`, 'application/pdf');
});``

Solution

  • Try following code:

    In Laravel controller:

    $pdf = PDF::loadView('finance.remainingFee', compact('fee', 'time'));
    $pdf->setPaper('a4' , 'portrait');
    return $pdf->output();
    

    And in Vue file:

      axios.get(APP_URL + `api/finance/remainingStudentFee/${fee_id}`, {responseType: 'blob'}).then(response => {
    
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'remaining_fee.pdf'); //or any other extension
        document.body.appendChild(link);
        link.click();
    
      })
      .catch(error => {
        console.log(error);
      })