In this post, I will show you how to generate pdf file in laravel 12 using dompdf composer package.
We will use the DomPDF Composer package to generate a PDF file in Laravel 12. We will create 10 dummy users and some dummy text to add to the PDF file. So, let’s follow the steps below to create the PDF file:
How to generate pdf file in laravel 12 using dompdf Example
Step 1: Install Laravel 12
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
laravel new example-app
Step 2: Install DomPDF Package
Next, we will install the DomPDF package using the following Composer command. Let’s run the command below:
composer require barryvdh/laravel-dompdf
Step 3: Create Controller
In this step, we will create a PDFController with a method called generatePDF() where we will write the code to generate a PDF. So, let’s create the controller using the command below. You Can Learn Laravel 12 Image Upload Example Tutorial
php artisan make:controller PDFController
In the PDFController
, we also get users table data and display it into a PDF file. So, you can add some dummy data to the users table by using the following Tinker command:
php artisan tinker
User::factory()->count(10)->create()
Now, update the code in the controller file.
app/Http/Controllers/PDFController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use PDF;
class PDFController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function generatePDF()
{
$users = User::get();
$data = [
'title' => 'Welcome to ItSolutionStuff.com',
'date' => date('m/d/Y'),
'users' => $users
];
$pdf = PDF::loadView('myPDF', $data);
return $pdf->download('itsolutionstuff.pdf');
}
}
Top comments (0)