Foros del Web » Programando para Internet » PHP »

Ayuda con FPDF

Estas en el tema de Ayuda con FPDF en el foro de PHP en Foros del Web. Tengo el siguiente codigo PHP para crear un fichero pdf en el que se muestra un listado en una tabla que lee desde un fichero ...
  #1 (permalink)  
Antiguo 04/09/2007, 04:05
Avatar de SILVI85  
Fecha de Ingreso: julio-2007
Mensajes: 109
Antigüedad: 16 años, 8 meses
Puntos: 1
Ayuda con FPDF

Tengo el siguiente codigo PHP para crear un fichero pdf en el que se muestra un listado en una tabla que lee desde un fichero txt.
El problema es que no se como ajustar las celdas segun el contenido del texto, es decir, que si hay mucho texto se me sale de la celda y se pisa el texto uno con otro..

Manualmente si se hacerlo.. el problema es que tengo un foreach para leer y entonces las hace todas del mismo tamaño

Si alguien me echa una mano se lo agradeceria

Código PHP:
class PDF extends FPDF 

//Cargar los datos 
function LoadData($file)
{
    
//Leer las líneas del fichero
    
$lines=file($file);
    
$data=array();
    foreach(
$lines as $line)
        
$data[]=explode(';',chop($line));
    return 
$data;
}
function 
BasicTable($header,$data)
{

$this->SetFont('Arial','',14);
    
//Cabecera
      
  
$this->Cell(17);
    foreach(
$header as $col)
       
$this->Cell(30,15,$col,1,0,'C');

    
$this->Ln();
    
//Datos
    
foreach($data as $row)
    {   
$this->Cell(17);
        foreach(
$row as $col)
        {
    
$this->Cell(30,6,$col,1,0,'C');
    }
        
$this->Ln();
    }
}


//cabecera de datos
$header=array('Nº Registro','Artículo','F.Alta','F.Baja','Procedencia','Pertenencia','Ubicacion','Observ.');

$data=$pdf->LoadData('a.txt'); 
  #2 (permalink)  
Antiguo 04/09/2007, 08:31
Avatar de mauled  
Fecha de Ingreso: marzo-2005
Ubicación: Cd. de México.
Mensajes: 3.001
Antigüedad: 19 años, 1 mes
Puntos: 33
De acuerdo Re: Ayuda con FPDF

Cuando tu celda va a contener mucho texto te recomiendo que uses Multicell() en la página de fpdf en el tutorial ,"tutorial 3", viene un ejemplo de esta función.

Saludillos.
  #3 (permalink)  
Antiguo 05/09/2007, 04:32
Avatar de SILVI85  
Fecha de Ingreso: julio-2007
Mensajes: 109
Antigüedad: 16 años, 8 meses
Puntos: 1
Re: Ayuda con FPDF

Pero multicell me imprime saltos de linea cada vez que llega al final de la celda y yo no quiero eso.
  #4 (permalink)  
Antiguo 05/09/2007, 13:25
Avatar de SILVI85  
Fecha de Ingreso: julio-2007
Mensajes: 109
Antigüedad: 16 años, 8 meses
Puntos: 1
Pregunta Re: Ayuda con FPDF

He conseguido hacer esto pero me lo hace con datos que coge de un array aleatorio y yo quiero que los datos que ponga en la tabla sean de un archivo .txt

Este es le codigo mc_table.php:
Código PHP:
<?php
require('fpdf.php');

class 
PDF_MC_Table extends FPDF
{
var 
$widths;
var 
$aligns;

function 
SetWidths($w)
{
    
//Set the array of column widths
    
$this->widths=$w;
}

function 
SetAligns($a)
{
    
//Set the array of column alignments
    
$this->aligns=$a;
}

function 
Row($data)
{
    
//Calculate the height of the row
    
$nb=0;
    for(
$i=0;$i<count($data);$i++)
        
$nb=max($nb,$this->NbLines($this->widths[$i],$data[$i]));
    
$h=5*$nb;
    
//Issue a page break first if needed
    
$this->CheckPageBreak($h);
    
//Draw the cells of the row
    
for($i=0;$i<count($data);$i++)
    {
        
$w=$this->widths[$i];
        
$a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
        
//Save the current position
        
$x=$this->GetX();
        
$y=$this->GetY();
        
//Draw the border
        
$this->Rect($x,$y,$w,$h);
        
//Print the text
        
$this->MultiCell($w,5,$data[$i],0,$a);
        
//Put the position to the right of the cell
        
$this->SetXY($x+$w,$y);
    }
    
//Go to the next line
    
$this->Ln($h);
}

function 
CheckPageBreak($h)
{
    
//If the height h would cause an overflow, add a new page immediately
    
if($this->GetY()+$h>$this->PageBreakTrigger)
        
$this->AddPage($this->CurOrientation);
}

function 
NbLines($w,$txt)
{
    
//Computes the number of lines a MultiCell of width w will take
    
$cw=&$this->CurrentFont['cw'];
    if(
$w==0)
        
$w=$this->w-$this->rMargin-$this->x;
    
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
    
$s=str_replace("\r",'',$txt);
    
$nb=strlen($s);
    if(
$nb>and $s[$nb-1]=="\n")
        
$nb--;
    
$sep=-1;
    
$i=0;
    
$j=0;
    
$l=0;
    
$nl=1;
    while(
$i<$nb)
    {
        
$c=$s[$i];
        if(
$c=="\n")
        {
            
$i++;
            
$sep=-1;
            
$j=$i;
            
$l=0;
            
$nl++;
            continue;
        }
        if(
$c==' ')
            
$sep=$i;
        
$l+=$cw[$c];
        if(
$l>$wmax)
        {
            if(
$sep==-1)
            {
                if(
$i==$j)
                    
$i++;
            }
            else
                
$i=$sep+1;
            
$sep=-1;
            
$j=$i;
            
$l=0;
            
$nl++;
        }
        else
            
$i++;
    }
    return 
$nl;
}
}
?>
y ex.php:

