Search

How to create and download PDF in Laravel?

  • Share this:
post-title

Welcome guys, In this article Here, we will know how to create a PDF in laravel. Making a PDF file and download in Laravel is simple and easy. if you have question about laravel PDF then i will give simple example with solution.

Step 1: Building a New Application

You can ignore this step if you already have an application downloaded or else, run the following command to create a brand new laravel project.

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

After downloaded new application or already installed then moved our application directory run the following command or using your own method

cd laravel-pdf

Step 2: Configure Database Connection

In this type of project, we must give precedence to the database connection, generically it should be configured before getting started. Incorporate the following code in .env file with your database details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create a Model with Migration

Run this command to create a modal with migration 

php artisan make:model Item -m
<? php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    use HasFactory;
}

Step 4: Install DomPDF Package

Next, we will install DomPDF package using following composer command, let's run bellow command:

composer require barryvdh/laravel-dompdf

After install DomPDF package we have adding the service provider in config/app.php file and add the following code.

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

Step 5: Create Controller

Make a file in app/Http/Controllers/ItemController.php and add the given code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Item;
use Carbon\Carbon;
use PDF;

class ItemController extends Controller
{   
    /**
     * THis method use for exports as pdf files 
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function itemExportPdf(Request $request){
        $items = Item::query();
        $items = $items->get();
        $pdfObject = PDF::loadView('exports.items', compact('items'));
        // download PDF file with download method
        return $pdfObject->download('pdf_file.pdf');
    }
}

Step 6: Create View File

Create a view file in resources/view/exports/items.blade.php and add the following code.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
      <title>{{ config('app.name', 'Laravel') }}</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
       <style>
            @page { size: 10cm 20cm landscape; }
       </style>
   </head>
   <body>
        <div class="container">
            <table class="table table-bordered table-lg">
               <thead class="thead-dark">
                  <tr>
                     <th>Sr</th>
                     <th>Name</th>
                     <th>Serial Number</th>
                  </tr>
               </thead>
               <tbody>
                  @foreach($items as $key => $data)
                  <tr>
                     <td>{{$key + 1}}</td>
                     <td>{{$data->item_name}}</td>
                     <td>{{$data->item_serial_number}}</td>
                  </tr>
                  @endforeach
               </tbody>
            </table>
        </div>
   </body>
</html>

Step 7: Add Route

Open routes/web.php file and add the following route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ItemController;

Route::group(['prefix'=>'export/pdf'], function(){
     Route::get('/item', [ItemController::class, 'itemExportPdf'])->name('item.export.pdf');
});

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/export/pdf/item
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (51)