Printing selective DOM elements on a page

Printing web pages from JavaScript, although not a common scenario, can be easily accomplished with some simple code. On the other hand, selectively printing some elements from a web page – like a div or a paragraph, can be challenging. Fortunately there are libraries available that can make the task easier. One such useful jQuery plugin is jQuery PrintElement, which allows you to selectively print a DOM element. Usage is extremely easy; just select any element from a webpage and fire the ‘printElement’ method.

For example if you have a div like the following:

<div id="toPrint">Lorem ipsum dolor sit amet, consectetur adipisicing 
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi 
ut aliquip ex ea commodo consequat.
</div>
 
<a href="" id="printThis">Print This</a>

You can print the above div using the following, this will popup the browser print dialog box and allow you to only print the above selected div.

$('#toPrint').printElement();

Just make sure that the above code is defined correctly, as in the document ready function. The following code will print the ‘toPrint’ div whenever the ‘Print This’ link is clicked.

$(document).ready(function(){
    $("#printThis").click(function(){
       $("#toPrint").printArea();
    });
});

If the div is dynamically generated, as through a Ajax call, you can use the jQuery ‘live’ method.

$(document).ready(function(){
    $("#printThis").live("click",function() { 
       $("#toPrint").printArea();
    });
});

Of course you will also have to define a print css, with which you can neatly format the print output, a dummy example of which is shown below.

@media print {
    #toPrint {
        background-color: white;
        border: 2px dotted #c0c0c0;
        height: 500px;
        width: 600px;
        position: fixed;
        font-size: 14px;
        line-height: 18px;
        -webkit-box-shadow: none;
        -moz-box-shadow:  none;
    }
}

You can also directly add inline css as an option to the ‘printElement’ method.

$("#toPrint").printElement({
    printBodyOptions:
    {
        styleToAdd:'padding:10px;font-size: 20px;'
    }
});

More options to add to the ‘printElement’ method can be found at the plugin page.