create print button for each of the table

1

I have 3 different tables on the same php page and I plan to print each table separately from one another.

Code that I'm using:

<?php
echo $tabela3;
echo $tabela4;
echo $tabela5;
echo "<td><form action='#' method='post'><input type=button name=imprime value='Imprimir' onclick='javascript:DoPrinting();'><td></form></center>";
?>
<script language="JavaScript">
function DoPrinting()
{
   if (!window.print)
   {
      alert("Use o Netscape ou Internet Explorer \n nas versões 4.0 ou superior!")
      return
   }
   window.print()
}
</script>

But this way whenever I do print, it prints the three tables, but I wanted to for example only print the first table and the other two do not or print the last one and the other two do not print.     

asked by anonymous 09.05.2018 / 10:18

1 answer

1

I'll start by saying that you can control what prints on a page with only CSS, hiding the elements you do not want to appear.

This is done either with @media print on the page in question, in addition to the rest of the CSS that it already has:

@media print {
    .elementos-a-esconder-na-impressao {
        display:none;
    }
}

Or by creating two different style files, one for normal viewing and one for printing, which includes the top with <link> :

<link rel="stylesheet" href="normal.css" media="screen"><!--normal-->
<link rel="stylesheet" href="impressao.css" media="print"><!--para impressão-->

In your case however it is more complicated because you want to print 3 different versions on the same page based on a click of a button, and each one showing different things. In this case you have to use Javascript to do this.

Serving me from an existing answer in the English OS can do this:

function printElem(elemID)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elemID).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

Now in order to use this function, you need to define labels and ids for each of them. In this sense, you can change the echos of the tables to:

echo "<div id='tabela3'>$tabela3</div>";
echo "<div id='tabela4'>$tabela4</div>";
echo "<div id='tabela5'>$tabela5</div>";

And now you can have 3 buttons each by printing the corresponding table, through your id :

echo "<button onclick='printElem(\"tabela3\")'>Imprimir tabela 3</button>";
echo "<button onclick='printElem(\"tabela4\")'>Imprimir tabela 4</button>";
echo "<button onclick='printElem(\"tabela5\")'>Imprimir tabela 5</button>";
    
09.05.2018 / 12:14