How do I use JavaScript to print content to a div?
I would like to use the print () function to print the content <div class="pagecontent"></div>
I know you can do something like onClick="window.print()"
, but this prints the whole window ... I want the content to .pagecontent
be printed.
What's the easiest way to do this with JavaScript or jQuery?
source to share
The easiest way is to define the stylesheet that applies to @media=print
. This would basically have something like:
* {
display: none; /* hide all elements when printing */
}
.pageContent {
display: block; /* make any class="pageContent" elements visible while printing */
}
Of course, this would make the pageContent elements visible, but everything inside them would still be invisible from the rule *
. You will have to play with this and only list the top level items that should be hidden.
source to share
You can add the content of the element to the iframe and then print the iframe.
HTML -
<span>Print Just Me.</span> I'll be omitted.<br />
<iframe id="iframe"></iframe>
JS -
$('span').on('click', function () {
$('#iframe').contents().find('body').html($(this).html());
window.frames['iframe'].print();
});
Here's a demo: http://jsfiddle.net/zaF3K/
You can also hide the iframe to make it happen behind the scenes:
#iframe {
display : none;
}
Here's a demo: http://jsfiddle.net/zaF3K/1/
source to share
if you want to use javascript than try this
window.printItn = function() {
var printContent = document.getElementById('pagecontent');
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
// you should add all css refrence for your html. something like.
var WinPrint= window.open(windowUrl,windowName,'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<'+'html'+'><head><link href="cssreference" rel="stylesheet" type="text/css" /></head><'+'body style="background:none !important"'+'>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write('<'+'/body'+'><'+'/html'+'>');
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
See demo : http://jsfiddle.net/mu8BG/1/
source to share