1

I am using Laravel/Jquery with barryvdh/laravel-snappy to create a pdf on the fly from database data.

In the controller I have:

if ($request->ajax())
{
    $document = Document::url($id)->first();
    $pdf = PDF::loadView('app.documents.whitepapers.pdf', compact('document'));
    return $pdf->download('filename.pdf');
    // return response()->send($pdf->download('filename.pdf'), 200, $headers);
}

How can I push this PDF to the browser so that is available as a download?

When I do it without Jquery it is working perfectly. The reason that it is behind a Jquery function is that I use a Modal with a form to collect a persons data before the download can be initiated. This has ajax validation.

klaaz
  • 551
  • 8
  • 20
  • What behaviour are you seeing at the moment, when using the code that you have posted? – David Smith Jul 04 '16 at 09:29
  • I see the binary data from the PDF in de javascript console and I assume it's enough to push the result, but it isn't. Do I have to do something in my jQuery ajax 'success' to push the result? – klaaz Jul 04 '16 at 09:38
  • There's an [answer here](http://stackoverflow.com/a/27563953/1206267) that should solve that missing link for you. – Ohgodwhy Jul 04 '16 at 09:45
  • That answer is not working for me. – klaaz Jul 04 '16 at 10:10

1 Answers1

2

You will not be able to present the file as a regular download via JavaScript. In order to show a download prompt to the user, you'll need an extra step in your workflow.

I would suggest the following workflow:

  1. User submits modal form
  2. Form is validated via AJAX. If validation passes, respond with a URL to download the user's PDF from, instead of the PDF itself.
  3. Your JavaScript redirects the user to this URL. Note that this is a redirect, rather than another AJAX request (see top.location.href)
  4. When the user accesses that URL, you are able to deliver the PDF using the code snippet you provided in your original question. This snippet sets the content-disposition of the response appropriately, forcing the download prompt to appear in the user's browser.

If you need to customise the PDF generation for each user, make sure to include the user's ID (or another piece of identifying information) through to step 4.

David Smith
  • 593
  • 2
  • 10