Export CRUD list with MPDF + OB_start ()

2

Good morning guys, I'm developing CRM using the CodeIgniter framework and I'm not able to export some CRUD lists using the MPDF library.

I'm trying to use the ob_start() function as indicated in the library manual itself, but when exporting, I get the following error in return:

Below,thecodesused:

view:

<divclass="col-sm-2">
    <a href="http://localhost/sistema/clientes/inserir" class="btn btn-   primary pull-right h2">Novo Cliente</a>
</div>

<div id="list" class="row">
    <div class="table-responsive col-md-12">
        <table class="table table-striped" cellspacing="0" cellpadding="0">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Contato</th>
                    <th>Telefone</th>
                    <th>Email</th>
                    <th>Cidade</th>
                    <th class="actions">Ações</th>
                </tr>
            </thead>

            <tbody>

                <?php foreach ( $clientes as $cliente ) {?>
                    <tr>
                        <td><?php echo $cliente->ccod; ?></td> 
                        <td><?php echo $cliente->cnome; ?></td>    
                        <td><?php echo $cliente->contato; ?></td>
                        <td><?php echo $cliente->telefone; ?></td>
                        <td><?php echo $cliente->email; ?></td>
                        <td><?php echo $cliente->cidade; ?> </td>
                        <td class="actions">
                            <a title="history" class="btn btn-success btn-xs" href="<?php echo base_url() . 'comments/history/' . $cliente->ccod; ?>">Historico</a>
                            <a title="orçamentos" class="btn btn-default btn-xs" href="<?php echo base_url() . 'orcamentos/history/' . $cliente->ccod; ?>">Orçamentos</a>
                            <a title="Editar" class="btn btn-warning btn-xs" href="<?php echo base_url() . 'clientes/editar/' . $cliente->ccod; ?>"> Editar</a>
                            <a title="Deletar" class="btn btn-danger btn-xs" href="<?php echo base_url() . 'clientes/deletar/' . $cliente->ccod; ?>" onclick="return confirm('Confirma a exclus�o deste registro?')">Deletar</a>
                        </td>       

                    </tr>               

                <?php } ?>
            </tbody>
        </table>
    </div>
</div>  

<div class="col-sm-12">
    <a href="http://localhost/sistema/clientes/exports" class="btn btn-default btn-xs pull-right h2">Exportar</a>
</div>

I'm putting the ob_start() logo function at the beginning of the view containing the HTML of the page.

Controller:

public function exports(){

    $html= ob_get_contents();

    ob_end_clean(); 

    //this the the PDF filename that user will get to download
    $pdfFilePath = "relatorio de clientes.pdf";

    //load mPDF library
    $this->load->library('m_pdf');
    //actually, you can pass mPDF parameter on this load() function
    $pdf = $this->m_pdf->load();
    //generate the PDF!
    $pdf->WriteHTML($html);
    //offer it to user via browser download! (The PDF won't be saved on your     server HDD)
    $pdf->Output($pdfFilePath, "D");      
}

In addition, I did not change anything in the files of the library, and complementing, follows a print from the screen where I'm trying to export the list, note that what I want to do is just print the list, the layout part and the menu do not.

I'm a beginner with PHP , I'm not sure if I'm putting the function in the correct location for my code.

    
asked by anonymous 16.01.2017 / 18:35

1 answer

0

I'll explain the idea to you, you get out of here and make the necessary adjustments to your code.

