Export CRUD list with MPDF + Ob_start()

Asked

Viewed 913 times

2

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

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

inserir a descrição da imagem aqui

Below are the codes used:

view:

<div class="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 setting the function ob_start() at the beginning of the view containing the HTML of the page.

Controler:

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");      
}

Also, I didn’t change anything in the library files, and in addition, follow a screenshot of where I am trying to export the list, note that what I intend to do is just print the list, the layout part and menu.

inserir a descrição da imagem aqui

I’m beginner with PHP, do not know if I am putting the function in the correct location of my code.

  • Show the VIEW complete, please.

  • Organize: You won’t be able to do the same view generate both the list and the pdf. Not the way you want it. Right, in this case, it is one method to generate the list, another to generate the pdf report from the list (are two things). A controller generates the list based on filters, right? Then the button Export can generate the report based on these same filters. It is much more complex than it seems...

  • I believe I understood what you meant, yes in my controller I am using a method to create the list of items, and a method to export, but I tried to take advantage of the same view actually, I will switch to the way you indicated and put the result. thank you

1 answer

0


I’ll explain the idea to you, you leave here and make whatever adaptations are necessary in your code.

Here’s the basic recipe for our algorithmism:

  1. Show the data and the FORM filtering and filtering;
  2. Generate filtered lists by request;
  3. Return database values as per the request filter;
  4. Generate the filtered reports in PDF using MPDF;

OBS: I did it all in one controller, but you can delegate the functions of model in your application later. Ideally you understand the 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 display_list.php: And this is, in fact, the tricky part of this program. Pay attention to JavaScript, 'Cause he does the magic.

If you click on Refresh with the FORM empty, the list is complete. If you pass a value in the FORM, the list changes. The export link (which can be a button or anything 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_list.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 is not wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.