In order to open a print dialog for the current page we do something like so:
<a href="javascript:window.print()">Print</a>
How to make a link in the current page that will open the print dialog with different context than the actual page?
Print dialog box in Chrome:
After playing around (and some googling), I came out with this solution:
I added a non-printable
class to the current view and printable
class to the printable container element. In my CSS, I used css media queries where @media screen
and @media print
states contains the corresponding display behavior:
@media screen {
.printable { display: none; }
.non-printable { display: block; }
}
@media print {
.printable { display: block; }
.non-printable { display: none; }
}
Now, I can print new content from my current view without opening a new tab or changing my current view.
Check out this jsFiddle and the supported browser's list.
Include printable content in a div. Like:
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();
}
It will just print the printable div.Thanks
There's a nice Javascript plugin called PrintThis that accomplishes this very easily.
You just need to use a jQuery
selector and call the plugin, e.g.:
$('selector').printThis();
https://github.com/jasonday/printThis
I'm not sure if this is actually an answer to your question since your question has very little detail about what you mean by opening a new window.
If you are on /page/one and you want to have a link open /report/page and automatically bring up the print dialog...then that is as easy as triggering window.print
on the load event, e.g.
<body onload='window.print()'>
If you don't want that page to always open the print dialog, then make the link to the new page /report/page?print=1
or something to that effect when you want to print, and when you find that in the URL trigger the onload event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With