Dompdf Illegal error "string offset 'Hex' online 1150 style.cls.php"

Asked

Viewed 1,234 times

1

I have the following code:

    <?php 
    session_start();
    if(isset($_SESSION['logado'])==false){
        echo("<script>window.location = 'login.php';</script>");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html" charset="utf-8">
        <title>Relatório</title>
        <link rel="icon" type="img/png" href="img/Brasão_do_Ceará.png">
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/estilo_relatorio.css">
        <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
        <script src="jquery/jquery.min.js"></script>
        <script src="jquery/bootstrap.min.js"></script>
        <script type="text/javascript" src="jquery/w3.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
            var comeco = $("#data_filtroe").val();
            var fim = $("#data_filtrod").val();
            $("input[type='date']").click(function(){
            $("#data_filtrod").attr("min",comeco);
            comeco = $("#data_filtroe").val();
            fim = $("#data_filtrod").val();   
            if(fim<comeco){
                document.querySelector('#data_filtrod').value = comeco;
                $("#data_filtrod").attr("min",comeco);
            }
            });
            $("input[type='date']").change(function(){
            comeco = $("#data_filtroe").val();
            fim = $("#data_filtrod").val();   
            if(fim<comeco){
                document.querySelector('#data_filtrod').value = comeco;
                $("#data_filtrod").attr("min",comeco);
            }
            });
            // $("#datas").click(function(){
            //  $("#status_diat").modal();
            // });
            $("tr").click(function() {
            $('tr').not(this).css( "background-color", "white" );
            $(this).css("background-color", "gray");
            });
            });
            function relatorio_diario(){
            var comeco = $("#data_filtroe").val();
            var fim = $("#data_filtrod").val();
            var turma = $("#turma").val();
            jQuery.ajax({
                method: "get",
                url: "status_relatorio.php",
                data: { "comeco": comeco, "fim": fim, "turma": turma },
                success: function(data){
                    document.querySelector('#status_dia').innerHTML = data;
                }
            });
            }
            function verif(){
                if(!($("#status")[0])){ // Verifica se o id status não existe, se não existir ele executa o código
                    alert("Nenhum dado a ser impresso!");
                }else{
                    data = new Date();
                    var datai = $("#data_filtroe").val();
                    var dataf = $("#data_filtrod").val();
                    var turma = $("#turma").val();
                    jQuery.ajax({
                        method: 'post',
                        url: 'gera_pdf.php',
                        data: { 'datai': datai, 'dataf': dataf, 'turma': turma},
                        success: function( data ){
                            alert(data);   
                         }
                    });
                }
            }
            /* Função Ajax, consulta no banco de dados */
            function mostra_ocorrencias(nome_aluno){
            jQuery.ajax({
                type: "get",
                url: "pesquisa_individual.php",
                data: 'nome_aluno='+nome_aluno,
                success: function( data ){      
                    document.querySelector('#relatorio').innerHTML = data;
                }
            });
                // var xmlhttp = new XMLHttpRequest();
                // xmlhttp.onreadystatechange = function(){
                //  if(xmlhttp.readyState===4 && xmlhttp.status===200){
                //      document.getElementById('relatorio').innerHTML = xmlhttp.responseText;
                //  }
                // };
                // xmlhttp.open("GET","pesquisa_individual.php?nome_aluno="+nome_aluno,true);
                // var rel = xmlhttp.send();
                // document.querySelector('#relatorio').innerHTML = rel; 
            }
        </script>
    </head>
    <body>
        <div class="caixa" id="menu" title="Voltar ao Menu." data-toggle="modal" data-target="#sair_menu">
        <i class="fa fa-home fa-2x"></i>
        <br>
        <h4>Menu</h4>
        </div>
        <div class="caixa" title="Filtrar" id="datas" data-toggle="modal" data-target="#status_diat">
        <i class="fa fa-filter fa-2x"></i>
        <br>
        <h4>Filtrar</h4>
        </div>
        <div class="caixa" title="Gerar PDF" id="pdf" onclick="verif()">
        <i class="fa fa-file-pdf-o fa-2x"></i>
        <br>
        <h4>PDF</h4>
        </div>
        <h1>Coga</h1>
        <div id="sair_menu" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                    <h4 class="modal-title">Deseja Sair de Relatório?</h4>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="window.location = 'menu.php';">Sim</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Não</button>
                    </div>
                </div>
            </div>
        </div>
        <div id="status_dia" align="center">
        </div>
        <div id="status_diat" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Gerar Relatório:</h4>
                    </div>
                    <div class="modal-body">
                    <label id="textoe">De:</label><input type="date" name="data_filtro" id="data_filtroe" value="<?php 
                            setlocale( LC_ALL, 'pt_BR', 'pt_BR.iso-8859-1', 'pt_BR.utf-8', 'portuguese' ); 
                            date_default_timezone_set( 'America/Fortaleza' );
                            echo date('Y-m-d');?>">
                    <label id="textod">Até:</label><input type="date" name="data_filtro" id="data_filtrod" min="" value="<?php 
                            setlocale( LC_ALL, 'pt_BR', 'pt_BR.iso-8859-1', 'pt_BR.utf-8', 'portuguese' ); 
                            date_default_timezone_set( 'America/Fortaleza' );
                            echo date('Y-m-d');?>">
                    <br><br>
                    <label>Filtrar:</label><select name="turma" id="turma">
                        <option>Todas as Turmas</option>
                        <?php
                            $con = mysql_pconnect("localhost","root","eeep_#2017");
                            mysql_query("SET NAMES 'utf8'");
                            mysql_query('SET character_set_connection=utf8');
                            mysql_query('SET character_set_client=utf8');
                            mysql_query('SET character_set_results=utf8');
                            mysql_select_db("alunos",$con);
                            $sql = "select curso from alunos_turmas group by curso order by curso";
                            $result = mysql_query($sql,$con);
                            while ($linha = mysql_fetch_array($result)) {
                                echo "<option>".$linha['curso']."</option>";
                            }
                        ?>
                    </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" onclick="relatorio_diario()">Ok</button>
                    </div>
                </div>
            </div>
        </div>
        <div id="pesquisa">
        <!-- O attributo oninput executa alguma função jquery ou javascript quando o usuário digita -->
            Pesquisar: <input oninput="w3.filterHTML('#tabela_nome_alunos', '.valores', this.value)" type="text" placeholder="Digite algo sobre o aluno." title="Digite algo sobre o aluno.">
        </div>

        <div align="center" id="tabela_principal">
        <table align="center" id="tabela_nome_alunos">
            <tr id="cabecalho">
                <td>Número</td>
                <td>Nome</td>
                <td>Turma</td>
            </tr>
