How to use FPDF in your Laravel App

From: tristan | Comments: 2

Creating a PDF on the fly is a big advantage of the FPDF library. You can use it for generating invoices, printable documentations or much more. It’s easy to use and for free. Here I will show you how to use FPDF in your Laravel application with a small example.

First install the FPDF package in your app:

$ composer require codedge/laravel-fpdf

Creating a PDF from your Controller:

<?php
namespace App\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Codedge\Fpdf\Fpdf\Fpdf;

class PDFController extends Controller
{
   private $fpdf;

    public function __construct()
    {
        
    }

    public function createPDF()
    {
        $this->fpdf = new Fpdf;
        $this->fpdf->AddPage("L", ['100', '100']);
        $this->fpdf->Text(10, 10, "Hello FPDF");       
        
        $this->fpdf->Output();
        exit;
    }
}

At the beginning add the FPDF Service Codedge\Fpdf\Fpdf\Fpdf to my controller. In the createPDF method I create the PDF with a page size of 100 x 100mm and added the text “Hello FPDF”. At the end I made an output of the PDF. After the output method you must exit your script, otherwise Laravel tries to render the page and you will get an error.

Add the Controller to your router in route/web.php:

Route::get('/pdf', 'PDFController@createPDF);

Now you can generate your PDF from yourapp.dev/pdf

For more FPDF functions visit the FPDF Website: http://www.fpdf.org/

2 responses to “How to use FPDF in your Laravel App”

  1. Manish P says:

    How can I export data in a pdf format using Fpdf package??
    In this article you have not shown it in connection with the database. So please give a guide.
    Thanks in advance.

    • tristan says:

      Hey Manish,

      you can use Fpdf like as usual. You can find many sample tutorials on http://www.fpdf.org/

      And for the database connection just use all Laravel gives you. Combine both and you will be happy.

Leave a Reply to tristan Cancel reply

Your email address will not be published. Required fields are marked *