Today I worked on printing the contents of a <div> tag. The first solution I found was to use java script to open a new window, write the contents of the <div> to it and use the window.print() function. It works well, but what I wanted to print was already being displayed in an iFrame, dialog like over the main window. I did not like opening yet another window in order to print.
The document has a Print button with an onclick event.
<button type="button" onclick="printMessage()">Print</button>
This is the function called by the button onclick event. This function gets the content from the div element and in turn calls the printElemContent function that does the actual printing
function printMessages(sender, args) { var responseDiv = $('#<%=uxResponseMessageDiv.ClientID %>'); if (responseDiv != null) { printElemContent(responseDiv.html()); }
Printing using a new window:
function printElemContent(data) { var myWindow = window.open('', 'my div', 'height=400, width=600'); myWindow.document.write('<html><head><title></title>'); myWindow.document.write('<html><body>'); myWindow.document.write(data); myWindow.document.write('</body></html>'); myWindow.document.close(); myWindow.focus(); myWindow.print(); myWindow.close(); return true; }
The above code works, and it solved my need, but like I said, it bothered me that I was opening another window. Also, once the window was opened, but had not yet opened the print dialog, I was left sitting in front of the screen wondering if I was supposed to do something, and I knew what was going on. There is a couple of seconds delay after showing the new window and before the print dialog is opened. What are my users going to be thinking when they try to print? I searched some more and came across a solution using jQuery and an off-screen iframe that did not require opening another window and to me works more smoothly and possibly more quickly. The difference between javascript and jQuery is not important to this. I personally prefer jQuery’s syntax so I tend to gravitate toward it and point it out here only so those less familiar will not miss the difference.
Printing using an iFrame:
Add an iframe tag somewhere in your document.
<iframe id="ifmcontentstoprint" style="position: absolute; top: -1000px; left: -1000px;"></iframe>
function printElemContent(data) { var iframe = $('#ifmcontentstoprint')[0]; var body; body = '<html><head><title></title>' + '<html><body>' + data + '</body></html>' iframe.contentDocument.write(body); iframe.contentDocument.close(); var iframeWindow = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView; iframeWindow.focus(); iframeWindow.print(); return true; }
So there you have it. How to print the contents of a <div>, another element or anything else you might want to print, so long as you can write it into an iframe.