reportes tcpdf

254 views
Skip to first unread message

Jorge Haeger

unread,
Dec 3, 2013, 6:50:58 PM12/3/13
to cakep...@googlegroups.com
hola a todos tengo una gran duda y me explicare bien antes que nada, tengo una tabla EMPLEADOS de la cual en su controlador cree la siguiente funcion:

 function viewPdf($id = null){
        if (!$id){
            $this->Session->setFlash('Id inválido para obtener pdf');
            $this->redirect(array('action'=>'index'), null, true);
        }

        Configure::write('debug',2);

        $id = intval($id);
          
        $property = $this->Empleado->read(null, $id);

          $this->set('property',$property);
        if (empty($property))
        {
            $this->Session->setFlash('Sorry, there is no property with the submitted ID.');
            $this->redirect(array('action'=>'index'), null, true);
        }
        $this->layout = 'pdf';
        $this->render();
   }

y en la vista pdf la siguiente:

<?php


$nom = $property['Empleado']['NOMBRE'];
$ape = $property['Empleado']['APELLIDO'];
$rut = $property['Empleado']['CEDULA'];
$nac =$property['Empleado']['NACIONALIDAD']; 
$sex =$property['Empleado']['SEXO']; 
$fecn =$property['Empleado']['FECHANAC']; 
$edad=$property['Empleado']['EDAD'];          
$edoc=$property['Empleado']['EDOCIVIL']; 

                   $tele=$property['Empleado']['TELEMERGENCIA'];
                  
$html = '<style>
div.student {
        color: #777;
        background-color: #F9F9F9;
        font-family: helvetica;
        font-size: 9pt;
    text-align: left;
 border:1px solid #DDD;
    }
h2{
    color: #F09A2E;
    font-weight: bold;
    padding: 10px 0;
}
.field_data{
      background-color: #F4F4F4;
    border: 1px solid #AAAAAA;
  padding-top: 10px;
padding-bottom: 5px;
padding-left: 5px;
height: 5px;
margin-left: 10px;
    }
</style>';

$html .='Fecha: '. date('d-m-Y',time());

$html .= '<h1>Datos del Trabajador</h1>';
//-------------------------------------------
$html .= '<h2 align="center ">Datos Personales</h2>';
$html .= '<div class="course">';
$html .= '<div><strong>Nombre Completo</strong></div>';
$html .= ''.$nom .' '.$ape;
$html .= '<div><strong>Rut</strong></div>';
$html .= $rut ;
$html .= '<div><strong>Nacionalidad</strong></div>';
$html .= $nac ;
$html .= '<div><strong>Fecha de Nacimiento</strong></div>';
$html .= $fecn ;
$html .= '<div><strong>Edad</strong></div>';
$html .= $edad ;
$html .= '<div><strong>Estado Civil</strong></div>';
$html .= $edoc ;

$html .= '</div>';


App::import('Vendor','xtcpdf');
 
ob_clean();
$tcpdf = new XTCPDF();
$textfont = 'freesans';


$tcpdf->SetAuthor("");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->xheadertext = ( false );
$tcpdf->setHeaderFont(array($textfont,'',10));
$tcpdf->xheadercolor = array(255,255,255);
 
$tcpdf->xfootertext = 'Constructora BAPER S.A';
$tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);


$tcpdf->AddPage();

$tcpdf->SetMargins(15, 5, 5);

$tcpdf->SetTitle($property['Empleado']['id']);
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',10);
// configuramos la calidad de JPEG
$tcpdf->setJPEGQuality(100);



$tcpdf->writeHTML($html, true, false, true, false, '');

// se pueden asignar mas datos, ver la documentación de TCPDF

echo $tcpdf->Output('mi_archivo.pdf', 'I'); //el pdf se muestra en el navegador
//echo $tcpdf->Output('mi_archivo.pdf', 'I'); //el pdf se descarga

?>


y me funciona muy bien, cada empleado tiene la opcion de imprimir por ejemplo su ficha pdf con sus datos, estos es por id c/u


como lo hago para imprimir todos los empleados, que tengo que modificar, he probado de todo y no me resulta, he creado varias funciones pero me dan error, y ademas en la vista creo un foreach? he hecho el intento igual pero no funciona, desde ya muchas gracias




Yoel Duran

unread,
Dec 4, 2013, 7:48:17 AM12/4/13
to cakep...@googlegroups.com
amigo te dejo este codigo pruebalo y adaptalo a tus necesidades


<?php
ob_end_clean();
ob_start();
App::import('Vendor', 'tcpdf/xctpdf');
//
require_once(APP . 'Vendor' . DS . 'tcpdf' . DS . 'config' . DS . 'lang' . DS . 'eng.php');
require_once (APP . 'Vendor' . DS . 'tcpdf' . DS . 'tcpdf.php');
//
$tcpdf = new xctpdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$textfont = 'freesans'; // looks better, finer, and more condensed than 'dejavusans'
//
$tcpdf->SetAuthor("");
$tcpdf->SetAutoPageBreak(false);
$tcpdf->setHeaderFont(array($textfont, '', 10));
$tcpdf->xheadercolor = array(255, 255, 255);
$tcpdf->xheadertext = '';
$tcpdf->xfootertext = '';
//
$tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// Now you position and print your page content
// example:
$tcpdf->AddPage();
$tcpdf->SetTextColor(0, 0, 0);
//
//
$t = "Tu Titulo<br/>";

