Laravel 11 Apexcharts Example Tutorial

             PDF is one of the most commonly used document formats today. Most web applications include a feature to generate PDFs for invoices, receipts, reports, and more. This blog will guide you on generating PDF files using TCPDF in Laravel 11 and help you add this functionality to your future projects.

Laravel 11 DomPdf : Generate Simple Invoice PDF from HTML using dompdf In Laravel 11
             PDF is one of the most commonly used document formats today. Most web applications include a feature to generate PDFs for invoices, receipts, reports, and more. This blog will guide you on generating PDF files using TCPDF in Laravel 11 and help you add this functionality to your future projects.

Table Of Content

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

TCPDF is a well-established library with comprehensive documentation. Here’s a tutorial on generating PDFs using TCPDF in Laravel 11.

2 Introduction

TCPDF is a well-established library with comprehensive documentation. Here’s a tutorial on generating PDFs using TCPDF in Laravel 11.

3 Create / Install a Laravel Project

3 Create / Install a Laravel Project

3.1 Install Laravel Project

Ensure Composer is installed. Run:

composer create-project laravel/laravel laravel11-dompdf-app

Then navigate to your project:

cd laravel11-dompdf-app

3.1 Install Laravel Project

Ensure Composer is installed. Run:

composer create-project laravel/laravel laravel11-pdf-app

Then navigate to your project:

cd laravel11-pdf-app

3.2 Configure MySql Database

To store payment data, access the .env file to define database credentials:

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

3.2 Configure MySql Database

To store payment data, access the .env file to define database credentials:

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

4 Install the DomPdf Library

To install Dompdf in Laravel 11, use Composer:

composer require barryvdh/laravel-dompdf

4 Install the TCPDF Library

To install TCPDF in Laravel 11, use Composer:

composer require elibyy/tcpdf-laravel

5 Create A Model and Migration

To create a migration for the order table:

    php artisan make:migration create_order_table

Add the following fields:
    
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('order', function (Blueprint $table) {
            $table->id();
            $table->string('order_ref');
            $table->string('order_invoice');
            $table->string('customer_first_name');
            $table->string('customer_last_name');
            $table->string('customer_address');
            $table->string('customer_company');
            $table->string('amount');
            $table->string('order_status');
            $table->timestamps();
        });
        Schema::create('orderitems', function (Blueprint $table) {
            $table->id();
            $table->string('order_id');
            $table->string('product_name');
            $table->string('item_price');
            $table->string('quantity');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('order');
        Schema::dropIfExists('orderitems');
    }
};

Run the migration:

php artisan migrate

Create the Order model in app/Models/Order.php:

php artisan make:model Order

    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orders';
}


Create the OrderItem model in app/Models/Orderitem.php:

php artisan make:model Orderitem

    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Orderitem extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orderitems';
}


5 Create A Model and Migration

To create a migration for the order table:

    php artisan make:migration create_order_table

Add the following fields:
    
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('order_ref');
            $table->string('order_invoice');
            $table->string('customer_first_name');
            $table->string('customer_last_name');
            $table->string('customer_address');
            $table->string('customer_company');
            $table->string('amount');
            $table->string('order_status');
            $table->timestamps();
        });
        Schema::create('orderitems', function (Blueprint $table) {
            $table->id();
            $table->string('order_id');
            $table->string('product_name');
            $table->string('item_price');
            $table->string('quantity');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('orders');
        Schema::dropIfExists('orderitems');
    }
};

Run the migration:

php artisan migrate

Create the Order model in app/Models/Order.php:

php artisan make:model Order

    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orders';
}


Create the OrderItem model in app/Models/Orderitem.php:

php artisan make:model Orderitem

    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Orderitem extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'orderitems';
}


6 Create Controller ( PdfController )

Create Controller PdfController:

php artisan make:controller PdfController

Within this controller, implement the index() and invoice() methods:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Orderitem;
use PDF;

class PdfController extends Controller
{
    public function index()
    {
       $orders = Order::get();
        return view('index',compact('orders'));
    }

    public function invoice($id)
    {
        $order=new Order;
        $orderitem=new Orderitem;
        $data = [
            'order' => $order->find($id),
            'orderitems' => $orderitem->where("order_id",$id)->get(),
        ];
        $pdf = PDF::loadView('invoice', $data);
        return $pdf->download('invoice.pdf');
    }
}
?>

6 Create Controller ( PdfController )

Create Controller PdfController:

php artisan make:controller PdfController

Within this controller, implement the index() and invoice() methods:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Orderitem;
use Elibyy\TCPDF\Facades\TCPDF;

