Step 1: Install Laravel

I'm going to explain step by step from scratch so, we need to get fresh Laravel application using below command. So open your terminal or command prompt and run below command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install dompdf package

Generate pdf in Laravel is very simple and easy using dompdf. It is very efficient way to generate pdf.

composer require barryvdh/laravel-dompdf

After successfully install package, open config/app.php file and add service provider and alias:

'providers' => [
    Barryvdh\DomPDF\ServiceProvider::class,
],

'aliases' => [
    'PDF' => Barryvdh\DomPDF\Facade::class,
],

Step 3: Add route

routes/web.php:

Route::get('/pdf', [PdfController::class, 'generatePDF'])->name('generatePDF');

Step 4: Create controller

By running below command, we will create our PdfController:

php artisan make:controller PdfController

app/Http/Controllers/PdfController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PdfController extends Controller
{
    public function generatePDF() {
        $data = [
            'title' => 'Hello, World!',
            'date' => date('m/d/Y')
        ];

        $pdf = PDF::loadView('mypdf', $data);
        return $pdf->download('example-pdf.pdf');
    }
}

Step 5: Create view

resources/views/mypdf.blade.php:

<!DOCTYPE html>
<html>
    <head>
        <title>Generate-PDF</title>
    </head>
    <body>
        <h1>{{ $title }}</h1>
        <p>{{ $date }}</p>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
            cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
            proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
    </body>
</html>

visit:

http://localhost:8000/pdf