<?php
    $con = mysql_pconnect("localhost","root","eeep_#2017");
    mysql_query("SET NAMES 'utf8'");
    mysql_query('SET character_set_connection=utf8');
    mysql_query('SET character_set_client=utf8');
    mysql_query('SET character_set_results=utf8');
    mysql_select_db("alunos",$con);
    $sql = "select * from alunos_turmas group by nome order by curso, numero asc";
    $resultado = mysql_query($sql,$con);
    while($linha = mysql_fetch_array($resultado)){
?>
            <tr style="background-color: white;" id="<?php echo $linha['nome'];?>" class="valores" value="<?php echo $linha['nome'];?>" onclick="mostra_ocorrencias(id)">
                <td><?php echo $linha['numero'];?></td>
                <td><?php echo $linha['nome'];?></td>
                <td><?php echo $linha['curso'];?></td>
            </tr>
            <?php }?>
        </table>
        </div>
        <br>
        <div align="center" id="relatorio">
        </div>
    </body>
</html>

Code gera_pdf.php:

    <?php
    session_start();
    require_once ("dompdf/dompdf_config.inc.php");
    $datai = $_POST['datai'];
    $dataf = $_POST['dataf'];
    $turma = "curso='";
    $turma .= $_POST['turma']."'"." and ";
    if($turma=="Todas as Turmas"){
        $turma = "";
    }
    $resultado ="";
    $datas1 = DateTime::createFromFormat('Y-m-d',$_POST['datai']) -> format('d/m/Y');
    $datas2 = DateTime::createFromFormat('Y-m-d',$_POST['dataf']) -> format('d/m/Y');
    $con = new PDO("mysql:host=localhost;dbname=alunos", "root", "eeep_#2017"); 
    $result = $con->query("select * from ocorrencias where ".$turma."data>='$datai' and data<='$dataf'");
    $html = "
<!DOCTYPE html>
<html>
<head>
    <title>Geração de PDF</title>
    <meta charset='utf-8' http-equiv='Content-Type' content='text/html'>
    <link rel='stylesheet' type='text/css' href='css/estilo_gera_pdf.css'>

    <!-- DataTables CSS -->
    <link href='./css/datatables-plugins/dataTables.bootstrap.css' rel='stylesheet'>

    <!-- DataTables Responsive CSS -->
    <link href='./css/datatables-responsive/dataTables.responsive.css' rel='stylesheet'>