Here is the basic recipe of our algorithm :

  • Show the data and the FORM filtering and filtering;
  • Generate filtered lists by request;
  • Return the values of the database, according to the request filter;
  • Generate filtered reports in PDF using MPDF ;
  • OBS: I did all this in a single controller , but you can delegate the model functions in your application later. Ideally you should understand logic.

    Controller Report.php :

    <?php
    
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Report extends CI_Controller {
    
        function __construct() {
            parent::__construct();
            $this->output->enable_profiler(FALSE);
        }
    
        function mostra_lista() {
            $data['title'] = 'Mostra lista';
            $data['dados'] = $this->dados();
            $this->load->view('mostra_lista', $data);
        }
    
        function gera_lista(){
            $data['title'] = 'Gera lista';
            $criterio = $this->input->get('criterio');
            if (empty($criterio)) {
                $data['dados'] = $this->dados();
                $this->load->view('gera_lista', $data);
            }
            else{
                $data['dados'] = $this->dados($criterio);
                $data['criterio'] = $criterio;
                $this->load->view('gera_lista', $data);
            }   
        }
    
        function gera_pdf() {
            $criterio = $this->input->get('criterio');
            $filename = __FUNCTION__.'.pdf';
            $data['dados'] = $this->dados($criterio);
            $view = $this->load->view('gera_lista', $data);
            $html = $view->output->final_output;
            $this->mpdf = new mPDF('utf-8', 'A4-P');
            $this->mpdf->WriteHTML($html);
            $this->mpdf->Output($filename,'D');
        }
    
        private function dados(){
            $dados = [];
            if(empty($this->input->get('criterio'))){
                for ($i = 1; $i <= 10; $i++) {
                    $dados[$i] = [
                        'id' => $i,
                        'empresa' => "Empresa $i",
                        'contato' => "Contato $i",
                        'telefone' => "Tel $i",
                        'email' => "[email protected]",
                        'cidade' => "Cidade $i",
                    ];
                }
                return $dados;
            }
            else{
                for ($i = 5; $i <= 10; $i++) {
                    $dados[$i] = [
                        'id' => $i,
                        'empresa' => "Empresa $i",
                        'contato' => "Contato $i",
                        'telefone' => "Tel $i",
                        'email' => "[email protected]",
                        'cidade' => "Cidade $i",
                    ];
                }
                return $dados;
            }
        }
    
    }
    

    View show_list.php : And this is, in fact, the tricky part of this program. Pay attention to JavaScript , because he does the magic.

    If you click Refresh with empty FORM , the list comes complete. If you pass a value in FORM , the list changes. The export link (which can be a button or something else) will always save the displayed list (this is the expected behavior).

    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
            <title>Example</title>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
            <script src="https://code.jquery.com/jquery-2.2.4.min.js"integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
            <script>
                $(function () {
                    //Carrega a lista completa com a pagina
                    mostra_lista();
                    // Carrega a lista sob demanda
                    $('#fa-refresh').click(function () {mostra_lista();});
                    // Altera comportamento padrao do FORM
                    $("#gera_lista").submit(function (e) {e.preventDefault();});
                });
                function mostra_lista() {
                    //Envia os dados do FORM para o controller
                    $.get(
                        $("#gera_lista").attr("action"),
                        $("#gera_lista").serialize(),
                        //Captura a lista filtrada pela requisicao
                        function (resp) {
                            //Altera o parametro de filtragem para o metodo gera_pdf()
                            var criterio = $('#criterio').val();
                            var href = "<?=base_url('report/gera_pdf/')?>?criterio="+criterio;
                            $("a").attr("href", href);
                            //Mostra a lista filtrada
                            $('#resp').html(resp);
                        }
                    );
                }
            </script>        
        </head>
        <body>
            <nav class="navbar"></nav>
            <div class="container">
                <form class="form-inline" id="gera_lista" action="<?= base_url('report/gera_lista') ?>">
                    <input type="text" name="criterio" id="criterio" class="form-control" placeholder="Critério de busca">
                    <button type="submit" class="btn btn-primary" id="fa-refresh">Refresh</button>
                </form>
                <br>
                <div class="col-lg-12">
                    <a id="gera_pdf" href="" target="_blank" value="">
                        Exportar lista exibida como pdf
                    </a>
                    <div id="resp"></div>
                </div>
            </div>
        </body>
    </html>
    

    View gera_lista.php :

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    $key = !empty($criterio) ? $criterio : '';
    ?>
    <table class="table">
        <tbody>
            <tr>
                <td>id</td>
                <td>empresa</td>
                <td>contato</td>
                <td>telefone</td>
                <td>email</td>
                <td>cidade</td>
            </tr>
            <?php
            if ($dados) {
                foreach ($dados as $item => $arr) {
                    echo '<tr>';
                    echo "<td>{$arr['id']}</td>";
                    echo "<td>{$arr['empresa']}</td>";
                    echo "<td>{$arr['contato']}</td>";
                    echo "<td>{$arr['telefone']}</td>";
                    echo "<td>{$arr['email']}</td>";
                    echo "<td>{$arr['cidade']}</td>";
                    echo '</tr>';
                }
            }
            ?>
        </tbody>
    </table>
    

    That's it. Test, put it to work in your environment and follow the logic that has no error.

        
    18.01.2017 / 03:08