How to Generate PDF Using TCPDF 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.

Laravel 11 TCPDF : Generating PDF Files From Html Using TCPDF

Table Of Content

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.

3 Create / Install a Laravel Project

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=

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';
}


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']);

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 CodeIgniter 4</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>
                <?php
                foreach($orders as $order)
                {?>
            <tr>
                    <td><?php echo $order['order_ref'];?></td>
                    <td><?php echo $order['amount'];?></td>
                    <td><?php echo $order['order_status'];?></td>
                    <td>
                    <a target="_blank"
                        title="Generate Invoice"
                        href="invoicepdf/<?php echo $order['id'];?>">
                        <?php echo $order['order_invoice'];?>
                </a>
                    </td>
                </tr>
                <?php
                }?>
            </tbody>
        </table>
    </div>

    <script>
        $(document).ready(function() {
            $('#orderTable').DataTable({});
        });
    </script>
</body>
</html>
Invoice Template (invoice.blade.php)
    
    <html>
	<head>
		<title>Get Sample Code Codigniter 4 TCPDG Generation
	</head>
	<body>
		<div style="font-size:24px; color:'#dddddd' "><i>Invoice</i></div>
        <hr>
		<table style="line-height: 1.5;" border="0">
            <tr>
                <td><b>Invoice:</b> #<?php echo $order["order_invoice"]; ?></td>
                <td style="text-align:right;"><b>Receiver:</b></td>
            </tr>
            <tr>
                <td><b>Date:</b> <?php echo date('Y-m-d',strtotime($order["order_at"])); ?></td>
                <td style="text-align:right;"><?php echo $order["customer_first_name"] . ' ' . $order["customer_last_name"]; ?></td>
            </tr>
            <tr>
                <td><b>Payment Due:</b><?php echo date('Y-m-d',strtotime($order["order_at"].' + 10 days')); ?></td>
                 <td style="text-align:right;"><?php echo $order["customer_company"]; ?></td>
            </tr>
            <tr>
            <td></td>
            <td style="text-align:right;"><?php echo $order["customer_address"]; ?></td>
            </tr>
        </table>
		<hr>
		
        <div style="border-bottom:1px solid #000;">
        <table style="line-height: 2;">
            <tr style="font-weight: bold;border:1px solid #cccccc;background-color:#f2f2f2;">
                <td style="border:1px solid #cccccc;width:200px;">Item Description</td>
                <td style = "text-align:right;border:1px solid #cccccc;width:85px">Price ($)</td>
                <td style = "text-align:right;border:1px solid #cccccc;width:75px;">Quantity</td>
                <td style = "text-align:right;border:1px solid #cccccc;">Subtotal ($)</td>
            </tr>
<?php
$total = 0;
foreach($orderitems as $item)
{
    $price = $item["item_price"] * $item["quantity"];
    $total += $price;
    ?>
    <tr> <td style="border:1px solid #cccccc;"><?php echo $item["product_name"]; ?></td>
                    <td style = "text-align:right; border:1px solid #cccccc;"><?php echo number_format($item["item_price"], 2); ?></td>
                    <td style = "text-align:right; border:1px solid #cccccc;"><?php echo $item["quantity"]; ?></td>
                    <td style = "text-align:right; border:1px solid #cccccc;"><?php echo number_format($price, 2); ?></td>
               </tr>
<?php
}
?>
<tr style = "font-weight: bold;">
    <td></td><td></td>
    <td style = "text-align:right;">Total ($)</td>
    <td style = "text-align:right;"><?php echo number_format($total, 2); ?></td>
</tr>
</table></div>
	</body>
</html>
    

9 Folder Structure

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

Tags