How to print a page in PHP to print using printer same as window.print() works

97,644
 <script type="text/javascript">     
    function PrintDiv() {    
       var divToPrint = document.getElementById('divToPrint');
       var popupWin = window.open('', '_blank', 'width=300,height=300');
       popupWin.document.open();
       popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
        popupWin.document.close();
            }
 </script>




<div id="divToPrint" style="display:none;">
  <div style="width:200px;height:300px;background-color:teal;">
           <?php echo $html; ?>      
  </div>
</div>
<div>
  <input type="button" value="print" onclick="PrintDiv();" />
</div>
Share:
97,644
Naresh
Author by

Naresh

profile for Puzzled Boy on Stack Exchange, a network of free, community-driven Q&amp;A sites http://stackexchange.com/users/flair/2100519.png

Updated on July 09, 2022

Comments

  • Naresh
    Naresh almost 2 years

    Actually i want to print the content with below code sample.

    $html having my all HTML which i want to print without render a View in Browser and without print/show in browser.

    I am trying to find a Same method as window.print(); works. But need in PHP. I don't want to show all the HTML in Browser.

    Is there any method or Trick ? Any suggestion can help me lot. Thank you.

    My Sample Code:

    $arr = array('one','two','three','four','five');
    $html = "<div style='background:red;color:black;'>";
    foreach($arr as $value){
        $html .= $value.'<br />';
    }
    $html .= "</div>"; 
    
    // print code to print $html content as same as JS window.print() works.
    
  • arefindev
    arefindev almost 9 years
    This was an awesome solution. It helped me a lot.
  • ram914
    ram914 over 6 years
    Can you write it in jQuery??