Ir al contenido principal

AJUSTAR TEXTO EN FPDF

SOLUCIÓN AL TEXTO SALTADO DE UNA CELDA DE LA LIBRERÍA FPDF.


El problema común que tenemos con la librería FPDF es esto cuando el texto es demasiado largo ocurre esto:

SOLUCIÓN.


Para solucionar esto, colocaremos el siguiente codigo. Este código es proporcionado por la propia comunidad de fpdf.org en la opción de su página principal llamada “Scripts”.

CODIGO

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

class PDF extends FPDF {

var $tablewidths;
var $footerset;

function _beginpage($orientation, $size) {
$this->page++;

// Resuelve el problema de sobrescribir una página si ya existe.
if(!isset($this->pages[$this->page])) 
$this->pages[$this->page] = '';
$this->state  =2;
$this->x = $this->lMargin;
$this->y = $this->tMargin;
$this->FontFamily = '';

// Compruebe el tamaño y la orientación.
if($orientation=='')
$orientation = $this->DefOrientation;
else
$orientation = strtoupper($orientation[0]);
if($size=='')
$size = $this->DefPageSize;
else
$size = $this->_getpagesize($size);
if($orientation!=$this->CurOrientation || $size[0]!=$this->CurPageSize[0] || $size[1]!=$this->CurPageSize[1])
{

// Nuevo tamaño o la orientación
if($orientation=='P')
{
$this->w = $size[0];
$this->h = $size[1];
}
else
{
$this->w = $size[1];
$this->h = $size[0];
}
$this->wPt = $this->w*$this->k;
$this->hPt = $this->h*$this->k;
$this->PageBreakTrigger = $this->h-$this->bMargin;
$this->CurOrientation = $orientation;
$this->CurPageSize = $size;
}
if($orientation!=$this->DefOrientation || $size[0]!=$this->DefPageSize[0] || $size[1]!=$this->DefPageSize[1])
$this->PageSizes[$this->page] = array($this->wPt, $this->hPt);
}

function Footer() {

// Compruebe si pie de página de esta página ya existe ( lo mismo para Header ( ) )
if(!isset($this->footerset[$this->page])) {
$this->SetY(-15);

// Numero de Pagina
$this->Cell(0,10,'Pagina '.$this->PageNo().'/{nb}',0,0,'C');

// Conjunto Footerset
$this->footerset[$this->page] = true;
}
}

function morepagestable($datas, $lineheight=13) {
// Algunas cosas para establecer y ' recuerdan '
$l = $this->lMargin;
$startheight = $h = $this->GetY();
$startpage = $currpage = $maxpage = $this->page;

// Calcular todo el ancho
$fullwidth = 0;
foreach($this->tablewidths AS $width) {
$fullwidth += $width;
}

// Ahora vamos a empezar a escribir la tabla
foreach($datas AS $row => $data) {
$this->page = $currpage;

// Escribir los bordes horizontales
$this->Line($l,$h,$fullwidth+$l,$h);

// Escribir el contenido y recordar la altura de la más alta columna
foreach($data AS $col => $txt) {
$this->page = $currpage;
$this->SetXY($l,$h);
$this->MultiCell($this->tablewidths[$col],$lineheight,$txt);
$l += $this->tablewidths[$col];

if(!isset($tmpheight[$row.'-'.$this->page]))
$tmpheight[$row.'-'.$this->page] = 0;
if($tmpheight[$row.'-'.$this->page] < $this->GetY()) {
$tmpheight[$row.'-'.$this->page] = $this->GetY();
}
if($this->page > $maxpage)
$maxpage = $this->page;
}

// Obtener la altura estábamos en la última página utilizada
$h = $tmpheight[$row.'-'.$maxpage];

//Establecer el "puntero " al margen izquierdo
$l = $this->lMargin;

// Establecer el "$currpage en la ultima pagina
$currpage = $maxpage;
}

// Dibujar las fronteras
// Empezamos a añadir una línea horizontal en la última página
$this->page = $maxpage;
$this->Line($l,$h,$fullwidth+$l,$h);
// Ahora empezamos en la parte superior del documento
for($i = $startpage; $i <= $maxpage; $i++) {
$this->page = $i;
$l = $this->lMargin;
$t  = ($i == $startpage) ? $startheight : $this->tMargin;
$lh = ($i == $maxpage)   ? $h : $this->h-$this->bMargin;
$this->Line($l,$t,$l,$lh);
foreach($this->tablewidths AS $width) {
$l += $width;
$this->Line($l,$t,$l,$lh);
}
}
// Establecerlo en la última página , si no que va a causar algunos problemas
$this->page = $maxpage;
}
}
?>
---------------------------------------------------------------------------------------

 Index.php

