Ver Mensaje Individual
  #1 (permalink)  
Antiguo 08/06/2011, 05:53
IEKK
 
Fecha de Ingreso: agosto-2010
Ubicación: Tenerife
Mensajes: 893
Antigüedad: 13 años, 8 meses
Puntos: 202
Aporte/ejemplo crear pdf haciendo clic con html2pdf

En el aporte anterior añadí un ejemplo simple de como pasar el html a pdf usando dompdf haciendo click a un botón y cambiado sus características.
http://www.forosdelweb.com/f18/aport...dompdf-919465/

Como algunos usuarios prefieren html2pdf a dompdf mostraré como hacer exactamente lo mismo con apenas modificar unas líneas de la función.

Recuerdo que sólo es un ejemplo que sirva de guía, para quienes han tenido problemas al crear pdfs.

Descargar html2pdf:
http://sourceforge.net/projects/phphtml2pdf/

Opciones:
html2pdf, dispone de muchísimas otras opciones, pero me centraré en lo básico que es mostrar el pdf y poder cambiarle las opciones.

No se muestran estas opciones en el ejemplo pero las comento ya que se le pueden añadir y que hacen de html2pdf una "buena" librería para convertir a pdf: (Ver en la documentación en caso de dudas)

Dejo la documentación del html2pdf en español:
http://wiki.spipu.net/doku.php?id=ht...:es:v3:accueil

Un pequeño dejavú, (aunque no igual) del post anterior:

convertToPDF.php
Código PHP:
<?php

function doPDF($path='',$content='',$body=false,$style='',$mode=false,$paper_1='P',$paper_2='A4')
{    
    if( 
$body!=true and $body!=false $body=false;
    if( 
$mode!=true and $mode!=false $mode=false;

    if( 
$body == true )
    {
        
$content='
        <!doctype html>
        <html>
        <head>
            <link rel="stylesheet" href="'
.$style.'" type="text/css" />
        </head>
        <body>'
            
.$content.
        
'</body>
        </html>'
;
    }

    if( 
$content!='' )
    {
        
ob_start();
        
        echo 
'<page>'.$content.'</page>';
        
        
//Añadimos la extensión del archivo. Si está vacío el nombre lo creamos
        
$path!='' $path .='.pdf' $path crearNombre(10);  
            
        
$content ob_get_clean(); 
        require_once(
'html2pdf/html2pdf.class.php'); 
        
        
//Orientación / formato del pdf y el idioma.
        
$pdf = new HTML2PDF($paper_1,$paper_2,'es'/*, array(10, 10, 10, 10) /*márgenes*/); //los márgenes también pueden definirse en <page> ver documentación
        
        
$pdf->WriteHTML($content);
        
        if(
$mode==false)
        {
            
//El pdf es creado "al vuelo", el nombre del archivo aparecerá predeterminado cuando le demos a guardar
            
$pdf->Output($path); // mostrar
            //$pdf->Output('ejemplo.pdf', 'D');  //forzar descarga 
        
}
        else
        {
            
$pdf->Output($path'F'); //guardar archivo ( ¡ojo! si ya existe lo sobreescribe )
            
header('Location: '.$path); // abrir
        
}
    
    }

}

function 
crearNombre($length)
{
    if( ! isset(
$length) or ! is_numeric($length) ) $length=6;
    
    
$str  "0123456789abcdefghijklmnopqrstuvwxyz";
    
$path '';
    
    for(
$i=$i<$length $i++)
      
$path .= $str{rand(0,strlen($str)-1)};

    return 
$path.'_'.date("d-m-Y_H-i-s").'.pdf';    
}

?>
index.php
Código PHP:
<?php

//Aquí pondriamos por ejemplo la consulta
$html='
<table style="background-color="#BECEDC"">
<tr>
<td>
    <img src="http://demo.html2pdf.fr/examples/res/logo.gif"/>
</td>
</tr>    
<tr>
<td>
<table>
    <tr>
        <th>Nombre</th>
        <th>Tipo</th>
        <th>Imagen</th>
        <th>Comentario</th>
        <th>Unidades</th>
        <th>Precio unidad</th>    
    </tr>    
    <tr>
        <td>pensandoo</td>
        <td>icono</td>
        <td><img src="http://static.forosdelweb.com/fdwtheme/images/smilies/scratchchin.gif"/></td>
        <td>iconito pensativo</td>
        <td>3</td>
        <td>10</td>
    </tr>
    <tr>
        <td>fiesta</td>
        <td>icono 3</td>
        <td><img src="http://static.forosdelweb.com/fdwtheme/images/smilies/porra.gif"/></td>
        <td>iconito festejando</td>
        <td>1</td>
        <td>24</td>
    </tr>
    <tr>
        <td>silbando</td>
        <td>icono</td>
        <td><img src="http://static.forosdelweb.com/fdwtheme/images/smilies/silbar.gif"/></td>
        <td>bombilla silbando</td>
        <td>19</td>
        <td>50</td>
    </tr>
    <tr>
        <td>no no no</td>
        <td>icono 2</td>
        <td><img src="http://static.forosdelweb.com/fdwtheme/images/smilies/negar.gif"/></td>
        <td>negacion</td>
        <td>5</td>
        <td>1</td>
    </tr>
</table>
</td>
</tr>
</table>
'
;

include(
'convertToPDF.php');

if ( isset(
$_POST['PDF_1']) )
    
doPDF('ejemplo',$html,false);

if ( isset(
$_POST['PDF_2']) )
    
doPDF('ejemplo',$html,true,'style.css');

if ( isset(
$_POST['PDF_3']) )
    
doPDF('',$html,true,'style.css');
            
if ( isset(
$_POST['PDF_4']) )
    
doPDF('ejemplo',$html,true,'style.css',false,'P','A5'); //será más grande (comparar con $_POST['PDF_2'])
    
if ( isset($_POST['PDF_5']) )
    
doPDF('ejemplo',$html,true,'',true);

if ( isset(
$_POST['PDF_6']) )
    
doPDF('',$html,true,'style.css',true);
    
if ( isset(
$_POST['PDF_7']) )
    
doPDF('pdfs/nuevo-ejemplo',$html,true,'style.css',true);



?>

<!doctype html>
<html>

<head>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<table class="header">
    <tr>
        <td><a href="http://www.forosdelweb.com/f18/" target="_blank"><h1>PHP</h1></a></td>
        <td><a href="http://www.forosdelweb.com/" target="_blank"><h2>FOROSDELWEB</h2></a></td>
    </tr>
</table>

<table class="menu">
    <tr>
        <td>Ejemplos para: <strong>html2pdf</strong></td>
        <td><a href="http://wiki.spipu.net/doku.php?id=html2pdf:es:v3:accueil" target="_blank">Documentaci&oacute;n</a></td>
        <td><a href="http://www.yaronet.com/html2pdf" target="_blank">Foro</a></td>
        <td><a href="http://html2pdf.fr/example" target="_blank">Ejemplos de html2pdf</a></td>
    </tr>
</table>

<?php echo $html ?>

<form  action="<?php echo $_SERVER['PHP_SELF'?>" method="POST">
<table>
  <tr>
    <td>Mostrar PDF sin CSS</td>
    <td><input name="PDF_1" type="submit" value="CREAR" /></td>
  </tr>
  <tr>
    <td>Mostrar PDF con CSS</td>
    <td><input name="PDF_2" type="submit" value="CREAR" /></td>
  </tr>
  <tr>
    <td>Mostrar PDF con CSS sin definir el nombre</td>
    <td><input name="PDF_3" type="submit" value="CREAR" /></td>
  </tr>
  <tr>
    <td>Mostrar PDF con CSS y cambiando el formato de la hoja</td>
    <td><input name="PDF_4" type="submit" value="CREAR" /></td>
  </tr>
  <tr>
    <td>Guardar y abrir PDF sin CSS</td>
    <td><input name="PDF_5" type="submit" value="CREAR" /></td>
  </tr>
  <tr>
    <td>Guardar y abrir PDF con CSS sin definir el nombre</td>
    <td><input name="PDF_6" type="submit" value="CREAR" /></td>
  </tr>
  <tr>
    <td>Guardar en otro directorio y abrir PDF con CSS</td>
    <td><input name="PDF_7" type="submit" value="CREAR" /></td>
  </tr>  
  
</table>

</form>

</body>
</html>
style.css
Código HTML:
Ver original
  1. body{
  2. font:12px Arial, Tahoma, Verdana, Helvetica, sans-serif;
  3. background-color:#BECEDC;
  4. color:#000;
  5. }
  6.  
  7. a h1{
  8. font-size:35px;
  9. color:#FFF;
  10. }
  11.  
  12. h2{
  13. color:#FC0;
  14. font-size:15px;
  15. }
  16.  
  17. table{
  18. width:100%;
  19. height:auto;
  20. margin:10px 0 10px 0;
  21. border-collapse:collapse;
  22. text-align:center;
  23. background-color:#365985;
  24. color:#FFF;
  25. }
  26.  
  27. table td,th{
  28. border:1px solid black;
  29. }
  30.  
  31. table th{
  32. color:#FC0;
  33. }
  34.  
  35. .menu{
  36. background-color:#69C;
  37. color:#FFF;
  38. }
  39.  
  40. .menu a{
  41. color:#FFF;
  42. }

Imagen de index.php


Imagen del pdf sin css


Imagen del pdf con css


En esencia es lo mismo, y como verán no es complicado generar pdf con una librería u otra.
Si quieren usar el resto de opciones que trae html2 sólo tienen que modificarlo a su gusto.
__________________
Pensaba que internet era una gran biblioteca de sabiduría, hasta que comprendí que un libro no puede tener mil páginas llenas de faltas de ortografía... :(