52

I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer.

This is is my HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>

Here I want to print the content of the div printarea.

I tried this:

$("#btn").click(function () {
    $("#printarea").print();
});

But it gives a console error when the button is clicked:

Uncaught TypeError: $(...).print is not a function

But when I am trying to print the entire page using

window.print();

it is working. But I only want to print the content of a particular div. I saw the answer $("#printarea").print(); in many places , but this is not working.

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97
  • 2
    You could setup a stylesheet with `media="print"` on it that hides all non-relevant content. – Rory McCrossan Nov 16 '15 at 10:08
  • You're looking for a CSS solution here actually, [this](http://stackoverflow.com/questions/7440976/how-to-print-a-part-of-my-page-using-jquery) is an easy setup for your purpose - it hides all the page elements except the ones with the class `.printable` – SidOfc Nov 16 '15 at 10:12
  • Using the JavaScript tag might be a good idea if you want to attract good answers: http://meta.stackoverflow.com/questions/290244/suggested-edits-do-questions-need-both-javascript-and-jquery-tags – Anders Nov 16 '15 at 10:34
  • Possible duplicate of [Print the contents of a DIV](http://stackoverflow.com/questions/2255291/print-the-contents-of-a-div) – Govind Samrow Jul 23 '16 at 14:12

15 Answers15

87

Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).

And it is working well...

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>

JavaScript

function printDiv() 
{

  var divToPrint=document.getElementById('DivIdToPrint');

  var newWin=window.open('','Print-Window');

  newWin.document.open();

  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

  newWin.document.close();

  setTimeout(function(){newWin.close();},10);

}
Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97
44

https://github.com/jasonday/printThis

$("#myID").printThis();

Great jQuery plugin to do exactly what you're after

andreini
  • 188
  • 1
  • 3
  • 17
CiaranSynnott
  • 908
  • 5
  • 9
  • Uncaught TypeError: $(...).printThis is not a function – Abdelrahman Farag Mar 02 '21 at 16:11
  • @AbdelrahmanFarag check if you are including JQuery properly in your webpage. You can try the CDN option specified here: https://www.w3schools.com/jquery/jquery_get_started.asp – Eaweb Mar 03 '21 at 11:51
10

If you want to do this without an extra plugin (like printThis), I think this should work. The idea is to have a special div that will be printed, while everything else is hidden using CSS. This is easier to do if the div is a direct child of the body tag, so you will have to move whatever you want to print to a div like that. S So begin with creating a div with id print-me as a direct child to your body tag. Then use this code to print the div:

$("#btn").click(function () {
    //Copy the element you want to print to the print-me div.
    $("#printarea").clone().appendTo("#print-me");
    //Apply some styles to hide everything else while printing.
    $("body").addClass("printing");
    //Print the window.
    window.print();
    //Restore the styles.
    $("body").removeClass("printing");
    //Clear up the div.
    $("#print-me").empty();
});

The styles you need are these:

@media print {
    /* Hide everything in the body when printing... */
    body.printing * { display: none; }
    /* ...except our special div. */
    body.printing #print-me { display: block; }
}

@media screen {
    /* Hide the special layer from the screen. */
    #print-me { display: none; }
}

The reason why we should only apply the @print styles when the printing class is present is that the page should be printed as normally if the user prints the page by selecting File -> Print.

Anders
  • 8,307
  • 9
  • 56
  • 88
10

None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.

HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p

Javascript:

function printFunc() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
    }
jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160
BibanCS
  • 309
  • 3
  • 9
9

Without using any plugin you can opt this logic.

$("#btn").click(function () {
    //Hide all other elements other than printarea.
    $("#printarea").show();
    window.print();
});
Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38
  • 3
    Prints everything in the page on Mozila firefox – zeddarn Oct 11 '16 at 09:33
  • 3
    Prints everything in the page on Chrome v.72, too. – cheeseus Mar 26 '19 at 17:14
  • Have a div with the class ```.container```, and I have certain elements outside of that div like a search bar and a button, that I do not want to show on the print page. When I select ```$(".container").show()``` it still prints everything... – BeerusDev Feb 09 '21 at 14:46
8

I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >

JavaScript

        function printtag(tagid) {
            var hashid = "#"+ tagid;
            var tagname =  $(hashid).prop("tagName").toLowerCase() ;
            var attributes = ""; 
            var attrs = document.getElementById(tagid).attributes;
              $.each(attrs,function(i,elem){
                attributes +=  " "+  elem.name+" ='"+elem.value+"' " ;
              })
            var divToPrint= $(hashid).html() ;
            var head = "<html><head>"+ $("head").html() + "</head>" ;
            var allcontent = head + "<body  onload='window.print()' >"+ "<" + tagname + attributes + ">" +  divToPrint + "</" + tagname + ">" +  "</body></html>"  ;
            var newWin=window.open('','Print-Window');
            newWin.document.open();
            newWin.document.write(allcontent);
            newWin.document.close();
           // setTimeout(function(){newWin.close();},10);
        }
