Amit Kumar
Amit Kumar

Reputation: 195

How to print a HTML content using printer in php?

I have a HTML content in a variable like this.

$message ="<div>
    <table align='center'>
        <tr><td><h1>Reporte de Tipo de Documentos</h1></td></tr>
        <tr><td><h2>Farmaceutica MDC</h2></td></tr>
    </table>
</div>
<div>
    <table style='width:960px; margin:0 auto;'>
        <tr colspan='7'>
            <td><?php echo 'Fecha: '".$time = date('d/m/Y h:i:s A')."; ?></td>
        </tr>
        <tr bgcolor='#CCCCCC' height='30'>
            <td><b>Sr. No.</b></td>
            <td><b>Tipo Documento</b></td>
            <td><b>Cant. Pasos</b></td>
            <td><b>Costo</b></td>
            <td><b>Precio</b></td>
            <td><b>Balance</b></td>
            <td><b>Notifica Cliente</b></td>
        </tr>
    </table>";

I want to print a printout page of this HTML Content. Like for web page we use

<script type="text/javascript">
    function printpage()
    {

        window.print();

    }
</script>.

So what i use to print the above HTML content?

Upvotes: 3

Views: 17043

Answers (2)

Vainglory07
Vainglory07

Reputation: 5273

   <input type="submit" value="Print" onclick="printIframe(report);"/>
   <script>
       function printIframe(objFrame) {
           objFrame.focus();
           objFrame.print();
           bjFrame.save();
       }
   </script>
   <iframe name="report" id="report" src="report.php"></iframe>

try calling the form inside an iframe then a link or button that will run the js to print the html/php inside the iframe..

Upvotes: 2

AlexStack
AlexStack

Reputation: 17381

How about embedding the contents of this page in HTML and adding a script to print it out automatically on page load?

<?php
$message ="<div>
    <table align='center'>
        <tr><td><h1>Reporte de Tipo de Documentos</h1></td></tr>
        <tr><td><h2>Farmaceutica MDC</h2></td></tr>
    </table>
</div>
<div>
    <table style='width:960px; margin:0 auto;'>
        <tr colspan='7'>
            <td><?php echo 'Fecha: '".$time = date('d/m/Y h:i:s A')."; ?></td>
        </tr>
        <tr bgcolor='#CCCCCC' height='30'>
            <td><b>Sr. No.</b></td>
            <td><b>Tipo Documento</b></td>
            <td><b>Cant. Pasos</b></td>
            <td><b>Costo</b></td>
            <td><b>Precio</b></td>
            <td><b>Balance</b></td>
            <td><b>Notifica Cliente</b></td>
        </tr>
    </table>";

echo "<html><head></head><body>" . $message . "<script type='application/javascript'>window.onload=function(){window.print()}</script></body></html>";
?>

To literally print the HTML code, you can sanitize the HTML like:

echo "<html><head></head><body>" . htmlspecialchars($message, ENT_QUOTES) . "<script type='application/javascript'>window.onload=function(){window.print()}</script></body></html>";
?>

More information about this:

Upvotes: 6

Related Questions