Hi guys! Ready for another tutorial? Have you ever heard that we can generate a PDF document including database table records
This is how to deal with PDF documents in Laravel. We have to take some external tools for this task.
Here we mainly use Laravel TCPDF library.

Step 1 - Create new laravel project

composer create-project laravel/laravel LaravelPDF

Step 2 - Migrate database

Open the project folder and edit database configuration files.

.env file


config/database.php file


Before database migration, we have something to do to avoid migration errors... In your project folder, open Http/Providers/AppServiceProvider.php file and replace its code with this.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Now open the database folder in the project folder and go into the folder called migrations. Then Delete the migration built for password resets. Edit the migration reserved for users. Replace this code.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Open a cmd and type this command to migrate database.
php artisan migrate

You will have the database tables now..

Now the database is ready for our task! But we have to upload some data to the database. So, go to PhpMyadmin and select the laravel_pdf database. Then import the SQL file include in my GitHub folder. It will upload some data to the database.
Move on for next step..

Step 3 - Install TCPDF Library into the project

As I mentioned at the beginning I will use TCPDF library to generate pdf fles. So we have to install it in the project. Open composer.json file and add this to require section.
"elibyy/tcpdf-laravel": "5.6.*",
Open another cmd and navigate into the project. Enter the following command to update composer.
composer update

Then open config/app.php file to do further configurations.
Place this code in providers section
Elibyy\TCPDF\ServiceProvider::class

Place this code in aliases section
'PDF' => Elibyy\TCPDF\Facades\TCPDF::class

Okay!!! Now we have fully installed TCPDF library! Move on guys!

Step 4 - Create a controller to add functionalities

Open the cmd and type the command to create a controller called UserController.
php artisan make:controller UserController

Add the index function to load the with users included in the database.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use PDF;

class UserController extends Controller
{
    public function index()
    {
     $users = User::all();
     return view('welcome', ['users' => $users]);
    }
}

Step 5 - Add Routes

Open routes/web.php and add this code lines.

Route::get('/', 'Usercontroller@index');

Route::get('/download', 'Usercontroller@savePDF');

Route::get('/viewpdf', 'Usercontroller@openPDF');



Step 6 - Modify the view file to load the front page

Edit the welcome blade file to integrate the styles and design. I use Bootstrap 4 to add styles.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel PDF</title>
        <!-- Bootstrap core CSS -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
        <style type="text/css">
            body{
                font-family: 'Lato', sans-serif;
            }
        </style>
    </head>
    <body>
        <div class="container" style="margin-top: 50px;">
            @if(count($users) > 0)
                    <h2 class="text-left">User List</h2><br>
                    <a href="/download" class="btn btn-success btn-sm">Download PDF</a>
                    <a href="/viewpdf" class="btn btn-primary btn-sm">Open PDF</a>
                    <br><br>
                    <table class="table table-bordered table-striped">
                        <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>
                @else
                    <br><h4 class="text-center">There are no users</h4>
                @endif 

        </div>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Bootstrap core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.min.js"></script>
    </body>
</html>

Open cmd and type php artisan serve. Then open web browser and type localhost:8000 to run the project. You will get this output view.
Now you have the view. You can see the two buttons to directly download the PDF and to open PDF via browser. But we haven't added the functionalities for these buttons. Routes have been created. Now it's time to include the logic for these buttons. Open UserController controller file to add the logic. We have to create two more functions!

Step 7 - Modify the controller 


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use PDF;

class UserController extends Controller
{
    public function index()
    {
     $users = User::all();
     return view('welcome', ['users' => $users]);
    }
    // this function opens the PDF in browser. If we want, we can downlod
    public function openPDF()
    {
        $users = User::orderBy('id','asc')->get();
        // usersPdf is the view that includes the downloading content
        $view = \View::make('usersPdf', ['users'=>$users]);
        $html_content = $view->render();
        // Set title in the PDF
        PDF::SetTitle("List of users");
        PDF::AddPage();
        PDF::writeHTML($html_content, true, false, true, false, '');
        // userlist is the name of the PDF downloading
        PDF::Output('userlist.pdf');    
    }
    // this function directly downloads the PDF. 
    public function savePDF()
    {
        $users = User::orderBy('id','asc')->get();
        $view = \View::make('usersPdf', ['users'=>$users]);
        $html_content = $view->render();
        PDF::SetTitle("List of users");
        PDF::AddPage();
        PDF::writeHTML($html_content, true, false, true, false, '');
        // D is the change of these two functions. Including D parameter will avoid 
        // loading PDF in browser and allows downloading directly
        PDF::Output('userlist.pdf', 'D');    
    }
}


Step 8 - Create the Downloading content

As the last step, we have to prepare the content in a view file called usersPdf since we included the view as usersPdf, in our controller functions. This view should include only the content. When it is rendered, only the basic HTML tags will be evaluated. The structure in the PDF is arranged using those basic tags. Do not include Bootstrap styles. They will not be recognized.

<div class="container">
    <h1>User list</h1>
    <table border="1" cellpadding="10" width="100%" style="margin-bottom: 100px;">
        <tr>
            <th width="20%">ID</th>
            <th width="40%">Name</th>
            <th width="40%">Email</th>
        </tr>
       @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
    </table>
</div>


WE HAVE COMPLETED THE TUTORIAL GUYS!

Now click on two buttons and see the outcome.. So, this is the way to generate PDFs easily using TCPDF library with Laravel. Laravel always provides easier ways to use libraries and packages. That's why I consider this as the best PHP framework..

Try this and give feedback. I'm looking forward for your comments...
Good Luck!




14 Comments

  1. Great Stuff Thanks

    ReplyDelete
  2. best tutorial Thank you so much for share your thoughts. I will definitely appreciate your ideas about Laravel Framework Development .

    Laravel Framework Development
    Aapthi Technologies USA
    Ecommerce Web Development Company

    ReplyDelete
  3. Laravel Development Company, Laravel is among the best PHP-based web app framework that is free and open-source. We offers a robust team of Laravel developers and programmers offering high-end and reliable solutions at highly-competitive rates. Contact us : +91-9806724185 or Contact@expresstechsoftwares.com

    ReplyDelete
  4. do it work for laravel version 5.8

    ReplyDelete
  5. how to save file into specific directory which is not available ?

    ReplyDelete
  6. Wow, this paragraph is pleasant, my younger sister is analyzing these kinds of things, thus I am going to tell her.

    ReplyDelete
  7. can you please make a tutorial on this but rather than getting all the data ,it only get data from an id?

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete