Others



How To Print Page With CSS Style Using JavaScript


The following example shows how to Print page or element with css styles using JavaScript.

Example
<html>
  <head>
    <meta charset='utf-8'>
    <style>
      h1{
        font-size:20px;
        color:#808080;
      }
      p{
        text-indent:20px;
        text-align:justify;
        line-height:25px;
      }
      table{
        border-collapse:collapse;
      }
      table td,table th{
        border:1px solid #ccc;
        padding:5px;
      }
    </style>
    <script>
    function printPage()
    {
      var printStyle = document.querySelector("style");
      
      var printBox = document.querySelector("#printBox");
      var printWidndow = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
      printWidndow.document.write("<style>"+printStyle.innerHTML+"</style>"+printBox.innerHTML);
      printWidndow.document.close();
      printWidndow.focus();
      printWidndow.print();
      printWidndow.close();
    }
    </script>
  </head>
  <body>
    <div id='printBox'>
      <h1>Sample Heading</h1>
      <p>The alarm went off and Jake rose awake. Rising early had become a daily ritual, one that he could not fully explain. From the outside, it was a wonder that he was able to get up so early each morning for someone who had absolutely no plans to be productive during the entire day.</p>
      <table>
        <thead>
          <tr>
            <th>Country</th>
            <th>Capital City</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Afghanistan</td>
            <td>Kabul</td>
          </tr>
          <tr>
            <td>Australia</td>
            <td>Canberra</td>
          </tr>
          <tr>
            <td>India</td>
            <td>New Delhi</td>
          </tr>
          <tr>
            <td>Malaysia</td>
            <td>Kuala Lumpur</td>
          </tr>
        </tbody>
      </table>
    </div><br>
    <input type='button' value='Print' onclick='printPage()'>
  </body>
</html>
Try it Yourself

Live Demo