4

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 !

2
  • Do you actually want to download the pdf or show it in your view? Commented Aug 25, 2019 at 20:35
  • You can check the solutions here: stackoverflow.com/questions/41938718/… Commented Aug 25, 2019 at 20:37

2 Answers 2

11

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. responseType: 'blob', // important solved it for me
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.