How to Create PDF File in Laravel 9?

Hello Dev, Today we are going to learn How to Create PDF File in Laravel 9. This tutorial will cover creating pdf file in laravel with example.

In this tutorial how to create pdf file in laravel 9?. We will learn how to generate PDF from HTML using the DomPDF library. We will use laravel 9 create pdf file using dompdf. In this tutorial, we will discuss about the Laravel 9 Export to PDF topic. This step by step tutorial allows you to explore the limitless opportunity if you are a newbie laravel developer. In general, PDF files are used to provide some information to the users.

You can generate a pdf file from a view using DomPDF. 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 per the requirement. After that, we will export this view as a PDF file.

Steps on How to Create PDF File in Laravel 9:

  • Step 1: Installing fresh new Laravel 9 Application
  • Step 2: Creating database and configurate .env file
  • Step 3: Installing DomPDF Package
  • Step 4: Creating Controller
  • Step 5: Creating Route
  • Step 6: Creating View File
  • Step 7: Testing
  • Step 8: Conclusion

Also Read: Laravel 9 Import Export Excel & CSV File to Database Example

Step 1: Installing fresh new Laravel 9 Application

First we are going to install a fresh new laravel 9 application. To install a laravel application run the following code in terminal.

composer create-project laravel/laravel example-app
cd example-app
Installing fresh new Laravel 9 Application
Installing fresh new Laravel 9 Application

Also Read: How to Upload Image in Laravel 9?

Step 2: Creating database and configurate .env file

After installing laravel application we are going to create a database and configurated it with laravel .env file. To create a database first visit phpmyadmin page and create a new database with name “example-app” (you can use whatever name you like).

Creating Database
Creating Database

Now after creating a database we are going to configurated it in laravel application which we had created earlier. Open the .env file from laravel application and update the database details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example-app
DB_USERNAME=root
DB_PASSWORD=
Configurate laravel .env file
Configurate laravel .env file

Step 3: Installing DomPDF Package

Next, we will install DomPDF package using following composer command, let’s run bellow command.

composer require barryvdh/laravel-dompdf

Also Read: Laravel 9 Form Validation With Error Messages

Step 4: Creating Controller

In this step, we will create PDFController with generatePDF() where we write code of generate pdf. so let’s create controller using bellow command.

php artisan make:controller PDFController

Now, update the code on 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 LaravelTuts.com',
            'date' => date('m/d/Y'),
            'users' => $users
        ]; 
            
        $pdf = PDF::loadView('myPDF', $data);
     
        return $pdf->download('laraveltuts.pdf');
    }
}
Creating Controller
Creating Controller

Now run the migration.

php artisan migrate
Running Migration - How to Create PDF File in Laravel 9
Running Migration

In PDFController, we also get users table data and display them into pdf file. so you can add some dummy data on the users table by using the following tinker command.

php artisan tinker
User::factory()->count(10)->create()
Creating Dummy Records for User table
Creating Dummy Records for User table

Also Read: Laravel 9 Remove Public from URL using htaccess

Step 5: Creating Route

Now, we are going to create our routes. Open routes from routes/web.php and add the following route as shown below.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PDFController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('generate-pdf', [PDFController::class, 'generatePDF']);
Creating Routes - How to Create PDF File in Laravel 9
Creating Routes

Also Read: Laravel 9 Get env Variable in Blade File Example

Step 6: Creating View File

In Last step, let’s create myPDF.blade.php (resources/views/myPDF.blade.php) for layout of pdf file and put following code.

resources/views/myPDF.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Create PDF File using DomPDF Tutorial - LaravelTuts.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</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.</p>
  
    <table class="table table-bordered">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
    </table>
</body>
</html>
Creating Blade File - How to Create PDF File in Laravel 9
Creating Blade File

Also Read: How to Use Inner Join In Laravel 9

Step 7: Testing

Now everything is done! we can now test our laravel application. First run the serve command on terminal as shown below.

php artisan serve

And open the following URL in any web browser.

http://127.0.0.1:8000/generate-pdf

After you visit this URL the PDF will be downloaded. You can see the preview of the PDF.

Previews:

How to Create PDF File in Laravel 9
How to Create PDF File in Laravel 9
How to Create PDF File in Laravel 9
How to Create PDF File in Laravel 9

Step 8: Conclusion

Today, We had learn How to Create PDF File in Laravel 9. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Laravel 9 User Roles and Permissions Tutorial Example

5 Comments

Leave a Reply