---------------------------------------------------------------------------------------
<?php

include('../Conexion.php');

require("fpdf.php");

$pdf = new PDF('L','pt');
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 8);
$pdf->Image('../imagenes/imajen.png' , 20 ,15, 50 , 50,'PNG');
$pdf->Cell(45, 10, '', 0);
$pdf->SetFont('Arial', '', 8);
$pdf->Cell(650, 35, '"ejemplo"',0);
$pdf->Cell(30, 35, 'Fecha: '.date('d-m-Y').'', 0);
$pdf->Ln(30);
$pdf->Cell(250, 10, '', 0);
$pdf->SetFont('Arial', 'B', 13);
$pdf->Cell(300,35,'Ejemplo Fpdf',0);
$pdf->Ln(35);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(100, 35, 'NOTA: ejemplo basico', 0);
$pdf->Ln(35);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(30, 13, 'ITEM', 1);
$pdf->Cell(215, 13, 'DESCRIPCION', 1);

$pdf->Ln(13);
$pdf->SetFont('Arial', '', 8);
$pdf->tablewidths = array(30,215);

$resultado=mysql_query("SELECT A.Descripcion 
FROM libro A, usuario B, prestamos D
WHERE B.IdUsuario = D.IdUsuario
AND A.IdLibro = D.IdLibro
AND D.Fecha_Maxima_De_Devolucion < '".$fecha."' and D.Fecha_De_Devolucion = '".$fecha1."'");
if(mysql_num_rows($resultado)>0)
{
$item = 0;


while($fila=mysql_fetch_array($resultado)){
$item = $item+1;
$b=$fila['Descripcion'];


$data[] = array(utf8_decode($item),utf8_decode($b));

}

$pdf->morepagestable($data);

$pdf->Output()

}

?>


Comentarios

Unknown dijo…
amigo el ejemplo funsiona muy bien! lo que necesito! pero no se como agregar mas columnas me da error! agradeceria tu ayuda!
Xedrik dijo…
Gracias!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
eli dijo…
Ever Meraz tendrias que revisar tu código detalladamente, seria bueno verlo tu código y en cual linea te bota el error.
Silvio Ramírez dijo…
Gracias! Pero donde debe ir cada uno de los archivos? El primero le agrega algunas cosas al principal de fpdf, pero el segundo llama solo a la libreria fpdf, mas no a las modificaciones?
Unknown dijo…
PARA AGREGAR MÁS COLUMNAS.
Hay que modificar la línea $pdf->tablewidths = array(30,215); actualmente hay dos columnas para agregar otra quedaría así $pdf->tablewidths = array(30,215,30);

y también hay que modificar:
$b=$fila['Descripcion'];
$c=$fila['Nueva Columna'];


$data[] = array(utf8_decode($item),utf8_decode($b),utf8_decode($c)); y listo. Así me funciono.

Muchas gracias por compartir el Código y explicarlo me sirvió muchísimo, de verdad se lo agradezco mucho.
eli dijo…
Exacto!! Geraldine Garcia Corredor
wmcfly dijo…
como podría centrar el texto ya ajustado en lugar de que me lo ponga alineado a la izquierda?
Me sale el siguiente error
Fatal error: Cannot declare class PDF, because the name is already in use in
Ignacio dijo…
mis registros son de 2 hojas cuando sobrepasa la primera hoja hay un error se pierden los datos es como que siguiera imprimiendo en el espacio de hoja y hoja no respeta el footer
eso como lo arreglaron?
Unknown dijo…
Gracias por el aporte, me pueden apoyar, al momento de realizar la consulta si es muy grande se pasa a la siguiente pagina, como le hago para controlar el salto de pagina para que imprima los encabezados y después continue con los datos de la consulta. Saludos
nihon academy dijo…
logre solucionar el problema de saltos de paginas en las tablas, mi problema era que al pasar rellenar mas de dos paginas la estructura de la tabla se perdía y las verticales desaparecían o no seguían la continuidad, aquí dejo la función modificada:

function morepagestable($datas, $lineheight = 13)
{
// Algunas cosas para establecer y ' recuerdan '
$l = $this->lMargin;
$startheight = $h = $this->GetY();
$startpage = $currpage = $maxpage = $this->page;

// Calcular todo el ancho
$fullwidth = 0;
foreach ($this->tablewidths as $width) {
$fullwidth += $width;
}

// Ahora vamos a empezar a escribir la tabla
foreach ($datas as $row => $data) {

$this->page = $currpage;
// Escribir los bordes horizontales
$this->Line($l, $h, $fullwidth + $l, $h);

if($this->GetY() > ($this->GetPageHeight() - 50)){
$this->AddPage('Portrait', 'Legal');
$h = $this->GetY();
$currpage = $this->page;
$this->Line($l, $h, $fullwidth + $l, $h);
}

// Escribir el contenido y recordar la altura de la más alta columna
foreach ($data as $col => $txt) {
$this->page = $currpage;
$this->SetXY($l, $h);
$this->MultiCell($this->tablewidths[$col], $lineheight, $txt,0,"C");
$l += $this->tablewidths[$col];

if (!isset($tmpheight[$row . '-' . $this->page]))
$tmpheight[$row . '-' . $this->page] = 0;
if ($tmpheight[$row . '-' . $this->page] < $this->GetY()) {
$tmpheight[$row . '-' . $this->page] = $this->GetY();
}
if ($this->page > $maxpage)
$maxpage = $this->page;

}

// VERTICAL LINE FOR EACH COLUMN
$th_h = $this->lMargin;
foreach ($data as $col => $txt) {
$th_h += $this->tablewidths[$col];
$this->Line($th_h , $h, $th_h, $tmpheight[$row . '-' . $maxpage]);
}
// INITIAL VERTICAL LINE
$this->Line($this->lMargin, $h, $this->lMargin, $tmpheight[$row . '-' . $maxpage]);
// FINAL VERTICAL LINE
$this->Line($l, $h, $l, $tmpheight[$row . '-' . $maxpage]);

// Obtener la altura estábamos en la última página utilizada
$h = $tmpheight[$row . '-' . $maxpage];

//Establecer el "puntero " al margen izquierdo
$l = $this->lMargin;

// Establecer el "$currpage en la ultima pagina
$currpage = $maxpage;


}

// Dibujar las fronteras
// Empezamos a añadir una línea horizontal en la última página
$this->page = $maxpage;
$this->Line($l, $h, $fullwidth + $l, $h);
// Ahora empezamos en la parte superior del documento
for ($i = $startpage; $i <= $maxpage; $i++) {
$this->page = $i;
$l = $this->lMargin;
$t = ($i == $startpage) ? $startheight : $this->tMargin;
$lh = ($i == $maxpage) ? $h : $this->h - $this->bMargin;
//$this->Line($l, $t, $l, $lh);
for ($i= 0; $i < count($this->tablewidths); $i++) {
$l += $this->tablewidths[$i];
//$this->Line($l, $t, $l, $lh);
}
}
// Establecerlo en la última página , si no que va a causar algunos problemas
$this->page = $maxpage;
}

agregue un if al principio del foreach $row que hace un salto de pagina al llegar al margen de la pagina indicado (NOTA: cambiar el valor asignado en el if a gusto, en mi caso 50)