Ver Mensaje Individual
  #1 (permalink)  
Antiguo 07/06/2011, 11:29
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 dompdf

Últimamente en el foro se han visto muchas preguntas y errores de como convertir el html a pdf usando diferentes librerías.
En este ejemplo sencillo usaremos una función para generar un pdf con dompdf.

Por supuesto el ejemplo es mejorable ya que sólo es una idea, pero espero mostrar una manera diferente de usar dompdf con tan solo una función, ya que la gente sólo hace copy & paste de los tutoriales y no salen de ahí.

Descargar dompdf: http://code.google.com/p/dompdf/downloads/list
Demos: http://pxd.me/dompdf/www/examples.php#samples

¿Qué conseguimos en este ejemplo?
  • No generaremos el pdf al cargar la página sino haciendo clic a un botón.
  • Mostraremos en el pdf toda la página o sólo una parte (lo que contenga la variable que enviemos).
  • Podremos usar css diferentes en el pdf a la que usamos en la página.
  • Se puede guardar el pdf en un directorio antes de mostrarlo.
  • También contaremos con la posibilidad de cambiar el tamaño y formato del documento (consulten como ver los formatos en la documentación).

Cosas importantes a tener en cuenta de dompdf:
handles most CSS 2.1 and a few CSS3 properties
image support (gif, png (8, 24 and 32 bit with alpha channel), bmp & jpeg)

Importante también saber que dompdf necesita las rutas absolutas para cargar las imágenes.

convertToPDF.php
Código PHP:
<?php
/*----------------------------------------------------------/*
    
$path     : nombre y/o ruta del pdf (sin la extensión)
                p.e: --> 'ejemplo' , 'pdfs/nuevo-ejemplo'
                si se deja vacío --> se genera uno aleatorio

$content  : contenido del pdf

$body     : true o false.
                true  --> Añade; <doctype>, <body>, <head> a $content
                false --> no altera el $content
                
$style    : la ruta de la CSS. Puede estar vacía
                 Para cargar una css --> necesita $body = true;

$mode     : true o false.
                true  --> guarda el pdf en un directorio y lo muestra 
                false --> pregunta si guarda o abre el archivo 
            
$paper_1  : tamaño del papel[*]
$paper_2  : estilo del papel[*]
    
    [*] como ver las opciones disponibles: 
        --> http://code.google.com/p/dompdf/wiki/Usage#Invoking_dompdf_via_the_command_line

/*----------------------------------------------------------*/ 

require_once("dompdf/dompdf_config.inc.php");

function 
doPDF($path='',$content='',$body=false,$style='',$mode=false,$paper_1='a4',$paper_2='portrait')
{    
    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!='' )
    {        
        
//Añadimos la extensión del archivo. Si está vacío el nombre lo creamos
        
$path!='' $path .='.pdf' $path crearNombre(10);  

        
//Las opciones del papel del PDF. Si no existen se asignan las siguientes:[*]
        
if( $paper_1=='' $paper_1='a4';
        if( 
$paper_2=='' $paper_2='portrait';
            
        
$dompdf =  new DOMPDF();
        
$dompdf -> set_paper($paper_1,$paper_2);
        
$dompdf -> load_html(utf8_encode($content));
        
//ini_set("memory_limit","32M"); //opcional 
        
$dompdf -> render();
        
        
//Creamos el pdf
        
if($mode==false)
            
$dompdf->stream($path);
            
        
//Lo guardamos en un directorio y lo mostramos
        
if($mode==true)
            if( 
file_put_contents($path$dompdf->output()) ) header('Location: '.$path);
    }
}

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

include('convertToPDF.php');

//$html= --> Aquí pondriamos por ejemplo la consulta
$html='
<img src="http://pxd.me/dompdf/www/images/title.gif"/>

<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>
'

?>

<?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,'letter','landscape'); 
    
if ( isset(
$_POST['PDF_5']) )
    
doPDF('ejemplo',$html,true,'',true); //asignamos los tags <html><head>... pero no tiene css

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); //lo guardamos en la carpeta pdfs    
?>

<!doctype html>
<html>

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

<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>dompdf</strong></td>
        <td><a href="http://code.google.com/p/dompdf/wiki/Usage" target="_blank">Documentaci&oacute;n</a></td>
        <td><a href="http://code.google.com/p/dompdf/source/browse/trunk/dompdf/dompdf_config.custom.inc.php?r=399" target="_blank">Define()</a></td>
        <td><a href="http://pxd.me/dompdf/www/examples.php#samples" target="_blank">Ejemplos de dompdf</a></td>
    </tr>
</table>

<body>

<?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:
body{
font:12px Arial, Tahoma, Verdana, Helvetica, sans-serif;
background-color:#BECEDC;
color:#000;
}

a h1{
font-size:35px;	
color:#FFF;
}

h2{
color:#FC0;
font-size:15px;	
}

table{
width:100%;
height:auto;
margin:10px 0 10px 0;
border-collapse:collapse;
text-align:center;
background-color:#365985;
color:#FFF;
}

table td,th{
border:1px solid black;
}

table th{
color:#FC0;	
}

.menu{
background-color:#69C;
color:#FFF;
}

.menu a{
color:#FFF;	
}
Imagen de index.php


Imagen del pdf sin css


Imagen del pdf con css


Como verán no es tan complicado crear un pdf con dompdf, con un formulario y una función todo arreglado
__________________
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... :(