class PdfController extends Controller
{
    public function index()
    {
       $orders = Order::get();
        return view('index',compact('orders'));
    }

    public function invoice($id)
    {

        $filename='invoice.pdf';

        $order=new Order;
        $orderitem=new Orderitem;

        $data = [
            'order' => $order->find($id),
            'orderitems' => $orderitem->where("order_id",$id)->get(),
        ];

        //return view('socialshare', compact('shareButtons', 'posts'));
        $html = view()->make('invoice', $data)->render();
      //  $html = view('invoice',$data);

		$pdf = new TCPDF('L', PDF_UNIT, 'A5', true, 'UTF-8', false);

		//$pdf::SetCreator(PDF_CREATOR);
		$pdf::SetAuthor('Get Sample Code');
		$pdf::SetTitle('Invoice');
		$pdf::SetSubject('Invoice');

		$pdf::setPrintHeader(false);
		$pdf::setPrintFooter(false);

		$pdf::addPage();

		// output the HTML content
		$pdf::writeHTML($html, true, false, true, false, '');
		//line ini penting
		//$this->response->setContentType('application/pdf');
		//Close and output PDF document
		$pdf::Output(public_path($filename), 'I');

        return response()->download(public_path($filename));
    }
}
?>

7 Define a Route

Add the following routes in routes/web.php:

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

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

Route::get('orders', [PdfController::class, 'index']);
Route::get('invoicepdf/{id}', [PdfController::class, 'invoice']);

7 Define a Route

Add the following routes in routes/web.php:

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

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

Route::get('orders', [PdfController::class, 'index']);
Route::get('invoicepdf/{id}', [PdfController::class, 'invoice']);

8 Create Blade File

