In my Laravel 7 application, I have a route where a PDF is dynamically generated, and I want the browser to treat it as a file download.
In writing this, I found a number of docs and questions about Laravel serving a file download using a file saved on the filesystem, but in my case, I don’t want to store the pdf in the filesystem. I just want to dynamically generate it when the user hits the route, and then the browser downloads the pdf.
I’m using the mpdf library and it appears that it is properly forming a pdf file. However, Laravel is throwing a The Response callback must not be null
LogicException. In the browser, I see the data of the PDF displayed, followed by the exception stack trace.
Here’s the controller method:
public function pdf($id) { $manual = new Appmanual($id); $contents = view('admin.manual')->with($manual)->render(); $mpdf = New MpdfMpdf(); $mpdf->WriteHtml($contents); $pdf = $mpdf->output(); return response()->streamDownload($pdf, 'manual.pdf'); }
In this screenshot, you can see the data of the PDF file, which tells me its being generated and delivered:
However the exception follows after the EOF of the PDF object:
I found this 5-year-old issue from Symfony for the same exception message, but it seems to have been long resolved. I’ve found nothing else in relation to Laravel 7.
How do I properly specify a pdf file download of data in Laravel 7?
Advertisement
Answer
I was able to get the desired behavior by using a macro and specifying the headers.
return response()->streamDownload( function() use ($pdf) { echo $pdf; } , 'manual.pdf', ['Content-type'=>'application/pdf'] );