3

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 !

Jeremy
  • 1,756
  • 3
  • 21
  • 45

2 Answers2

9

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();
});
jureispro
  • 1,342
  • 5
  • 22
  • 43
0
I think you need to check if your code is generating PDF properly at path you have provided. If it is then following functions will work for you

// Download
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);

// Render
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);