Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Graficas con fpdf y jpgraph

Estas en el tema de Graficas con fpdf y jpgraph en el foro de PHP en Foros del Web. Buenas foro. Necesito de su ayuda estoy realizando un reporte de ventas donde necesito crear gráficas de para las ventas realizadas. El reporte ya lo ...
  #1 (permalink)  
Antiguo 23/04/2013, 09:54
Avatar de jandrogdz  
Fecha de Ingreso: julio-2012
Ubicación: public $Guadalajara
Mensajes: 397
Antigüedad: 11 años, 9 meses
Puntos: 12
Pregunta Graficas con fpdf y jpgraph

Buenas foro.

Necesito de su ayuda estoy realizando un reporte de ventas donde necesito crear gráficas de para las ventas realizadas.

El reporte ya lo tengo generado pero no se como incorporar jpgraph a fpdf para poder crear la gráfica. Encontré por la web un ejemplo que funciona pero como comento no se como incorporarlo a FPDF.

Para el reporte utilice esta clase:
Código PHP:
Ver original
  1. <?php
  2. require('fpdf.php');
  3.  
  4. class PDF_MC_Table extends FPDF
  5. {
  6.     var $widths;
  7.     var $aligns;
  8.    
  9.  
  10.     function SetWidths($w){
  11.         //Set the array of column widths
  12.         $this->widths=$w;
  13.     }
  14.  
  15.     function SetAligns($a){
  16.         //Set the array of column alignments
  17.         $this->aligns=$a;
  18.     }
  19.  
  20. function Row($data)
  21. {
  22.     //Calculate the height of the row
  23.     $nb=0;
  24.     for($i=0;$i<count($data);$i++)
  25.         $nb=max($nb,$this->NbLines($this->widths[$i],$data[$i]));
  26.     $h=6*$nb;
  27.     //Issue a page break first if needed
  28.     $this->CheckPageBreak($h);
  29.     //Draw the cells of the row
  30.     for($i=0;$i<count($data);$i++)
  31.     {
  32.         $w=$this->widths[$i];
  33.         $a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
  34.         //Save the current position
  35.         $x=$this->GetX();
  36.         $y=$this->GetY();
  37.         //Draw the border
  38.         $this->Rect($x,$y,$w,$h);
  39.         //Print the text
  40.         $this->MultiCell($w,6,$data[$i],0,$a);
  41.         //Put the position to the right of the cell
  42.         $this->SetXY($x+$w,$y);
  43.     }
  44.     //Go to the next line
  45.     $this->Ln($h);
  46. }
  47.  
  48. function CheckPageBreak($h)
  49. {
  50.     //If the height h would cause an overflow, add a new page immediately
  51.     if($this->GetY()+$h>$this->PageBreakTrigger)
  52.         $this->AddPage($this->CurOrientation);
  53. }
  54.  
  55. function NbLines($w,$txt)
  56. {
  57.     //Computes the number of lines a MultiCell of width w will take
  58.     $cw=&$this->CurrentFont['cw'];
  59.     if($w==0)
  60.         $w=$this->w-$this->rMargin-$this->x;
  61.     $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
  62.     $s=str_replace("\r",'',$txt);
  63.     $nb=strlen($s);
  64.     if($nb>0 and $s[$nb-1]=="\n")
  65.         $nb--;
  66.     $sep=-1;
  67.     $i=0;
  68.     $j=0;
  69.     $l=0;
  70.     $nl=1;
  71.     while($i<$nb)
  72.     {
  73.         $c=$s[$i];
  74.         if($c=="\n")
  75.         {
  76.             $i++;
  77.             $sep=-1;
  78.             $j=$i;
  79.             $l=0;
  80.             $nl++;
  81.             continue;
  82.         }
  83.         if($c==' ')
  84.             $sep=$i;
  85.         $l+=$cw[$c];
  86.         if($l>$wmax)
  87.         {
  88.             if($sep==-1)
  89.             {
  90.                 if($i==$j)
  91.                     $i++;
  92.             }
  93.             else
  94.                 $i=$sep+1;
  95.             $sep=-1;
  96.             $j=$i;
  97.             $l=0;
  98.             $nl++;
  99.         }
  100.         else
  101.             $i++;
  102.     }
  103.     return $nl;
  104. }
  105. }
  106. ?>

Y de ahí mando a llamar los métodos de FPDF:
Código PHP:
Ver original
  1. $pdf=new PDF_MC_Table('L','mm','A4');

