How To pdf (CakePHP 2.1 + TCPDF)
Para poder realizar informes pdf existen muchas librerias, hoy explicaré como incluir TCPDF al framework MVC CakePHP.
Los pasos a seguir son los siguientes:
- Descargar TCPDF
- Para incluirla en nuestro proyecto descomprimirla en el directorio /app/vendor/ de nuestra aplicación. El resultado debería de ser /app/vendor/tcpdf/
- Crear un layout para los pdf's en /app/views/layouts/pdf.ctp, con este contenido:
01 <?php 02 header("Content-type: application/pdf"); 03 echo $content_for_layout; 04 ?>
- En el controlador que queramos crear los pdf's, crearemos una función para ello:
01 <?php 02 function pdf() 03 { 04 Configure::write('debug',0); 05 $this->layout = 'pdf'; /* esto utilizara el layout 'pdf. 06 ctp' */ 07 /* Operaciones que deseamos realizar y variables que 08 pasaremos a la vista. */ 09 $this->render(); 10 } 11 ?>
- Por ultimo crear una vista para esta funcion, con el siguiente contenido:
01 <?php 02 App::import('Vendor','tcpdf/tcpdf'); 03 ob_clean(); 04 // create new PDF document 05 $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 06 PDF_PAGE_FORMAT, true, 'UTF-8', false); 07 08 // set document information 09 $pdf->SetCreator(PDF_CREATOR); 10 $pdf->SetAuthor('Nicola Asuni'); 11 $pdf->SetTitle('TCPDF Example 001'); 12 $pdf->SetSubject('TCPDF Tutorial'); 13 $pdf->SetKeywords('TCPDF, PDF, example, test, guide'); 14 15 // set default header data 16 $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 17 PDF_HEADER_TITLE.' 001', 18 PDF_HEADER_STRING, array(0,64,255), 19 array(0,64,128)); 20 $pdf->setFooterData($tc=array(0,64,0), $lc=array(0,64,128)); 21 22 // set header and footer fonts 23 $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', 24 PDF_FONT_SIZE_MAIN)); 25 $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', 26 PDF_FONT_SIZE_DATA)); 27 28 // set default monospaced font 29 $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); 30 31 //set margins 32 $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, 33 PDF_MARGIN_RIGHT); 34 $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); 35 $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); 36 37 //set auto page breaks 38 $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); 39 40 //set image scale factor 41 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 42 43 //set some language-dependent strings 44 $pdf->setLanguageArray($l); 45 46 // --------------------------------------------------------- 47 48 // set default font subsetting mode 49 $pdf->setFontSubsetting(true); 50 51 // Set font 52 // dejavusans is a UTF-8 Unicode font, if you only need to 53 // print standard ASCII chars, you can use core fonts like 54 // helvetica or times to reduce file size. 55 $pdf->SetFont('dejavusans', '', 14, '', true); 56 57 // Add a page 58 // This method has several options, check the source code 59 documentation for more information. 60 $pdf->AddPage(); 61 62 // set text shadow effect 63 $pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 64 'depth_h'=>0.2, 'color'=>array(196,196, 65 196), 'opacity'=>1, 'blend_mode'=> 66 'Normal')); 67 68 $html = '<h1>HTML Example</h1> 69 Some special characters: < ? € € & è 70 è © > \\slash \\\\double-slash \\\\\\triple- 71 slash 72 <h2>List</h2> 73 List example: 74 <ol> 75 76 <li><b>bold text</b></li> 77 <li><i>italic text</i></li> 78 <li><u>underlined text</u></li> 79 <li><b>b<i>bi<u>biu</u>bi</i>b</b></li> 80 <li><a href="http://www.tecnick.com" dir="ltr">link to 81 http://www.tecnick.com</a></li> 82 <li>Sed ut perspiciatis unde omnis iste natus error sit 83 voluptatem accusantium doloremque laudantium, totam rem 84 aperiam, eaque ipsa quae ab illo inventore veritatis et 85 quasi architecto beatae vitae dicta sunt explicabo.<br /> 86 Nemo enim ipsam voluptatem quia voluptas sit aspernatur 87 aut odit aut fugit, sed quia consequuntur magni dolores 88 eos qui ratione voluptatem sequi nesciunt.</li> 89 <li>SUBLIST 90 <ol> 91 <li>row one 92 <ul> 93 <li>sublist</li> 94 </ul> 95 </li> 96 <li>row two</li> 97 </ol> 98 </li> 99 <li><b>T</b>E<i>S</i><u>T</u> <del>line through</del>< 100 /li> 101 <li><font size="+3">font + 3</font></li> 102 <li><small>small text</small> normal <small>small text< 103 /small> normal <sub>subscript</sub> normal <sup> 104 superscript</sup> normal</li> 105 </ol> 106 <dl> 107 <dt>Coffee</dt> 108 <dd>Black hot drink</dd> 109 <dt>Milk</dt> 110 <dd>White cold drink</dd> 111 </dl> 112 <div style="text-align:center">IMAGES<br /> 113 114 </div>'; 115 116 // output the HTML content 117 $pdf->writeHTML($html, true, false, true, false, ''); 118 119 // --------------------------------------------------------- 120 121 // Close and output PDF document 122 // This method has several options, check the source code 123 documentation for more information. 124 $pdf->Output('example_001.pdf', 'I'); 125 exit; 126 //=========================================================== 127 =+ 128 // END OF FILE 129 //=========================================================== 130 =+ 131 ?>
- En este ejemplo se creará un pdf de la pagina TCPDF, el ejemplo mostrado lo podemos encontrar en sección de ejemplos la página de TCPDF, es en la linea 02 en la que se incluye la librería a la vista y la linea 03 es para limpiar (eliminar) el búfer de salida. Ademas es importante remarcar que al final despues de
$pdf->Output('example_001.pdf', 'I');
- se tiene que agregar la sentencia exit; para que el navegador presente correctamente el informe en el formato adecuado
An Internal Error Has Occurred.
ResponderEliminarError: An Internal Error Has Occurred.
¿Por que?
Este comentario ha sido eliminado por el autor.
ResponderEliminarLa solución es esta
ResponderEliminarescriban la siguiente vista
http://www.tcpdf.org/examples/example_001.phps
Que es el primer ejemplo de la pagina oficial de TCPDF: http://www.tcpdf.org/examples.php
En el ejemplo solo cambien
require_once('../config/lang/eng.php');
require_once('../tcpdf.php');
por
App::import('Vendor','tcpdf/tcpdf');
ob_clean();
Por ultimo como Bien dice el buen Oscar agreguen exit despues de
$pdf->Output('example_001.pdf', 'I');
funciono perfectamente thanks..
ResponderEliminarsoy nuevo en cake y estoy intentando hacer el ejemplo con cakephp 2.4.5
ResponderEliminarme sale el siguiente error
Class 'TCPDF' not found
alguien puede ayudarme