Printing a Dynamically Loaded Iframe with jQuery

This is an example of printing a dynamically loaded iframe on a button click. This is useful for printing specific or generated reports or pages without leaving the current page.

The iframe to be targeted looks like this and can be placed virtually anywhere in the body tag:

<iframe id="iframeprint" width="1" height="1" frameborder="0"></iframe>

The button to be clicked for printing:

<p style="text-align:center"><a id="iframeprintbutton" href="#">Load and print page in iframe</a></p>

The jQuery on the calling page:

$().ready(function() {

	$('#iframeprintbutton').click(function() {
		$("#iframeprint").attr("src", "iframecontents.htm");
		return false;
     });

});

In the example, that page to be printed is in the same directory of the calling page. Use whatever URL will work for the location of the page you want to print. You can use absolute URLs. For example, http://yoursite.com/yourfile.htm.

All that is needed on the page to be printed is a call to the print function.

<script language="javascript">
 try
            {
                document.execCommand('print', false, null);
            }
            catch(e)
            {
                window.print();
            }
</script>

You could probably use straight javascript here, but I find jQuery quicker and easier to work with.

Usual recommended jQuery reading:

Demo

Download zip of all files

No related posts.

2 Comments

  • Alex
    January 26, 2011 - 1:23 pm | Permalink

    This solution doesnt work, it prints the page that contains the iframe, not the iframe content itself

  • Ecotech
    August 17, 2011 - 11:13 pm | Permalink

    Hello, I checked your this application, its very nice. I want to know is there any solution to print PDF document which will work on Mozilla Firefox 5

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>