Sometimes it is necessary to make a printed copy of the created document from web. So creating an option of printing the page may need for a developer to create for the user. But like other library applications (Microsoft Word, Microsoft Excel) this is not so simple. You have to add something in coding and styling the page a little bit for a better feel of the page.
For printing a general page without noticing styles it is very much easy. You just have to add a line of JavaScript code for doing that.
<a href="#" onclick="window.print();">Print Me</a>
But the main problem of the method is that, it prints all the elements of the page at a time. So, if we want our user to print a particular div or section of a page. We have to think about a little bit. I have a used a little JavaScript plugin for doing this job easily. You just have to call the plugin and have to initialize it. Like below,
<script src="jquery.PrintArea.js_4.js"></script>
<script>
$(function() {
$('.print').click(function() {
$('#type the div id or class you want to print').printArea();
return false;
});
});
</script>
In the ‘#type the div id or class you want to print’ you have to type your desired div id or class name. You can easily download the plugin file from here.
Now, comes the tricky part of the print page. What if you want to print the div in another style that is not like the page user is seeing. For doing this you have to add some CSS.
It is better to use a CSS file for printing the page. It will execute when the page will print. You can add the CSS like below.
<link rel="stylesheet" type="text/css" href="theme.css" media="print">
Or you can add the CSS for the print like below.
@media print
{
#type the div id or class you want to print{display:block;}
}
@media screen
{
#type the div id or class you want to print{display:none;}
}
Now in the CSS file, edit the div and images that you want to view in the print layout. and edit in the screen layout edit the CSS that you want to see at the screen but not at the print.
In many forums I have seen a common question that how to print a div that is hidden along with a button click.
With the CSS you can control this. Just make the div hidden for general view and make it visible while it is in the print mode. From the above CSS you can control this.
Hope this help you. Thanks.