Código PHP:
<?php
define
('FPDF_FONTPATH','font/');
require(
'mc_table.php');

function 
GenerateWord()
{
    
//Get a random word
    
$nb=rand(3,10);
    
$w='';
    for(
$i=1;$i<=$nb;$i++)
        
$w.=chr(rand(ord('a'),ord('z')));
    return 
$w;
}

function 
GenerateSentence()
{
    
//Get a random sentence
    
$nb=rand(1,10);
    
$s='';
    for(
$i=1;$i<=$nb;$i++)
        
$s.=GenerateWord().' ';
    return 
substr($s,0,-1);
}

$pdf=new PDF_MC_Table();
$pdf->Open();
$pdf->AddPage();
$pdf->SetFont('Arial','',14);
//Table with 20 rows and 4 columns
$pdf->SetWidths(array(30,50,30,40));
srand(microtime()*1000000);
for(
$i=0;$i<20;$i++)
    
$pdf->Row(array(GenerateSentence(),GenerateSentence(),GenerateSentence(),GenerateSentence()));
$pdf->Output();
?>
El ejemplo se puede ver aquí: http://www.fpdf.org/en/script/ex3.pdf

Como puedo hacerlo con datos obtenidos del archivo .txt? Gracias
  #5 (permalink)  
Antiguo 25/09/2008, 09:47
 
Fecha de Ingreso: febrero-2008
Ubicación: Cajamarca-Peru
Mensajes: 68
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Ayuda con FPDF

Código PHP:
<?php require_once('../Connections/kapla.php'); ?>
<?php
include("../funciones/funciones.php");
?>
<?php
define
('FPDF_FONTPATH','font/');
require(
'mc_table.php');
?>
<?
$colname_alq_equip 
"-1";
if (isset(
$_GET['id_alqui'])) {
 
$colname_alq_equip = (get_magic_quotes_gpc()) ? $_GET['id_alqui'] : addslashes($_GET['id_alqui']);
}
mysql_select_db($database_kapla$kapla);
$query_alq_equip sprintf("SELECT * FROM alquiler_equipo inner join equipo on alquiler_equipo.id_equipo=equipo.id_equipo INNER JOIN categoria_equipo on equipo.id_cate = categoria_equipo.id_cate inner join tipo_equipo on equipo.id_tipo = tipo_equipo.id_tipo inner join tarifa on alquiler_equipo.id_tarifa=tarifa.id_tarifa WHERE id_alqui = '%s'"$colname_alq_equip);
$alq_equip mysql_query($query_alq_equip$kapla) or die(mysql_error());
$row_alq_equip mysql_fetch_assoc($alq_equip);
$totalRows_alq_equip mysql_num_rows($alq_equip);
$pdf=new PDF_MC_Table();
$pdf->Open();
$pdf->AddPage();
//Table with 20 rows and 4 columns
$pdf->SetWidths(array(30,68,18,12,17,17,15,15));
$pdf->Titulo(array('Codigo','Equipo','Tarifa','Cant.','Costo','Subtotal','Movi.','Desmov.'));
do{
    
$ne"".strtoupper($row_alq_equip['nombre_tipo'])."";
    if (
$row_alq_equip['marca_equipo'] != '')
        
$ne.=  " ".$row_alq_equip['marca_equipo']."";
    if (
$row_alq_equip['modelo_equipo'] != '')
        
$ne.= ', Modelo: '.$row_alq_equip['modelo_equipo'];
    if (
$row_alq_equip['num_serie_equipo'] != '')
        
$ne.= ', Serie: '.$row_alq_equip['num_serie_equipo'];
    if (
$row_alq_equip['pot_equipo'] != '')
        
$ne.= ', Potencia: '.$row_alq_equip['pot_equipo'];
    if (
$row_alq_equip['marca_motor'] != '')
        
$ne .= ', Motor: '.$row_alq_equip['marca_motor'];
    if (
$row_alq_equip['diametro_equipo'] != '0')
        
$ne .= ', Diametro: '.$row_alq_equip['diametro_equipo'];
    if (
$row_alq_equip['accesorios_equipo'] != '')
        
$ne .= ', Accesorios: '.$row_alq_equip['accesorios_equipo'];
    if (
$row_alq_equip['combustible_equipo'] != '3')
        
$ne .= ', Combustible: '.combus($row_alq_equip['combustible_equipo']);
    
$subto $row_alq_equip['cantidad']*$row_alq_equip['costo_equipo'];
    
$pdf->Row(array($row_alq_equip['id_equipo'],$ne,$row_alq_equip['periodo_tarifa'],$row_alq_equip['cantidad'],$row_alq_equip['costo_equipo'],$subto,$row_alq_equip['costo_movi'],$row_alq_equip['costo_desmov']));
}while(
$row_alq_equip mysql_fetch_assoc($alq_equip));
$pdf->Output();
?>
con una consulta simplemente en el array pones los nombres de tus columnas, este es mi caso, prueba algo similar para el tuyo.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado




La zona horaria es GMT -6. Ahora son las 06:17.