> Manuales > Crear PDF en PHP con FPDF

Aprende a trabajar con tablas en documentos PDF que generamos con PHP y la librería FPDF, para mostrar cómodamente información tabulada.

Tablas en FPDF

Siguiendo con nuestro manual sobre FPDF vamos a ver como construir una tabla para el documento pdf. Abordaremos dos ejemplos de construcción de tablas, uno más sencillo que el otro, pero ambos igual de interesantes.

La primera tabla es muy sencillita, tan solo 2 lineas y la cabecera. Para ello vamos a pasarle un array con los nombres de cada celda, y después vamos a ir rellenando las columnas y las filas con la función CELL.

La función seria la siguiente:

functionTablaBasica($header)
   {
    //Cabecera
    foreach($header as $col)
    $this->Cell(40,7,$col,1);
    $this->Ln();
   
      $this->Cell(40,5,"hola",1);
      $this->Cell(40,5,"hola2",1);
      $this->Cell(40,5,"hola3",1);
      $this->Cell(40,5,"hola4",1);
      $this->Ln();
      $this->Cell(40,5,"linea ",1);
      $this->Cell(40,5,"linea 2",1);
      $this->Cell(40,5,"linea 3",1);
      $this->Cell(40,5,"linea 4",1);
   }

y la llamada a la función seria la siguiente:

//Creación del objeto de la clase heredada
$pdf=new PDF();
//Títulos de las columnas
$header=array('Columna 1','Columna 2','Columna 3','Columna 4');
$pdf->AliasNbPages();
//Primera página
$pdf->AddPage();
$pdf->SetY(65);
//$pdf->AddPage();
$pdf->Tabla Basica($header);

El siguiente ejemplo de tabla es algo más complicado ya que le vamos a dar colores a las filas y vamos a quitar los bordes inferiores de cala linea.

La función sería la siguiente:

function TablaColores($header)
{
    //Colores, ancho de línea y fuente en negrita
    $this->SetFillColor(255,0,0);
    $this->SetTextColor(255);
    $this->SetDrawColor(128,0,0);
    $this->SetLineWidth(.3);
    $this->SetFont('','B');
    //Cabecera
    
    for($i=0;$i<count($header);$i++)
    $this->Cell(40,7,$header[$i],1,0,'C',1);
    $this->Ln();
    //Restauración de colores y fuentes
    $this->SetFillColor(224,235,255);
    $this->SetTextColor(0);
    $this->SetFont('');
    //Datos
    $fill=false;
    
    $this->Cell(40,6,"hola",'LR',0,'L',$fill);
    $this->Cell(40,6,"hola2",'LR',0,'L',$fill);
    $this->Cell(40,6,"hola3",'LR',0,'R',$fill);
    $this->Cell(40,6,"hola4",'LR',0,'R',$fill);
    $this->Ln();
    $fill=true;
    $this->Cell(40,6,"col",'LR',0,'L',$fill);
    $this->Cell(40,6,"col2",'LR',0,'L',$fill);
    $this->Cell(40,6,"col3",'LR',0,'R',$fill);
    $this->Cell(40,6,"col4",'LR',0,'R',$fill);
    $fill=!$fill;
    $this->Ln();
    $this->Cell(160,0,'','T');
}

Todas las funciones que vemos ya están explicadas en otros artículos del manual de FPDF por lo que no entraremos en detalles.

Hemos establecido el color de relleno de las celdas, el color del texto, el grosor de los bordes y el tipo de letra. A continuación hemos creado la primera linea en rojo y la letra en negrita. Después asignamos otros colores para el relleno y la letra y vamos rellenando el resto de filas. Vamos colocando los bordes donde necesitamos y diciendo si la celda va rellena o no de color con la variable $fill.

Al final tenemos que añadir el borde de abajo del todo, para ello utilizamos la linea:

$this->Cell(160,0,'','T');

Que nos dice que la linea tiene que ser 160 de ancho, 0 de alto y mostrando solo el borde superior.

Os pongo el ejemplo completo con las dos tablas:

<?php
require('fpdf.php');

class PDF extends FPDF
{
//Cabecera de página
   function Header()
   {
    //Logo
    $this->Image("leon.jpg" , 10 ,8, 35 , 38 , "JPG" ,"http://www.mipagina.com");
    //Arial bold 15
    $this->SetFont('Arial','B',15);
    //Movernos a la derecha
    $this->Cell(80);
    //Título
    $this->Cell(60,10,'Titulo del archivo',1,0,'C');
    //Salto de línea
    $this->Ln(20);
      
   }
   
   //Pie de página
   function Footer()
   {
    //Posición: a 1,5 cm del final
    $this->SetY(-15);
    //Arial italic 8
    $this->SetFont('Arial','I',8);
    //Número de página
    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
   }
   //Tabla simple
   function TablaSimple($header)
   {
    //Cabecera
    foreach($header as $col)
    $this->Cell(40,7,$col,1);
    $this->Ln();
   
      $this->Cell(40,5,"hola",1);
      $this->Cell(40,5,"hola2",1);
      $this->Cell(40,5,"hola3",1);
      $this->Cell(40,5,"hola4",1);
      $this->Ln();
      $this->Cell(40,5,"linea ",1);
      $this->Cell(40,5,"linea 2",1);
      $this->Cell(40,5,"linea 3",1);
      $this->Cell(40,5,"linea 4",1);
   }
   
   //Tabla coloreada
function TablaColores($header)
{
//Colores, ancho de línea y fuente en negrita
$this->SetFillColor(255,0,0);
$this->SetTextColor(255);
$this->SetDrawColor(128,0,0);
$this->SetLineWidth(.3);
$this->SetFont('','B');
//Cabecera

for($i=0;$i<count($header);$i++)
$this->Cell(40,7,$header[$i],1,0,'C',1);
$this->Ln();
//Restauración de colores y fuentes
$this->SetFillColor(224,235,255);
$this->SetTextColor(0);
$this->SetFont('');
//Datos
   $fill=false;
$this->Cell(40,6,"hola",'LR',0,'L',$fill);
$this->Cell(40,6,"hola2",'LR',0,'L',$fill);
$this->Cell(40,6,"hola3",'LR',0,'R',$fill);
$this->Cell(40,6,"hola4",'LR',0,'R',$fill);
$this->Ln();
      $fill=!$fill;
      $this->Cell(40,6,"col",'LR',0,'L',$fill);
$this->Cell(40,6,"col2",'LR',0,'L',$fill);
$this->Cell(40,6,"col3",'LR',0,'R',$fill);
$this->Cell(40,6,"col4",'LR',0,'R',$fill);
$fill=true;
   $this->Ln();
   $this->Cell(160,0,'','T');
}

   
   
}

$pdf=new PDF();
//Títulos de las columnas
$header=array('Columna 1','Columna 2','Columna 3','Columna 4');
$pdf->AliasNbPages();
//Primera página
$pdf->AddPage();
$pdf->SetY(65);
//$pdf->AddPage();
$pdf->TablaSimple($header);
//Segunda página
$pdf->AddPage();
$pdf->SetY(65);
$pdf->TablaColores($header);
$pdf->Output();
?>

Con esto has aprendido a trabajar con tablas, para tabular información de manera fácilmente entendible en archivos PDF. Hemos aprendido las funciones para crear las tablas en PFDF con PHP. En el siguiente artículo abordaremos una práctica suplementaria de las tablas, que consiste en la maquetación del contenido por columnas en un archivo PDF.

Sara Alvarez

Equipo DesarrolloWeb.com

Manual