//$tcpdf->writeHTMLCell(derecho, izquierdo, margen derecho, margen superior,$t,0, 1, 0, true, 'C',false);
$tcpdf->writeHTMLCell(0, 10, 30, 35, $t, 0, 1, 0, true, 'C', false);
$tcpdf->SetFont('times', '', 11);
//
$tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 
$tcpdf->Image(APP.'webroot'.DS.'img'.DS.'eurocamiones.png',200,0,80,50);
//$pdf->Image(K_PATH_IMAGES.'foto.png',222,15,30,25);
$tcpdf->SetFont('times', 'B', 12);
// print a line using Cell()
$t1 = "Reporte General de Usuarios Registrados<BR/>";
//$pdf->writeHTMLCell(derecho, izquierdo, margen derecho, mergen superior,$t,0, 1, 0, true, 'C',false);
$tcpdf->writeHTMLCell(0, 10, 30,70, $t1, 0, 1, 0, true, 'C', false);
$tcpdf->SetFont('times', '', 11);
//
$tabla='<table border="1" cellpadding="5" cellspacing="0" width="100%">
                <tr>

                    <th width="50px">ID</th>
                    <th width="100px">Nombres</th>
                    <th width="100px">Apellidos</th>
                    <th width="100px">Fecha Reg</th>
                    <th width="100px">Fecha Actualizacion</th>
                    <th width="100px">Fecha Ult Ingreso</th>
                    <th width="100px">Tipo</th>
                   
                </tr >';
                $contador=1;
                
                
                 foreach ($datos as $usuario):
                    if($contador%2==0) $bg="#F7F9FA"; else $bg="#dcdcdc";
                    
                $dia = explode('-', $usuario['Usuario']['registro']);
                $dia1 = explode('-', $usuario['Usuario']['actualizacion']);
                $tabla.='<tr bgcolor="'.$bg.'" align="center">
                            
                    
                        <td align="center" width="50">
                            '.$usuario['Usuario']['id'].'
                        </td>
                        <td align="left" width="100">
                            '.$usuario['Usuario']['nombres'].'
                        </td>
                        <td align="left" width="100">
                            '.$usuario['Usuario']['apellidos'].'
                        </td>
                        <td align="left" width="100">
                            '.$dia[2] . "/" . $dia[1] . "/" . $dia[0].'
                        </td>
                        <td align="left" width="100">
                            '.$dia1[2] . "/" . $dia1[1] . "/" . $dia1[0].'
                        </td>
                        <td align="left" width="100">
                            '.$usuario['Usuario']['ultingreso'].'
                        </td>
                        <td align="left" width="100">
                            '.$usuario['Usuario']['tipo'].'
                        </td>
                        
                    </tr>';

                    
                    $contador++;
                endforeach;
            $tabla.='</table>';
$tcpdf->writeHTMLCell(15,10, 30, '',$tabla,0, 1, 0, true, '',true);            
$html = 'Fecha: ' . date('j-n-Y');
$tcpdf->writeHTMLCell(150, 20, 20, 10,$html,0, 1, 0, true, '',true);
//
$tcpdf->Output('Usuarios.pdf', 'I');
ob_end_flush();

?>



--
Has recibido este mensaje porque estás suscrito al grupo "CakePHP en Español" de Grupos de Google.
Para anular la suscripción a este grupo y dejar de recibir sus correos electrónicos, envía un correo electrónico a cakephp-esp...@googlegroups.com.
Para publicar una entrada en este grupo, envía un correo electrónico a cakep...@googlegroups.com.
Visita este grupo en http://groups.google.com/group/cakephp-esp.
Para obtener más opciones, visita https://groups.google.com/groups/opt_out.



--
Yoel Duran
Der KinderBad

Angel Alexander Arboleda

unread,
Dec 4, 2013, 2:56:14 PM12/4/13
to cakep...@googlegroups.com

Hola Jorge

Yo uso

CakePHP 2.4.2


1.

En tu controlador crea una funcion: por ejemplo




    public function create_pdf(){

    $employee = $this->Modelo->find('all');

    $this->set(compact('employee'));

    $this->layout = '/pdf/default';

    $this->render('/Pdf/my_pdf_fini');

    }


fijate que en la carpeta View

2

debe existir una subcarpeta llamada Pdf  en View (Opcional si quieres separar todos los reportes pdf).


3 Debes de crear una vista llamada my_pdf_fini.ctp en la carpeta Pdf.


Eso es todo 

Si te fijas en el metodo Find

es donde dices que inforamcion quieres en este caso $this->Modelo->find('all'); buscara todos.

find(string $type = 'first', array $params = array())

Mas informacion:

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html




Javier Adrian Rivera Perez

unread,
Dec 6, 2013, 5:35:52 AM12/6/13
to cakep...@googlegroups.com
Si son pdf muy extensos es mejor que no lo crees con html ya que este
proceso consume demaciada memoria y muchas veces se muere el script.
Lo recomendable es utilizar los metodos que trae el tcp para crear los
pdf como cell y entre otras.
Cordialmente;

Adrian Rivera
Analista Programador
Colombia, Pereira Rda
Cel: +57 311 644 6541
Tel: +57 3295965
Skype: aderiver
twitter: @aderriver



2013/12/4 Angel Alexander Arboleda <a3co...@gmail.com>:
Reply all
Reply to author
Forward
0 new messages