How to Print a Div Content Using jQuery

Last updated 1 week, 6 days ago | 42 views 75     5

Printing specific content from a web page can be incredibly useful, especially when you want to focus on a particular section. With jQuery, you can easily achieve this. Here's how.

HTML Structure

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Print Div Content</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #printArea {
      border: 1px solid #000;
      padding: 20px;
      margin: 20px 0;
    }
  </style>
</head>

<body>
  <h1>Print Div Example</h1>

  <div id="printArea">
    <p>This is the content inside the div that will be printed.</p>
    <p>Only this section will be printed.</p>
  </div>

  <button id="printButton">Print Content</button>

  <script>
    $('#printButton').click(function () {
      var divContent = $('#printArea').html();
      var originalContent = $('body').html();

      $('body').html(divContent);
      window.print();
      $('body').html(originalContent);
    });
  </script>
</body>

</html>

Explanation

  1. HTML Structure: The page contains a div with the content to be printed and a button to trigger the print action.

  2. jQuery Script:

    • Captures the HTML content of the target div.

    • Temporarily replaces the page's content with the div content.

    • Calls window.print() to open the print dialog.

    • Restores the original page content after printing.

Additional Tips

  • Use @media print {} CSS rules to control the print layout.

  • For more complex scenarios, like preserving original page scripts or handling multiple sections, consider using an iframe.

Conclusion

By following this approach, you can easily allow users to print specific sections of a webpage without altering the original design. This method is particularly helpful for generating reports, invoices, or any custom content for printing.