Wednesday, November 14, 2012

Use Javascript to Print Content of a Div


Simple note

Copy all content to a new window (with styles if any) then call window.print()

Code

<html>
    <head>
        <script type="text/javascript">
            function printContent (divId) {
                // open a new window
                var mywindow = window.open('', '', 'height=400,width=600'),
                    mwindoc = mywindow.document;
                // write content to new window
                mwindoc.write('<html><head><title>my div</title>');
                var links = document.getElementsByTagName('head')[0].getElementsByTagName('link'),
                    i;

                // add styles to new window
                for (i = 0; i < links.length; i++) {
                    var link = links[i],
                        lcnt = '<link'
                            + (link.rel? ' rel="'+link.rel+'"' : '')
                            + (link.type? ' type="'+link.type+'"' : '')
                            + (link.href? ' href="'+link.href+'"' : '')
                            + ' />';
                    //alert(lcnt);
                    mwindoc.write(lcnt);
                }
                mwindoc.write('</head><body >');
                // add contents to print to new window
                // the divId is the assigned div id
                mwindoc.write(document.getElementById(divId).innerHTML);
                mwindoc.write('</body></html>');

                // call print function then close the new window
                mywindow.document.close();
                mywindow.focus();
                mywindow.print();
                mywindow.close();

                return true;
            }
        </script>
    </head>
        <div id="content">
            <div style="color: green; font-size: 36px;">
                The content to print
            </div>
        </div>
        <button onclick="printContent('content');">Print</button>
</html>


Result

Print window (not browser window) appeared after 'Print' button clicked

References

http://stackoverflow.com/questions/2255291/print-the-contents-of-a-div

http://stackoverflow.com/questions/2555697/window-print-not-working-in-ie

Download

File at github
https://github.com/benbai123/HTML_CSS_Javascript_practice/blob/master/javascript/use_javascript_to_print_contents_of_a_div.html

2 comments:

  1. Replies
    1. They are almost the same, please refer to http://zkfiddle.org/sample/216k6a/1-Print-Div-Content

      Delete