To generate a PDF in the Laravel application, use the “dompdf package.” Dompdf is an HTML-to-PDF converter.
To export into PDF, We need to write the view file. Then, we will write the HTML code and load data dynamically from the database as required. After that, we will export this view as a PDF file.
Step 1: Create a laravel project
Install Laravel using the following command.
composer create-project --prefer-dist laravel/laravel laravelPDF
You need to install the laravel/ui package.
composer require laravel/ui
Now, add the Bootstrap library using laravel/ui:
php artisan ui bootstrap
Step: 2 Download the laravel-dompdf package
composer require barryvdh/laravel-dompdf
Step: 3 Configure the package in Laravel
Go to bootstrap >> provider.php file and add the below code:
<?php return [ App\Providers\AppServiceProvider::class, Barryvdh\DomPDF\ServiceProvider::class, ];
Here, we are registering the ServiceProvider of the barryvdh package.
Step 4: Connecting Laravel with Database
Open phpmyadmin and create a new Database like this:
Now, open the .env file, edit these variables, and put your database name, username, and password:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=laravelpdf DB_USERNAME=root DB_PASSWORD=root
Keep in mind that I am using MAMP; these are my credentials, and it is local.
Step 5: Create model and migration files
We will create model and migration files using the following command.
php artisan make:model Disneyplus -m
Go to the [timestamp].create_disneypluses_table.php file and add the columns.
public function up() { Schema::create('disneypluses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('show_name'); $table->string('series'); $table->string('lead_actor'); $table->timestamps(); }); }
Now, migrate the database using the following command.
php artisan migrate
Step 6: Create a controller and routes
The next step is to create a DisneyplusController.php file.
php artisan make:controller DisneyplusController
Now, add the two routes inside the routes >> web.php file.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\DisneyPlusController; Route::get('/', function () { return view('welcome'); }); Route::get('disneyplus/create', [DisneyPlusController::class, 'create'])->name("disneyplus.create"); Route::post('disneyplus/store', [DisneyPlusController::class, 'store'])->name("disneyplus.store");
Create two methods inside the DisneyplusController.php file.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Barryvdh\DomPDF\Facade\Pdf; class DisneyplusController extends Controller { public function create() { } public function store() { } }
Don’t forget to import the PDF module.
Step 7: Create a layout blade file
Inside the resources >> views folder, create a new file called layout.blade.php.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Laravel PDF Generation</title> </head> <body> <div class="container"> @yield('content') </div> <!-- Scripts --> @vite(['resources/sass/app.scss', 'resources/js/app.js']) </body> </html>
Step: 8 Create a form blade file for input the data
Inside the views folder, create the form.blade.php file. Add the following code:
@extends('layout') @section('content') <style> .uper { margin-top: 40px; } </style> <div class="card uper"> <div class="card-header"> Add Disneyplus Shows </div> <div class="card-body"> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif <form method="post" action="{{ route('disneyplus.store') }}"> <div class="form-group"> @csrf <label for="name">Show Name:</label> <input type="text" class="form-control" name="show_name"/> </div> <div class="form-group"> <label for="series">Series :</label> <input type="text" class="form-control" name="series"/> </div> <div class="form-group"> <label for="actor">Show Lead Actor :</label> <input type="text" class="form-control" name="lead_actor"/> </div> </br> <button type="submit" class="btn btn-primary">Create Show</button> </form> </div> </div> @endsection
Step 9: Store data in the database
We will write the two functions inside the DisneyplusController.php file.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Disneyplus; use Barryvdh\DomPDF\Facade\Pdf; class DisneyplusController extends Controller { public function create() { return view('form'); } public function store(Request $request) { $validatedData = $request->validate([ 'show_name' => 'required|max:255', 'series' => 'required|max:255', 'lead_actor' => 'required|max:255', ]); Disneyplus::create($validatedData); return redirect('disneyplus/list'); } }
In the above file, we first show the form file, and then, inside the store function, we check for validation and store the data in the database.
We haven’t created the disneyplus/list route yet but will do it later.
Add the fillable fields inside the Disneyplus.php model file.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Disneyplus extends Model { use HasFactory; protected $fillable = ['show_name', 'series', 'lead_actor']; }
Go to this route: http://localhost:8000/disneyplus/create
You will see one form. Try to save the data; if everything in the code is right, you will see one entry in the database.
Step 10: Create a view file to display the data
Before creating a view file, we must add one route inside the web.php.
//web.php Route::get('disneyplus/list', [DisneyPlusController::class, 'index'])->name('disneyplus.index');
Create a view file called list.blade.php file. Add the following code.
@extends('layout') @section('content') <table class="table table-striped"> <thead> <th>ID</th> <th>Show Name</th> <th>Series</th> <th>Lead Actor</th> <th>Action</th> </thead> <tbody> @foreach($shows as $show) <tr> <td>{{$show->id}}</td> <td>{{$show->show_name}}</td> <td>{{$show->series}}</td> <td>{{$show->lead_actor}}</td> </tr> @endforeach </tbody> </table> @endsection
Now, add the code inside the index() function to the DisneyplusController.php file.
public function index() { $shows = Disneyplus::all(); return view('list', compact('shows')); }
Now, go to http://localhost:8000/disneyplus/list
You will see the listing of the shows.
Step: 11 Create a route to download the PDF file
Add the following code inside the route file.
// web.php Route::get('/downloadPDF/{id}',[DisneyPlusController::class, 'downloadPDF'])->name('disneyplus.pdf');
Update the list.blade.php file and add the Download PDF link.
@extends('layout') @section('content') <table class="table table-striped"> <thead> <th>ID</th> <th>Show Name</th> <th>Series</th> <th>Lead Actor</th> <th>Action</th> </thead> <tbody> @foreach($shows as $show) <tr> <td>{{$show->id}}</td> <td>{{$show->show_name}}</td> <td>{{$show->series}}</td> <td>{{$show->lead_actor}}</td> <td><a href="{{ route('disneyplus.pdf', $show->id)}}">Download PDF</a></td> </tr> @endforeach </tbody> </table> @endsection
Step: 12 Create a pdf.blade.php file to design our pdf
You can create the new DOMPDF instance and load an HTML string, file, or blade view name. You can save it to the file or stream. Inside the views folder, create one pdf.blade.php file and add the following code.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> {{$show->show_name}} {{$show->series}} {{$show->lead_actor}} </body> </html>
Step: 13 Write a controller function to download the PDF
Write the following code inside the DisneyplusController.php file.
// DisneyplusController.php public function downloadPDF($id) { $show = Disneyplus::find($id); $pdf = PDF::loadView('pdf', compact('show')); return $pdf->download('disney.pdf'); }
Go to http://localhost:8000/disneyplus/list and click on the Download PDF link.
It downloads the PDF file and opens it; you will see the data.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Great tutorial thanks!!
could it generate pdf out of tables and images?
here i am facing some problem when i am trying to use external css. can you help me how can i solve this problem?
Not working only page infinity loading but nothing else
I have updated the article in Laravel 11(which is announced earlier this month); you can try again.
Let me know if you are still facing any issues.
Hi Krunal, great tutorial!!
I´m just starting with Laravel and this was a super useful explanation
to me.
Thanks and keep helping people to leverage knowledge on this great framework
People like you make a great difference
Cheers
Mauricio
Thank for sharing keep continue…. Good luck
Well Done, Krunal! This was a very helpful tutorial.
Two small suggestions:
1. Why not include the “use PDF; ” directive in your DisneyplusController script, rather than as a sidenote?
2. It would save a few keystrokes to use “php artisan make:controller DisneyplusController -r” and lete the system insert the index, store and create functions.
its giv an error
Error : failed to open stream: No such file or directory in file
it is work
Hi Kunal,
could you please make a tutorial about creating a PDF with multiple pages?
Thanks!
Illegal string offset ‘hex’ this error occurred while create pdf file
I have updated the article in Laravel 11(which is announced earlier this month); you can try again.
Let me know if you are still facing any issues.