November

3

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.

No comments yet.

Leave a comment

Why ask?

 

« | »