create print button for each table

Asked

Viewed 1,144 times

1

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

Code I am 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 print, prints the three tables, but I wanted to for example just print the first table and the other two not or print the last and the other two not print.

1 answer

1


Let me start by saying that you can control what you print on a CSS-only page by hiding the elements you don’t want to appear.

This is done either with the @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 at 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 showing different things. In this case you really have to use Javascript to do this.

Using a existing response in the English OS can do so:

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 to be able to use this function you need to define labels and respective id’s for each of them. In this sense you can change the echos that of the tables for:

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

Browser other questions tagged

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