Generating and then downloading PDF files using Laravel, essentially you are downloading blade files as PDF’s which can open up your web applications to some unique possibilities.
This post was done using Laravel 10, but it should work fine for other versions like 9 or 8.
The first step is to install DOMpdf for generating PDF files
composer require barryvdh/laravel-dompdf
Next in config/app.php
add the following into the providers
array:
Barryvdh\DomPDF\ServiceProvider::class,
and then in the aliases
array add:
'PDF' => Barryvdh\DomPDF\Facade::class,
Now you want to publish the configuration settings for DOMPdf
php artisan vendor:publish
Create a blade file in views pdf/save_as_pdf.blade.php
<b>Title:</b> <pre>{{$title}}</pre> <b>Description:</b> <pre>{{$description}}</pre> <b>Dimensions:</b> <pre>{{$dimensions}}</pre>
This blade file is what will be converted to PDF, it’s simple for the case of this being a guide.
To then save this blade file as a PDF use this as a route controller:
public function downloadPdf(Product $product): \Illuminate\Http\Response { $pdf = PDF::loadView('pdf.save_as_pdf', [ 'title' => $product->title, 'description' => $product->description, 'dimensions' => $product->dimensions ]); return $pdf->download($product->id . '.pdf'); }
When you click on a link or navigate to this route this will automatically download the PDF through the browser.