Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download PDF with laravel-dompdf with vuejs front-end

Tags:

laravel

vue.js

I created an API with Laravel. I use Vuejs for the front end.

I would like to generate a PDF based on the user and download it with view. Only, it does not work.

Here is my controller:

public function generate($id)
    {
        $data = CoverLetter::where([
            ['id', '=', $id],
            ['user_id', '=', auth()->user()->id]
        ])->first();

        $path = public_path() . '/pdf/' . $data->filename . '.pdf';

        $pdf = PDF::loadView('pdf.coverletter', $data);

        $pdf->save($path);

        return response()->download($path);
    }

And my function in vue :

async downloadCoverLetter(file) {
   axios.get('/cover-letter/generate/' + file.id)
}

And my button for download :

<button @click="downloadCoverLetter(file)"></button>

But it doesn't download at all. How to do ? Thank you !

like image 218
Jeremy Avatar asked Nov 14 '25 18:11

Jeremy


1 Answers

You can try to download file using Axios using following code:

axios({
  url: '/cover-letter/generate/' + file.id,
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.pdf');
  document.body.appendChild(link);
  link.click();
});
like image 73
jureispro Avatar answered Nov 17 '25 09:11

jureispro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!