Pero encontre esta clase para las graficas:
Código PHP:
Ver original
  1. class Reporte extends FPDF
  2. {
  3.     public function __construct($orientation='L', $unit='mm', $format='A4'){
  4.         parent::__construct($orientation, $unit, $format);
  5.     }
  6.    
  7.     public function gaficoPDF($datos = array(),$nombreGrafico = NULL,$ubicacionTamamo = array(),$titulo = NULL){
  8.         //construccion de los arrays de los ejes x e y
  9.         if(!is_array($datos) || !is_array($ubicacionTamamo)){
  10.             echo "los datos del grafico y la ubicacion deben de ser arreglos";
  11.         }
  12.         elseif($nombreGrafico == NULL){
  13.             echo "debe indicar el nombre del grafico a crear";
  14.         }
  15.         else{
  16.            #obtenemos los datos del grafico  
  17.           foreach ($datos as $key => $value){
  18.             $data[] = $value[0];
  19.             $nombres[] = $key;
  20.             $color[] = $value[1];
  21.            }
  22.            $x = $ubicacionTamamo[0];
  23.            $y = $ubicacionTamamo[1];
  24.            $ancho = $ubicacionTamamo[2];  
  25.            $altura = $ubicacionTamamo[3];  
  26.            #Creamos un grafico vacio
  27.           $graph = new PieGraph(600,400);
  28.            #indicamos titulo del grafico si lo indicamos como parametro
  29.           if(!empty($titulo)){
  30.             $graph->title->Set($titulo);
  31.            }  
  32.            //Creamos el plot de tipo tarta
  33.            $p1 = new PiePlot3D($data);
  34.            $p1->SetSliceColors($color);
  35.            #indicamos la leyenda para cada porcion de la tarta
  36.           $p1->SetLegends($nombres);
  37.            //Añadirmos el plot al grafico
  38.            $graph->Add($p1);
  39.            //mostramos el grafico en pantalla
  40.            $graph->Stroke("$nombreGrafico.png");
  41.            $this->Image("$nombreGrafico.png",$x,$y,$ancho,$altura);  
  42.   }
  43.  }
  44. }

Pero como hago para agregarlo a mi archivo para poder hacer el grafico.

De verdad les agradecería si me pudieran ayudar.

De antemano muchas gracias.
__________________
Lo imposible solo cuesta un poco mas
  #2 (permalink)  
Antiguo 23/04/2013, 10:39
Avatar de anacona16  
Fecha de Ingreso: marzo-2010
Ubicación: Bogota DC
Mensajes: 610
Antigüedad: 14 años, 1 mes
Puntos: 52
Respuesta: Graficas con fpdf y jpgraph

Hola, he tenido la misma necesidad y la he resuelto de la siguiente manera, creas el PDF de manera normal con FPDF, luego (para mostrarte rapidamente) creas la grafica en el mismo archivo (no es lo mas optimo) de la siguiente manera:

Código PHP:
Ver original
  1. // Create the graph. These two calls are always required
  2.   $graph = new Graph(270, 200, 'auto');
  3.   $graph->SetScale("textlin");
  4.  
  5.   $theme_class = new UniversalTheme;
  6.   $graph->SetTheme($theme_class);
  7.  
  8.   $graph->SetBox(false);
  9.  
  10.   $graph->ygrid->SetFill(false);
  11.   $graph->xaxis->SetTickLabels(array('PA-01', 'PA-02', 'PA-03', 'PA-04'));
  12.   $graph->yaxis->HideLine(false);
  13.   $graph->yaxis->HideTicks(false, false);
  14.  
  15.   // Create the bar plots
  16.   $b1plot = new BarPlot($data1y);
  17.  
  18.   // Create the grouped bar plot
  19.   $gbplot = new GroupBarPlot(array($b1plot));
  20.   // ...and add it to the graPH
  21.   $graph->Add($gbplot);
  22.  
  23.   $b1plot->SetColor('white');
  24.   $b1plot->SetFillColor('#C5C5C5');
  25.  
  26.   $graph->title->Set("Promedios por Periodo:");
  27.  
  28.   $nombreImagen = 'path-absouta/uploads/info/' . uniqid() . '.png';
  29.  
  30.   // Display the graph
  31.   $graph->Stroke($nombreImagen);
  32.  
  33.   //Aqui agrego la imagen que acabo de crear con jpgraph
  34.   $pdf->Image($nombreImagen, $pdf->GetX() + 140, $pdf->GetY() - 25, 40, 30);

Luego puedes borrar la imagen con
Código PHP:
Ver original 
__________________
Aprendiendo!!!
  #3 (permalink)  
Antiguo 23/04/2013, 10:47
Avatar de jandrogdz  
Fecha de Ingreso: julio-2012
Ubicación: public $Guadalajara
Mensajes: 397
Antigüedad: 11 años, 9 meses
Puntos: 12
Respuesta: Graficas con fpdf y jpgraph

Gracias por contestar anacona16 justamente lo acababa de hacer así tal cual me lo dices. Lo único que no encuentro es como cambiar el color de la gráfica de tarta.

Sabes como hacerlo
__________________
Lo imposible solo cuesta un poco mas

Etiquetas: fpdf, jpgraph
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.
Respuesta




La zona horaria es GMT -6. Ahora son las 11:32.