Monday, April 16, 2012

Print Page Content to printer (or virtual print output) in ASP.NET using iFrame

Sometimes, there is a need to give user a facility to print the web page contents (or part of them) as they appear in their browser.

This article is to explain how we can achieve the same using iFrame, and javascript:

While designing your webpage, you should decide which contents should allowed to be printed, and can wrap them within DIV or any HTML container. (You can also print all contents of your page)

For this example, lets assume the DIV (with ID - "divFormContents") contains the contents you facilitate users to print.

Now, add an iFrame (with id = ifmContents, and with following style) in your webpage:

height: 0px; width: 0px; position: absolute

Write following javascript in your webpage.


function printPageContents() {
var content = document.getElementById("divFormContents");
var printContents = document.getElementById("ifmContents").contentWindow;
printContents.document.open();
printContents.document.write(content.innerHTML);
printContents.document.close();
printContents.focus();
printContents.print()
}

Finally, write a call to this javascript method (printPageContents())

That's all we need to do, and the users will now be able to print all the contents that reside within the container ("divFormContents") in our example

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive