Export HTML to PDF Table DomPDF with MySQL and PHP

0

The approach to my problem consists of the following:

I am exporting a Table from a query to MYSQL using the DomPDF 0.6.2 library but it turns out that the Header and the First Line are shown aligned to the Right and the rest of the lines, from the second appear well aligned to the left.

For what I would like to please help me to solve these 4 points:

  • That the lines appear aligned correctly on the left.
  • That the pages appear numbered in the PIE of the Page as 1 of 3, 2 of 3, etc.
  • That can establish the value of the margins of the sheet.
  • That you can establish a HEAD on each page.
  • I already thank you.

    File index.php

    <?php 
    ob_start();
    require_once('includes/conexionbd.php');  // Llama al archivo que contiene la conección a la BD.
    
    // Abre la Conexión con la BD.
    $conexion = AbreConn('dbe');
    
    // Creo la consulta de selección SQL a la BD.
    $sql = "SELECT Clientes.IdCliente, Clientes.NomRazSoc, Clientes.RFC, Clientes_Domicilios.Calle, 
    Clientes_Domicilios.NumExterior, Clientes_Domicilios.NumInterior, Clientes_Domicilios.Colonia, Municipios.Municipio,
    Estados.Estado, Paises.Pais, Clientes_Domicilios.CP, Clientes.Estatus 
    FROM Clientes, Clientes_Domicilios, Municipios, Estados, Paises     
    WHERE Clientes.IdCliente = Clientes_Domicilios.IdCliente AND Clientes_Domicilios.IdMunicipio = Municipios.IdMunicipio
    AND Clientes_Domicilios.IdEstado = Estados.IdEstado AND Clientes_Domicilios.IdPais = Paises.IdPais 
    AND Clientes.IdEmpresa = 1 AND Clientes_Domicilios.IdTipoDom = 1 AND RFC = 'XEXX010101000' ORDER BY Clientes.NomRazSoc ASC";
    // Ejecuto la consulta de selección.
    mysqli_set_charset($conexion,"utf8"); // Función que Codifica a UTF8 para evitar errores de JSON.
    $result = mysqli_query($conexion, $sql);    
    ?>  
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//ES" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="es">
    <head>
    <title>Ejemplo de Exportación de HTML a PDF</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="robots" content="NOINDEX,NOFOLLOW,NOARCHIVE,NOODP,NOSNIPPET">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <link href="assests/bootstrap/css/bootstrap-3.3.7.min.css" type="text/css" rel="stylesheet">      
    <script src="assests/jquery/jquery.min.js" type="text/javascript"></script> 
    <script src="assests/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    </head>
    <body>
    <table border="0" width="100%" height="60" cellspacing="0" cellpadding="0"><tr><td>&nbsp;</td></tr></table>
    <div class="container">
        <div class="btn btn-primary"><a href="generarpdf.php" style="color:#FFF; text-decoration:none; " target="_blank">Visualizar en PDF</a></div>  
    <div class="row">
        <div class="col-md-14">             
            <div class="panel panel-default">
                <br><p>
                <p><font face="arial" size="5" color="#000000">Ejemplo de exportación de Tabla HTML a PDF usando la librería "dompdf"</font></p> 
                <br><p>  
                <p><font face="verdana" size="3" color="#000000"><b>Clientes</b></font></p>  
                <div class="panel-body"> 
    <?php               
                echo '<table class="table table-striped table-hover table-responsive cell-border" id="TabLisClientes">';
                    echo '<thead>';
                        echo '<tr style="background-color:#e6e6e6;">';
                            echo '<th>Nombre o Razón Social</th>';
                            echo '<th>R.F.C.</th>';
                            echo '<th>Calle</th>';
                            echo '<th>No.Ext.</th>';
                            echo '<th>No.Int.</th>';
                            echo '<th>Colonia</th>';
                            echo '<th>Municipio</th>';
                            echo '<th>Estado</th>';
                            echo '<th>País</th>';
                            echo '<th>C.P.</th>';
                            echo '<th>Status</th>';     
                        echo '</tr>';
                        echo '</thead>';
                        echo '<tbody>';
    
                        while($row = mysqli_fetch_assoc($result)) {
                        $active = '';
                        if($row['Estatus'] == 'Activo') {
                            $active = '<label class="label label-success">Activo</label>';
                        } else {
                            $active = '<label class="label label-danger">Inactivo</label>'; 
                        }
    
                        echo '<tr>';
                            echo '<td>'.$row['NomRazSoc'].'</td>';
                            echo '<td>'.$row['RFC'].'</td>';
                            echo '<td>'.$row['Calle'].'</td>';
                            echo '<td>'.$row['NumExterior'].'</td>';
                            echo '<td>'.$row['NumInterior'].'</td>';
                            echo '<td>'.$row['Colonia'].'</td>';
                            echo '<td>'.$row['Municipio'].'</td>';
                            echo '<td>'.$row['Estado'].'</td>';
                            echo '<td>'.$row['Pais'].'</td>';               
                            echo '<td>'.$row['CP'].'</td>';             
                            echo '<td>'.$active.'</td>';
                        echo '</tr>';                       
                        } // Fin while 
    
                        // Cierra la Conexión con la BD.
                        mysqli_close($conexion);
    
                        echo '</tbody>';
                    echo '</table>';
                ?>  
                </div> <!-- / panel-body -->
            </div> <!-- / panel panel-default -->               
        </div> <!-- / col-md-14 -->
    </div> <!-- / row -->
    </div> <!-- / container -->
    </body>
    </html>
    

    File generatepdf.php

    <?php 
    ob_start();
    require_once('includes/conexionbd.php');  // Llama al archivo que contiene la conección a la BD.
    
    // Abre la Conexión con la BD.
    $conexion = AbreConn('dbe');
    
    // Creo la consulta de selección SQL a la BD.
    $sql = "SELECT Clientes.IdCliente, Clientes.NomRazSoc, Clientes.RFC, Clientes_Domicilios.Calle, 
    Clientes_Domicilios.NumExterior, Clientes_Domicilios.NumInterior, Clientes_Domicilios.Colonia, Municipios.Municipio,
    Estados.Estado, Paises.Pais, Clientes_Domicilios.CP, Clientes.Estatus 
    FROM Clientes, Clientes_Domicilios, Municipios, Estados, Paises     
    WHERE Clientes.IdCliente = Clientes_Domicilios.IdCliente AND Clientes_Domicilios.IdMunicipio = Municipios.IdMunicipio
    AND Clientes_Domicilios.IdEstado = Estados.IdEstado AND Clientes_Domicilios.IdPais = Paises.IdPais 
    AND Clientes.IdEmpresa = 1 AND Clientes_Domicilios.IdTipoDom = 1 AND RFC = 'XEXX010101000' ORDER BY Clientes.NomRazSoc ASC";
    // Ejecuto la consulta de selección.
    mysqli_set_charset($conexion,"utf8"); // Función que Codifica a UTF8 para evitar errores de JSON.
    $result = mysqli_query($conexion, $sql);    
    ?>  
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//ES" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="es">
    <head>
    <title>Ejemplo de Exportación de HTML a PDF</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="robots" content="NOINDEX,NOFOLLOW,NOARCHIVE,NOODP,NOSNIPPET">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <link href="assests/bootstrap/css/bootstrap-3.3.7.min.css" type="text/css" rel="stylesheet">      
    <script src="assests/jquery/jquery.min.js" type="text/javascript"></script> 
    <script src="assests/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    </head>
    <body>
    <table border="0" width="100%" height="60" cellspacing="0" cellpadding="0"><tr><td>&nbsp;</td></tr></table>
    <div class="container">
        <div class="btn btn-primary"><a href="generarpdf.php" style="color:#FFF; text-decoration:none; " target="_blank">Visualizar en PDF</a></div>  
    <div class="row">
        <div class="col-md-14">             
            <div class="panel panel-default">
                <br><p>
                <p><font face="arial" size="5" color="#000000">Ejemplo de exportación de Tabla HTML a PDF usando la librería "dompdf"</font></p> 
                <br><p>  
                <p><font face="verdana" size="3" color="#000000"><b>Clientes</b></font></p>  
                <div class="panel-body"> 
    <?php               
                echo '<table class="table table-striped table-hover table-responsive cell-border" id="TabLisClientes">';
                    echo '<thead>';
                        echo '<tr style="background-color:#e6e6e6;">';
                            echo '<th>Nombre o Razón Social</th>';
                            echo '<th>R.F.C.</th>';
                            echo '<th>Calle</th>';
                            echo '<th>No.Ext.</th>';
                            echo '<th>No.Int.</th>';
                            echo '<th>Colonia</th>';
                            echo '<th>Municipio</th>';
                            echo '<th>Estado</th>';
                            echo '<th>País</th>';
                            echo '<th>C.P.</th>';
                            echo '<th>Status</th>';     
                        echo '</tr>';
                        echo '</thead>';
                        echo '<tbody>';
    
                        while($row = mysqli_fetch_assoc($result)) {
                        $active = '';
                        if($row['Estatus'] == 'Activo') {
                            $active = '<label class="label label-success">Activo</label>';
                        } else {
                            $active = '<label class="label label-danger">Inactivo</label>'; 
                        }
    
                        echo '<tr>';
                            echo '<td>'.$row['NomRazSoc'].'</td>';
                            echo '<td>'.$row['RFC'].'</td>';
                            echo '<td>'.$row['Calle'].'</td>';
                            echo '<td>'.$row['NumExterior'].'</td>';
                            echo '<td>'.$row['NumInterior'].'</td>';
                            echo '<td>'.$row['Colonia'].'</td>';
                            echo '<td>'.$row['Municipio'].'</td>';
                            echo '<td>'.$row['Estado'].'</td>';
                            echo '<td>'.$row['Pais'].'</td>';               
                            echo '<td>'.$row['CP'].'</td>';             
                            echo '<td>'.$active.'</td>';
                        echo '</tr>';                       
                        } // Fin while 
    
                        // Cierra la Conexión con la BD.
                        mysqli_close($conexion);
    
                        echo '</tbody>';
                    echo '</table>';
                ?>  
                </div> <!-- / panel-body -->
            </div> <!-- / panel panel-default -->               
        </div> <!-- / col-md-14 -->
    </div> <!-- / row -->
    </div> <!-- / container -->
    </body>
    </html>
    <?php
    # Cargamos la librería dompdf.
    require_once 'dompdf/dompdf_config.inc.php';
    
    # Instanciamos un objeto de la clase DOMPDF.
    $mipdf = new DOMPDF();
    
    # Definimos el tamaño y orientación del papel que queremos.
    # O por defecto cogerá el que está en el fichero de configuración.
    $mipdf ->set_paper("Legal", "landscape");
    
    # Cargamos el contenido HTML.
    $mipdf ->load_html(ob_get_clean());
    
    # Renderizamos el documento PDF.
    $mipdf ->render();
    
    # Enviamos el fichero PDF al navegador.
    $mipdf->stream("Clientes.pdf", array("Attachment" => false));
    
    exit(0);
    ?>
    

    This is the image of the MYSQL Query Table (File index.php):

    This is the PDF image of the Exported table (File generate.php):

        
    asked by Francisco Aguilar 03.10.2018 в 06:13
    source

    2 answers

    0

    The solution to the alignment problem I found right here in stack overflow, in this url link

    I put it between the tags of the page or File generatepdf.php that I show next (it is the last line related to the styles):

    <head>
    <title>Ejemplo de Exportación de HTML a PDF</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="robots" content="NOINDEX,NOFOLLOW,NOARCHIVE,NOODP,NOSNIPPET">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <link href="assests/bootstrap/css/bootstrap-3.3.7.min.css" type="text/css" rel="stylesheet">      
    <script src="assests/jquery/jquery.min.js" type="text/javascript"></script> 
    <script src="assests/bootstrap/js/bootstrap.min.js" type="text/javascript">  </script>
    <style type="text/css"> thead:before, thead:after { display: none; } tbody:before, tbody:after { display: none; } </style>
    </head>
    

    This is the result after adding the aforementioned style line:

    Thanks to Pathros link

    Now I just need to solve the remaining 3 points, namely:

  • That the pages appear numbered in the PIE of the Page as 1 of 3, 2 of 3, etc.
  • That can establish the value of the margins of the sheet.
  • That you can establish a HEAD on each page.
  • Could you help me with these points please?

        
    answered by 04.10.2018 в 03:04
    0

    The remaining 3 points of my problem have already been resolved, which were the following:

  • That the pages appear numbered in the PIE of the Page as 1 of 3, 2 of 3, etc.
  • That can establish the value of the margins of the sheet.
  • That you can establish a HEAD on each page.
  • The solution consisted of modifying code in the Genepdf.php File in the manner I describe below:

    I unchecked the line "define (" DOMPDF_ENABLE_PHP ", true);" in the file "dompdf_config.custom.inc.php" of the library "dompdf".

    I added the line "require_once 'dompdf / dompdf_config.custom.inc.php';" immediately after the line "require_once 'dompdf / dompdf_config.inc.php';".

    I removed the labels "", "", and "", along with the texts

    <br><p>
    <p><font face="arial" size="5" color="#000000">Ejemplo de exportación de Tabla HTML a PDF usando la librería "dompdf"</font></p> 
    <br><p>  
    <p><font face="verdana" size="3" color="#000000"><b>Clientes</b></font></p>  
    <div class="panel-body"> 
    

    Add the following lines before the "" tag and after the "" tag:

    <script type="text/php">
    if ( isset($pdf) ) {
        // OLD 
        $font = Font_Metrics::get_font("Arial", "normal");
        $pdf->page_text(960, 590, "{PAGE_NUM} de {PAGE_COUNT}", $font, 10, array(0,0,0));
        // v.0.7.0 and greater
        /*$x = 72;
        $y = 18;
        $text = "{PAGE_NUM} of {PAGE_COUNT}";
        $font = $fontMetrics->get_font("helvetica", "bold");
        $size = 6;
        $color = array(255,0,0);
        $word_space = 0.0;  //  default
        $char_space = 0.0;  //  default
        $angle = 0.0;   //  default
        $pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);*/
    }
    </script>   
    <div id="header">Cabecera de Página</div>
    <div id="footer">Pie de Página</div>
    

    Finally I added the last 3 style lines in the following tag:

    <style type="text/css"> 
    thead:before, thead:after { display: none; } tbody:before, tbody:after { display: none; }
    @page { margin: 40px 10px; }
    #header { position: fixed; left: 0px; top: -32px; right: 0px; height: 40px; background-color: orange; text-align: center; }
    #footer { position: fixed; left: 0px; bottom: -32px; right: 0px; height: 30px; background-color: lightblue; text-align: center; }       
    </style>
    

    And the Final Result was the Next:

    THANK YOU!

        
    answered by 04.10.2018 в 08:06