</head>
<body onload='print()'>
    <table width='100%' class='table table-striped table-bordered table-hover' id='dataTables-example'>
        <thead>
            <tr>
                <th>Líder</th>
                <th>Data</th>
                <th>Turma</th>
                <th>Aluno</th>
                <th>Tipo</th>
                <th>Justificativa</th>
            </tr>
        </thead>
        <tbody>";
            while ($linha = $result->fetch(PDO::FETCH_ASSOC)) { 
                $datamos = DateTime::createFromFormat('Y-m-d',$linha['data']) -> format('d/m/Y');
                $resultado .= "<tr style='background-color: white;' class='valores'><td>".$linha['lider']."</td><td>".$datamos."</td><td>".$linha['curso']."</td><td>".$linha['nome_aluno']."</td><td>".$linha['tipo']."</td>
            <td>"; 
            if($linha['obs']==''){
                $resultado .= '-';
            }else{
                $resultado .= $linha['obs'];
            }
            $resultado .= "</td>
        </tr>";
        }
        $html.=$resultado."</tbody>
    </table>


    <script src='./css/datatables/js/jquery.dataTables.min.js'></script>
    <script src='./css/datatables-plugins/dataTables.bootstrap.min.js'></script>
    <script src='./css/datatables-responsive/dataTables.responsive.js'></script>
    <script type='text/javascript'>
        $(document).ready(function(){
            $('#dataTables-example').DataTable({
                responsive: true
            });
        });
    </script>
</body>
</html>";
$dompdf = new DOMPDF ();
$dompdf-> load_html ($html);
$dompdf-> render ();
$dompdf-> stream ("sample.pdf");
?>

The error presented is this:

Illegal "string offset 'Hex' online 1150 style.cls.php"

  • Carlos is setting here jsPDF, their documentation does not seem to cover it. As soon as I can make the adjustments I post, I’m trying here. See you around.

  • That’s cool, after I answered the question that updated the cache! Af

  • What is the version of Dompdf that you’re using ?

1 answer

0


According to the documentation of jsPDF the plugin addHTML was discontinued.

You can use the plugin fromHTML.

There is a small difference between the two, which is the following:

addHTML

/*
 * @param element {Mixed} Elemento HTML, ou qualquer coisa suportada por html2canvas.
 * @param x {Number} iniciando a coordenada X nas unidades declaradas da instância jsPDF.
 * @param y {Number} iniciando a coordenada Y nas unidades declaradas da instância jsPDF.
 * @param options {Object} Opções adicionais, verifique o código abaixo.
 * @param callback {Function} para chamar quando a renderização tiver terminado.
 */
addHTML(element, x, y, options, callback)

fromHTML

/*
 * @param HTML {String or DOM Element} Texto formatado em HTML ou ponteiro para o elemento DOM que deve ser processado em PDF.
 * @param x {Number} iniciando a coordenada X nas unidades declaradas da instância jsPDF.
 * @param y {Number} iniciando a coordenada Y nas unidades declaradas da instância jsPDF.
 * @param settings {Object} Variáveis adicionais / opcionais que controlam a análise, renderização.
 * @param callback {Function} para chamar quando a renderização tiver terminado.
 */
fromHTML(HTML, x, y, settings, callback, margins)

Remarks

In the tests done by me, the method fromHTML worked in the version 1.0.272 above this version in my tests it did not apply the format defined in CSS.

Enter the full address for the files CSS, example:

http://exemplo.com.br/css/style.css

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script>
// var datai = $("#data_filtroe").val(); // Comentado apenas para teste
// var dataf = $("#data_filtrod").val(); // Comentado apenas para teste
// var turma = $("#turma").val(); // Comentado apenas para teste
$.ajax({
    method: 'get', // Alterei para GET apenas para fins de teste
    url: 'https://gist.githubusercontent.com/wellmotta/f23329f397c4d50a0f286ad488da5760/raw/7da6cf71f38b83d5718e99d796575c6441c5b948/boot_table.html',
    // data: { 'datai': datai, 'dataf': dataf, 'turma': turma}, // Comentado apenas para teste
    success: function(response){
        savePDF(response);
    }
});
function savePDF(codigoHTML) {
    var doc = new jsPDF('portrait', 'pt', 'a4'),
    data = new Date();
    margins = {
        top: 40,
        bottom: 60,
        left: 40,
        width: 1000
    };
    doc.fromHTML(codigoHTML,
    margins.left, // x coord
    margins.top, { pagesplit: true },
    function(dispose){
        doc.save("Relatorio - "+data.getDate()+"/"+data.getMonth()+"/"+data.getFullYear()+".pdf");
    });
}
</script>

You can see working perfectly here on jsbin

  • Your answer got in line "Low quality publications" because someone signaled her. I don’t know if it’s really a good answer or not, but at least it seems plausible that it is. However, when clicking the "Run" button, I didn’t see anything happen. Anyway, I will mark as "Seems OK" in the review queue.

  • Nothing happened because you need the file gera_pdf.php as there is no server to run the file.

  • The generated table it does not get the width on the full page how can I leave it to occupy the full width of the page? And when it exceeds the first page the next ones have no margin spacing at the top... How can I resolve?

Browser other questions tagged

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