Print the contents of a DIV

Slight changes over earlier version - tested on CHROME

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

EDIT It's been over 13 years since the plugin mentioned below was written, as per the comments, it doesn't work any more due to changed api in jQuery, feel free to fork and add a pull request!

Although this has been said by @gabe, If you are using jQuery, you can use my printElement plugin.

There's a sample here, and more information about the plugin here.

The usage is rather straight forward, just grab an element with a jQuery selector and print it:

$("#myDiv").printElement();

I hope it helps!


I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:

@media print {
    .myDivToPrint {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}