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:
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>
Take a Look at this Plugin
Makes your code as easy as -> $('SelectorToPrint').printElement();
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();
});
//Learn more: www.tenoclocks.com
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();
});
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
JQuery:
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();
}
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