There are multiple posts dealing with part of these topics, but none that puts them together.
On a given page, I wish to create a new IFRAME, add some JavaScript to it which will print the page to a printer, and add some HTML to it which will be printed.
Below is my attempt with a live demo at http://jsbin.com/UDUCADI/2/. It prints, but prints the parent page and not the IFRAME.
How do I just print the IFRAME?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Print IFRAME</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#printIt').click(function(){
var iframe = $('<iframe>');
var script = document.createElement("script");
script.type = "text/javascript";
script.text = "window.print()";
iframe[0].appendChild(script);
iframe.appendTo('body');
var iframeDocument=$(iframe[0].contentWindow.document);
iframeDocument.find('body').html($('#stuffToPrint').html());
})
});
</script>
</head>
<body>
<button id="printIt">Print</button>
<div id="stuffToPrint">
<p>Print this text!</p>
<img alt="And print this image" src="dropdown_arrow_blue.gif">
</div>
<div>Don't print this!</div>
</body>
</html>