Search code examples
codeignitercodeigniter-4

CodeIgniter: 4.0.3 FPDF - error Class 'FPDF' not found


I am trying to generate a PDF document from CodeIgniter: 4.0.3 using fpdf library. I have copied fpdf library in app/ThirdParty folder.

I have included library reference at the top of controller like this.

    <?php namespace App\Controllers\Purchase;

     namespace App\ThirdParty\fpdf;

     use CodeIgniter\Controller;

     use FPDF;

I have created a class in the controller to extend FPDF to include header and footers like this.

    class PDF extends FPDF
    {

    
       function Header()
       {
       }
    
    }

I generate the pdf like this.

       $pdf = new PDF();
       $pdf->AddPage();

When I run the application, I get this error.

Error Class 'FPDF' not found 114 class PDF extends FPDF

How to fix this?


Solution

  • You should checkout whatever your namespace in fpdf lib is. It looks like you're a bit confused about them and the use word

    Here's an example on how to load a lib which is under the app/ThirdParty folder :

    Your FPDF main class named FPDF.php :

    <?php
    
    // the path you need to follow to access your file
    namespace App\ThirdParty;
    
    class FPDF {
        
        public function __construct() {
            // do your things
        }
    }
    

    Your Controller named Foo.php :

    <?php
    
    namespace App\Controllers;
    
    // the namespace of the lib file + its class name
    use App\ThirdParty\FPDF;
    
    class Foo extends \CodeIgniter\Controller {
        
        public function myPDF() {
            $pdf = new FPDF();
        }
    }