Akram Elhaddad
  • 194
  • 3
  • 7
8

Below code from codepen worked for me as I wanted,

function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

$('button').on('click',function(){
printData();
})

Here is a link codepen

AmarjaPatil4
  • 1,640
  • 3
  • 28
  • 41
  • does not work in IE. For IE: var printContent = document.getElementById("PrintContent"); var windowUrl = 'Job Receipt'; var uniqueName = new Date(); var windowName = 'Print' + uniqueName.getTime(); var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0'); printWindow.document.write(printContent.innerHTML); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close(); – mzonerz Apr 24 '19 at 09:54
5

use this library : Print.JS

with this library you can print both HTML and PDF.

<form method="post" action="#" id="printJS-form">
    ...
 </form>

 <button type="button" onclick="printJS('printJS-form', 'html')">
    Print Form
 </button>
Naveed Ahmed
  • 463
  • 4
  • 11
5
<div id='printarea'>
    <p>This is a sample text for printing purpose.</p> 
</div>
<input type='button' id='btn' value='Print' onlick="printDiv()">
<p>Do not print.</p>

function printDiv(){
        var printContents = document.getElementById("printarea").innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
}

This Above function should be load on same page.

Balamurugan M
  • 580
  • 5
  • 9
5

First include the header

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> 

<script type="text/JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.6.0/jQuery.print.js"></script>

As you are using a print function with a selector which is a part of print.js so you need to call them before you use it...

Else 
    window.print()  

will do it

$("#btn").click(function () {
    $("#printarea").print();
});

or

$("#btn").on('click',function () {
    $("#printarea").print();
});
Herman Neple
  • 156
  • 12
Ankit Ankola
  • 51
  • 1
  • 2
2

I tried all the non-plugin approaches here, but all caused blank pages to print after the content, or had other problems. Here's my solution:

Html:

<body>
<div id="page-content">        
    <div id="printme">Content To Print</div>
    <div>Don't print this.</div>
</div>
<div id="hidden-print-div"></div>
</body>

Jquery:

    $(document).ready(function () {
        $("#hidden-print-div").html($("#printme").html());
    });

Css:

    #hidden-print-div {
        display: none;
    }

    @media print {
        #hidden-print-div {
            display: block;
        }

        #page-content {
            display: none;
        }
    }
Timothy Kanski
  • 1,861
  • 14
  • 20
2

Below code uses no library. works fine.

HTML CODE

<div id="printDoc">
<p> Print Me ! </p>
</div>
<input type='button' id='btn' value='Print' onclick='printDiv("printDoc");' >

JavaScript CODE

<script>
        function printDiv(printDoc){
            var restorepage = document.body.innerHTML;
            var printcontent = document.getElementById(printDoc).innerHTML;
            document.body.innerHTML = printcontent;
            window.print();
            document.body.innerHTML = restorepage;
        }
</script>
uhg3
  • 21
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 08 '23 at 07:55
  • Thank you, this solved my problem – Dwight Jul 21 '23 at 23:42
1

Take a Look at this Plugin

Makes your code as easy as -> $('SelectorToPrint').printElement();

ahervin
  • 461
  • 2
  • 15
1

Print only selected element on codepen

HTML:

<div class="print">
 <p>Print 1</p>
 <a href="#" class="js-print-link">Click Me To Print</a>
</div>

<div class="print">
 <p>Print 2</p>
 <a href="#" class="js-print-link">Click Me To Print</a>
</div>

JQuery:

$('.js-print-link').on('click', function() {
  var printBlock = $(this).parents('.print').siblings('.print');
  printBlock.hide();
  window.print();
  printBlock.show();
});
Denis
  • 300
  • 2
  • 10
0

CSS CODE

<style type="text/css">
    table {border-collapse: collapse; width: 100%; margin-bottom: 10px; width: 450px;}
    table, th, td {border: 1px solid #000000;}
    @media print {
        .print-btn{
            display: none;
        }
    }
</style>

HTML CODE

<table>
    <tbody>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>      
            <th>Points</th>
        </tr>
        <tr>
            <td>Jill</td>
            <td>Smith</td>      
            <td>50</td>
        </tr>
        <tr>
            <td>Eve</td>
            <td>Jackson</td>        
            <td>94</td>
        </tr>
        <tr>
            <td>John</td>
            <td>Doe</td>        
            <td>80</td>
        </tr>
        <tr>
            <td>Adam</td>
            <td>Johnson</td>        
            <td>67</td>
        </tr>
    </tbody>
</table>
<button class="print-btn" onclick="window.print()">Print me</button>

OUTPUT enter image description here

Ram Pukar
  • 1,583
  • 15
  • 17