jQuery Print Function to Print Div Content with CSS

Last updated 1 month ago | 58 views 75     5

Tags:- HTML JQuery CSS

Printing specific div content with CSS styling using jQuery is a common requirement when generating reports or invoices. Here's a comprehensive solution that allows you to print multiple div elements while preserving CSS styling.

✅ 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 with CSS</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #printDiv1, #printDiv2 {
      padding: 20px;
      margin-bottom: 20px;
      border: 2px solid black;
    }

    #printDiv1 {
      background-color: lightyellow;
    }

    #printDiv2 {
      background-color: lightblue;
    }

    @media print {
      body * {
        visibility: hidden;
      }

      .print-content, .print-content * {
        visibility: visible;
      }

      .print-content {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
      }
    }
  </style>
</head>

<body>
  <h1>jQuery Print Div with CSS Example</h1>

  <div id="printDiv1">
    <p>This is the first div that will be printed.</p>
  </div>

  <div id="printDiv2">
    <p>This is the second div that will be printed.</p>
  </div>

  <br>
  <button onclick="printMultipleDivs(['#printDiv1', '#printDiv2'])">Print Both Divs</button>

  <script>
    function printMultipleDivs(divIDs) {
      let printContent = '';

      divIDs.forEach(function (divID) {
        printContent += $(divID).html();
      });

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

</html>

???? Explanation

  1. HTML Structure: Two div elements with unique content and a button to trigger the print action.

  2. CSS for Print Handling:

    • The @media print rule hides all content except the specified div elements.

  3. jQuery Functionality:

    • Combines the content of the specified div elements.

    • Temporarily replaces the body content with the selected content for printing.

    • Restores the original content after printing.

✅ Benefits

  • Allows you to print multiple div elements sequentially.

  • Preserves the original page layout after printing.

By following this approach, you can efficiently handle multiple print targets with ease.