Order List (index.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataTables with Laravel 11</title>
     <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>Order List</h1>
        <table id="orderTable" class="table table-bordered ">
            <thead>
            <tr>
                    <th scope="col">Order Ref</th>
                    <th scope="col" class="text-right">Amount</th>
                    <th scope="col" class="text-right">Order Status</th>
                    <th scope="col" class="text-right">Download Invoice</th>
                </tr>
            </thead>
            <tbody>
                
                 @foreach($orders as $order)
            <tr>
                    <td>{{ $order->order_ref }}</td>
                    <td>{{ $order->amount }}</td>
                    <td>{{ $order->order_status }}</td>
                    <td>
                    <a target="_blank"
                        title="Generate Invoice"
                        href="invoicepdf/{{ $order->id }} ">
                        
                        {{ $order->order_invoice }} 
                </a>
                    </td>
                </tr>
                @endforeach       
               
            </tbody>
        </table>
    </div>

    <script>
        $(document).ready(function() {
            $('#orderTable').DataTable({});
        });
    </script>
</body>
</html>

Invoice Template (invoice.blade.php)
    
    <!DOCTYPE html>
<html>
<head>
    <title>Generate Dynamic PDFs in Laravel with DomPDF - GetSampleCode.com</title>
<style>
.table-bordered {
    border: 1px solid #ccc;
    border-spacing: 0px;
}
.table-bordered td,
.table-bordered th {
    border: 1px solid #ccc;
    padding:5px;
}
@page {

margin: 100px 25px;

}



header {

position: fixed;

top: -60px;

left: 0px;

right: 0px;

height: 50px;

font-size: 20px !important;

background-color: #000;

color: white;

text-align: center;

line-height: 35px;

}



footer {

position: fixed; 

bottom: -60px; 

left: 0px; 

right: 0px;

height: 50px; 

font-size: 20px !important;

background-color: #000;

color: white;

text-align: center;

line-height: 35px;

}
footer:after {
   content:"Page No - " counter(page);
}

    </style>
</head>
<body>
<header>

Welcome to Get Sample Code

</header>



<!-- Define Footer Block -->

<footer>
</footer>
<div style="font-size:24px; color:'#dddddd'; text-align:center "><i>Invoice</i></div>
<hr>
		<table class="table" width="100%">
            <tr>
                <td><b>Invoice:</b> # {{ $order->order_invoice }}</td>
                <td><b>Receiver:</b></td>
            </tr>
            <tr>
                <td><b>Date:</b> {{ \Carbon\Carbon::parse($order->order_at)->format('Y-m-d')  }} </td>
                <td>{{ $order->customer_first_name }} {{ $order->customer_last_name }} <br> {{ $order->customer_company }}</td>
            </tr>
           
            <tr>
            <td></td>
            <td >{{ $order->customer_address }}</td>
            </tr>
        </table>
		<hr>
        <table class="table table-bordered table-striped" width="100%" >
         <thead>
            <tr>
                <th>Item Description</th>
                <th>Price ($)</th>
                <th>Quantity</th>
                <th>Subtotal ($)</th>
            </tr>
        </thead>
    @php($total = 0);
    @foreach($orderitems as $item)
    @php($price = $item->item_price*$item->quantity)
    @php($total += $price)
    <tr> 
        <td>{{ $item->product_name }}</td>
        <td>{{ number_format($item->item_price, 2) }}</td>
        <td>{{ $item->quantity}}</td>
        <td style="text-align:right;">{{ number_format($price, 2) }}</td>
    </tr>
               @endforeach            
    <tr>
        <td colspan="3" style="text-align:right;">Total ($)</td>
        <td style = "text-align:right;">{{ number_format($total, 2) }}</td>
    </tr>
    </table>
    
  
</body>
</html>
    

8 Create Blade File

Order List (index.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo Invoice List in  Laravel 11</title>
     <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>Order List</h1>
        <table id="orderTable" class="table table-bordered ">
            <thead>
            <tr>
                    <th scope="col">Order Ref</th>
                    <th scope="col" class="text-right">Amount</th>
                    <th scope="col" class="text-right">Order Status</th>
                    <th scope="col" class="text-right">Download Invoice</th>
                </tr>
            </thead>
            <tbody>
                
                 @foreach($orders as $order)
            <tr>
                    <td>{{ $order->order_ref }}</td>
                    <td>{{ $order->amount }}</td>
                    <td>{{ $order->order_status }}</td>
                    <td>
                    <a target="_blank"
                        title="Generate Invoice"
                        href="invoicepdf/{{ $order->id }} ">
                        
                        {{ $order->order_invoice }} 
                </a>
                    </td>
                </tr>
                @endforeach       
               
            </tbody>
        </table>
    </div>

    <script>
        $(document).ready(function() {
            $('#orderTable').DataTable({});
        });
    </script>
</body>
</html>

Invoice Template (invoice.blade.php)
    
    <!DOCTYPE html>
<html>
<head>
    <title>Generate Dynamic PDFs in Laravel with DomPDF - GetSampleCode.com</title>
<style>
.table-bordered {
    border: 1px solid #ccc;
    border-spacing: 0px;
}
.table-bordered td,
.table-bordered th {
    border: 1px solid #ccc;
    padding:5px;
}

    </style>
</head>
<body>
<div style="font-size:24px; color:'#dddddd'; text-align:center "><i>Invoice</i></div>
<hr>
		<table class="table" width="100%">
            <tr>
                <td><b>Invoice:</b> # {{ $order->order_invoice }}</td>
                <td><b>Receiver:</b></td>
            </tr>
            <tr>
                <td><b>Date:</b> {{ \Carbon\Carbon::parse($order->order_at)->format('Y-m-d')  }} </td>
                <td>{{ $order->customer_first_name }} {{ $order->customer_last_name }} <br> {{ $order->customer_company }}</td>
            </tr>
           
            <tr>
            <td></td>
            <td >{{ $order->customer_address }}</td>
            </tr>
        </table>
		<hr>
        <table class="table table-bordered table-striped" width="100%" >
         <thead>
            <tr>
                <th>Item Description</th>
                <th>Price ($)</th>
                <th>Quantity</th>
                <th>Subtotal ($)</th>
            </tr>
        </thead>
    @php($total = 0);
    @foreach($orderitems as $item)
    @php($price = $item->item_price*$item->quantity)
    @php($total += $price)
    <tr> 
        <td>{{ $item->product_name }}</td>
        <td>{{ number_format($item->item_price, 2) }}</td>
        <td>{{ $item->quantity}}</td>
        <td style="text-align:right;">{{ number_format($price, 2) }}</td>
    </tr>
               @endforeach            
    <tr>
        <td colspan="3" style="text-align:right;">Total ($)</td>
        <td style = "text-align:right;">{{ number_format($total, 2) }}</td>
    </tr>
    </table>
    
  
</body>
</html>    

9 Folder Structure

9 Folder Structure

10 Run Laravel Server to Test the App

Start your server with:

php artisan serve

10 Run Laravel Server to Test the App

Start your server with:

php artisan serve

11 Conclusion

This example illustrates how to integrate TCPDF with Laravel 11 to generate PDFs, using Generating PDF in Laravel 11 and How to Generate PDF Using TCPDF in Laravel 11 techniques.

Reference URL

11 Conclusion

This example illustrates how to integrate TCPDF with Laravel 11 to generate PDFs, using Generating PDF in Laravel 11 and How to Generate PDF Using TCPDF in Laravel 11 techniques.

Reference URL

Tags