Generar PDF con PHP y FPDF: tabla de usuarios desde MySQL
Generar un reporte en PDF con PHP, MySQLi y FPDF
A continuación se presentan los archivos que conforman un sistema para consultar registros de usuarios en MySQL y generar un reporte en PDF con tabla estilizada utilizando la librería FPDF.
1. dbconfig.php
Archivo de configuración con los datos de conexión a la base de datos.
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "**********");
define("DB_NAME", "usuarios");
?>2. myDBC.php
Clase que gestiona la conexión con MySQLi y la obtención de los datos.
<?php
class myDBC {
public $mysqli = null;
public function __construct() {
include_once "dbconfig.php";
$this->mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($this->mysqli->connect_errno) {
echo "Error MySQLi: (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
exit();
}
$this->mysqli->set_charset("utf8");
}
public function __destruct() {
$this->CloseDB();
}
public function runQuery($qry) {
$result = $this->mysqli->query($qry);
return $result;
}
public function seleccionar_datos() {
$q = 'SELECT nombre, nick, correo FROM registro';
$result = $this->mysqli->query($q);
// Array asociativo que contendrá los datos
$valores = array();
if ($result->num_rows == 0) {
echo '<script type="text/javascript">
alert("Ningún registro");
</script>';
} else {
while ($row = mysqli_fetch_assoc($result)) {
// Se crea un arreglo asociativo
array_push($valores, $row);
}
}
// Regresa array asociativo
return $valores;
}
}
?>3. PDF.php
Clase que extiende FPDF para dibujar la cabecera y las filas de la tabla con celdas redondeadas y ajuste automático de texto.
<?php
require('fpdf/fpdf.php');
class PDF extends FPDF {
function cabeceraHorizontal($cabecera) {
$this->SetXY(10, 10);
$this->SetFont('Arial', 'B', 10);
$this->SetFillColor(2, 157, 116); // Fondo verde de celda
$this->SetTextColor(240, 255, 240); // Letra color blanco
$ejeX = 10;
foreach ($cabecera as $fila) {
$this->RoundedRect($ejeX, 10, 40, 7, 2, 'FD');
$this->CellFitSpace(40, 7, utf8_decode($fila), 0, 0, 'C');
$ejeX = $ejeX + 40;
}
}
function datosHorizontal($datos) {
$this->SetXY(10, 17);
$this->SetFont('Arial', '', 10);
$this->SetFillColor(229, 229, 229); // Gris tenue de cada fila
$this->SetTextColor(3, 3, 3); // Color del texto: negro
$bandera = false; // Para alternar el relleno
$ejeY = 17; // Posición inicial en Y
$letra = 'D'; // 'D' dibuja borde; 'FD' dibuja borde y rellena
foreach ($datos as $fila) {
// Por cada 3 CellFitSpace se crea un RoundedRect encimado.
// El parámetro $letra cambia en cada iteración para alternar D y FD.
// Solo la celda central lleva bordes izquierdo y derecho.
$this->RoundedRect(10, $ejeY, 120, 7, 2, $letra);
//$this->CellFitSpace(40, 7, utf8_decode($fila['id_user']), 0, 0, 'L');
$this->CellFitSpace(40, 7, utf8_decode($fila['nombre']), 0, 0, 'L');
$this->CellFitSpace(40, 7, utf8_decode($fila['nick']), 'LR', 0, 'L');
$this->CellFitSpace(40, 7, utf8_decode($fila['correo']), 0, 0, 'L');
$this->Ln();
// Condición ternaria que cambia el valor de $letra
($letra == 'D') ? $letra = 'FD' : $letra = 'D';
// Aumenta la siguiente posición de Y (X es fijo)
// Se suma 7 porque cada celda tiene esa altura
$ejeY = $ejeY + 7;
}
}
function tablaHorizontal($cabeceraHorizontal, $datosHorizontal) {
$this->cabeceraHorizontal($cabeceraHorizontal);
$this->datosHorizontal($datosHorizontal);
}
// **************************************************************************************************************
function CellFit($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '', $scale = false, $force = true) {
// Obtiene el ancho del texto
$str_width = $this->GetStringWidth($txt);
// Calcula la proporción para ajustar la celda
if ($w == 0) {
$w = $this->w - $this->rMargin - $this->x;
}
$ratio = ($w - $this->cMargin * 2) / $str_width;
$fit = ($ratio < 1 || ($ratio > 1 && $force));
if ($fit) {
if ($scale) {
// Escalado horizontal
$horiz_scale = $ratio * 100.0;
$this->_out(sprintf('BT %.2F Tz ET', $horiz_scale));
} else {
// Espaciado entre caracteres en puntos
$char_space = ($w - $this->cMargin * 2 - $str_width) / max($this->MBGetStringLength($txt) - 1, 1) * $this->k;
$this->_out(sprintf('BT %.2F Tc ET', $char_space));
}
// Anula la alineación del usuario (el texto ocupará la celda)
$align = '';
}
// Delega en el método Cell
$this->Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);
// Restablece el espaciado/escalado de caracteres
if ($fit) {
$this->_out('BT ' . ($scale ? '100 Tz' : '0 Tc') . ' ET');
}
}
function CellFitSpace($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '') {
$this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, false, false);
}
// Parche para trabajar también con texto CJK de doble byte
function MBGetStringLength($s) {
if ($this->CurrentFont['type'] == 'Type0') {
$len = 0;
$nbbytes = strlen($s);
for ($i = 0; $i < $nbbytes; $i++) {
if (ord($s[$i]) < 128) {
$len++;
} else {
$len++;
$i++;
}
}
return $len;
} else {
return strlen($s);
}
}
// **********************************************************************************************
function RoundedRect($x, $y, $w, $h, $r, $style = '', $angle = '1234') {
$k = $this->k;
$hp = $this->h;
if ($style == 'F') {
$op = 'f';
} elseif ($style == 'FD' || $style == 'DF') {
$op = 'B';
} else {
$op = 'S';
}
$MyArc = 4 / 3 * (sqrt(2) - 1);
$this->_out(sprintf('%.2f %.2f m', ($x + $r) * $k, ($hp - $y) * $k));
$xc = $x + $w - $r;
$yc = $y + $r;
$this->_out(sprintf('%.2f %.2f l', $xc * $k, ($hp - $y) * $k));
if (strpos($angle, '2') === false) {
$this->_out(sprintf('%.2f %.2f l', ($x + $w) * $k, ($hp - $y) * $k));
} else {
$this->_Arc($xc + $r * $MyArc, $yc - $r, $xc + $r, $yc - $r * $MyArc, $xc + $r, $yc);
}
$xc = $x + $w - $r;
$yc = $y + $h - $r;
$this->_out(sprintf('%.2f %.2f l', ($x + $w) * $k, ($hp - $yc) * $k));
if (strpos($angle, '3') === false) {
$this->_out(sprintf('%.2f %.2f l', ($x + $w) * $k, ($hp - ($y + $h)) * $k));
} else {
$this->_Arc($xc + $r, $yc + $r * $MyArc, $xc + $r * $MyArc, $yc + $r, $xc, $yc + $r);
}
$xc = $x + $r;
$yc = $y + $h - $r;
$this->_out(sprintf('%.2f %.2f l', $xc * $k, ($hp - ($y + $h)) * $k));
if (strpos($angle, '4') === false) {
$this->_out(sprintf('%.2f %.2f l', ($x) * $k, ($hp - ($y + $h)) * $k));
} else {
$this->_Arc($xc - $r * $MyArc, $yc + $r, $xc - $r, $yc + $r * $MyArc, $xc - $r, $yc);
}
$xc = $x + $r;
$yc = $y + $r;
$this->_out(sprintf('%.2f %.2f l', ($x) * $k, ($hp - $yc) * $k));
if (strpos($angle, '1') === false) {
$this->_out(sprintf('%.2f %.2f l', ($x) * $k, ($hp - $y) * $k));
$this->_out(sprintf('%.2f %.2f l', ($x + $r) * $k, ($hp - $y) * $k));
} else {
$this->_Arc($xc - $r, $yc - $r * $MyArc, $xc - $r * $MyArc, $yc - $r, $xc, $yc - $r);
}
$this->_out($op);
}
function _Arc($x1, $y1, $x2, $y2, $x3, $y3) {
$h = $this->h;
$this->_out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c ', $x1 * $this->k, ($h - $y1) * $this->k,
$x2 * $this->k, ($h - $y2) * $this->k, $x3 * $this->k, ($h - $y3) * $this->k));
}
} // FIN Class PDF
?>4. index.php
Archivo principal que obtiene los datos, construye el PDF y lo envía al navegador.
<?php
include_once('PDF.php');
include_once('myDBC.php');
$seleccion = new myDBC();
$datosReporte = $seleccion->seleccionar_datos();
$pdf = new PDF();
$pdf->AddPage();
$miCabecera = array('Nombre', 'Nick', 'Correo');
$pdf->tablaHorizontal($miCabecera, $datosReporte);
$pdf->Output(); // Salida al navegador
?>