Codeigniter 4 PDF Tutorial, generate pdfs with the integration of the FPDF library, using codeigniter version 4.1.8
FPDF Tutorial – Codeigniter 4 fpdf integration
To follow this tutorial it is necessary to have php version 8 installed, first check your installed version
php -v
Because if you use a lower version of codeigniter than 4.1.6 you will get the following error for incompatibility with php 8, strtolower(): Passing null to parameter #1 ($string) of type string is deprecated
This is the error when using codeigniter version 4.1.5 with php 8.1, you can learn more about error handling in codeigniter 4
It’s time to create a new project, we enter the following command
composer create-project codeigniter4/appstarter pdf_tuto
Now we download the library fpdf and copy the files to the following location nameProject/app/Libraries
Now you need to add the namespace App\Libraries; so that the class can be recognized
The next step is to automatically load the class for that add the path in the file nameProject/app/Config/Autoload.php , in the array, you can check this article Generate PDF in Codeigniter
public $classmap = [
"Fpdf" => APPPATH .'/Libraries/Fpdf.php'
];
Now add the following configuration in the file .env , to work in a state of development
CI_ENVIRONMENT = development
We define a route for our new method
$routes->get('/pdf', 'Home::pdf');
Now we add the following code to generate our pdf
namespace App\Controllers;
use App\Libraries\Fpdf;
class Home extends BaseController
{
public function index()
{
return view('welcome_message');
}
public function pdf()
{
$this->pdf = new fpdf();
$this->pdf->AddPage();
$this->pdf->AliasNbPages();
$this->pdf->SetTitle("OpenGisCRM Report Leads");
$this->pdf->SetLeftMargin(15);
$this->pdf->SetRightMargin(15);
$this->pdf->SetFillColor(200,200,200);
$this->pdf->SetFont('Arial', 'B', 9);
$this->pdf->SetWidths(array(40,40,40));
$this->pdf->Row(array('f name','l name','email'));
$this->pdf->Row(array('john','doe','admin@gmail.com'));
$this->pdf->Cell(40,5,'Total By Date:','TB',0,'L','1');
$this->pdf->Cell(40,5, date("d-m-y"),'B',0,'L',0);
$this->pdf->Cell(40,5,'By OpenGisCRM :','TB',0,'L','1');
$this->pdf->Cell(40,5, 'https://opengiscrm.com/','B',0,'L',0);
$this->pdf->Ln(5);
$this->pdf->Output("OpenGisCRM Report leads.pdf", 'D');
}
}
We go to the associated route where we download the pdf and open it showing the result
In addition to the fpdf library, there are other report libraries such as dompdf