Skip to content

Instantly share code, notes, and snippets.

@estefanionsantos
Created April 19, 2025 04:55
Show Gist options
  • Save estefanionsantos/403ff7a27cba6b65067a3a36571adce0 to your computer and use it in GitHub Desktop.
Save estefanionsantos/403ff7a27cba6b65067a3a36571adce0 to your computer and use it in GitHub Desktop.
fpdf-tuto5-1
<?php
use Rubricate\Fpdf\FileFpdf;
class PDF extends FileFpdf
{
public function loadData($file)
{
$lines = file($file);
$data = [];
foreach($lines as $line){
$data[] = explode(';', trim($line));
}
return $data;
}
public function basicTable($header, $data)
{
foreach($header as $col){
$this->cell(40, 7, $col, 1);
}
$this->ln();
foreach($data as $row) {
foreach($row as $col){
$this->cell(40, 6, $col, 1);
}
$this->ln();
}
}
public function improvedTable($header, $data)
{
$w = array(40, 35, 40, 45);
for($i=0; $i < count($header); $i++){
$this->cell($w[$i], 7, $header[$i], 1, 0, 'C');
}
$this->ln();
foreach($data as $row){
$this->cell($w[0], 6, $row[0], 'LR');
$this->cell($w[1], 6, $row[1], 'LR');
$this->cell($w[2], 6, number_format($row[2]),'LR', 0, 'R');
$this->cell($w[3], 6, number_format($row[3]),'LR', 0, 'R');
$this->ln();
}
$this->cell(array_sum($w), 0, '', 'T');
}
public function fancyTable($header, $data)
{
$this->setFillColor(255,0,0);
$this->setTextColor(255);
$this->setDrawColor(128,0,0);
$this->setLineWidth(.3);
$this->setFont('','B');
$w = [40, 35, 40, 45];
for($i=0; $i < count($header); $i++){
$this->cell($w[$i], 7, $header[$i], 1, 0, 'C', true);
}
$this->ln();
$this->setFillColor(224, 235, 255);
$this->setTextColor(0);
$this->setFont('');
$fill = false;
foreach($data as $row){
$this->cell($w[0], 6, $row[0], 'LR', 0, 'L', $fill);
$this->cell($w[1], 6, $row[1], 'LR', 0, 'L', $fill);
$this->cell($w[2], 6, number_format($row[2]), 'LR', 0, 'R', $fill);
$this->cell($w[3], 6, number_format($row[3]), 'LR', 0, 'R', $fill);
$this->ln();
$fill = !$fill;
}
$this->cell(array_sum($w),0,'','T');
}
}
$header = ['Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)'];
$pdf = new PDF();
$data = $pdf->loadData('countries.txt');
$pdf->setFont('Arial','',14);
$pdf->addPage();
$pdf->basicTable($header,$data);
$pdf->addPage();
$pdf->improvedTable($header,$data);
$pdf->addPage();
$pdf->fancyTable($header,$data);
$pdf->output();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment