Laravel

Laravel 6 Generate PDF File

Pinterest LinkedIn Tumblr

Step 1: Setup Laravel 6
We going to setup laravel 6 projects in our machine

laravel new laravel

Step 2: Install dompdf Package

we will install barryvdh/laravel-dompdf composer package by following composer command in your laravel 6 application.

we need to install barryvdh/laravel-dompdf composer package in our project.

composer require barryvdh/laravel-dompdf

After installation package, open config/app.php file and add service provider and alias.

config/app.php

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

Step 3: Add Controller
Create PDFController Controller using command and add code below
php artisan make:controller PDFController

app/Http/Controllers/PDFController.php

<?php
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use PDF;
  
class PDFController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function PDFgenerate()
    {
        $pdf = PDF::loadView('RealProgrammer');
  
        return $pdf->download('RealProgrammer.pdf');
    }
}

Step 4: Add Route

Now add within routes folder. open web.php and add a route.
routes/web.php

Route::get('pdf-generate','PDFController@PDFgenerate');

Step 5: Create View File

In the last step, let’s create RealProgrammer.blade.php(resources/views/RealProgrammer.blade.php) for the layout of a pdf file and put the following code:

resources/views/RealProgrammer.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>PDF Generator</title>
</head>
<body>
    <div>
        <h1>PDF Generator</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloremque, veniam saepe deserunt, expedita dicta ea esse est odit autem sed earum modi, eius distinctio numquam beatae at ab nostrum veritatis.</p>
    </div>
</body>
</html>

Step 6: Now run server command

php artisan serve