Send data to Iframe and Print
Send data to Iframe and Print
by Adi Jaya
HTML
<div id="demo">
<h2>hello world</h2>
<p>Lorem Ipsum</p>
<img alt="cats" src="http://lorempixel.com/200/200/cats/1/"/>
<pre>Hell0========== world :-D</pre>
</div>
<!-- other content [ no print ] -->
<ul>
<li>lorem</li>
<li>ipsum</li>
<li>dolor</li>
<li>sit amet</li>
</ul>
<hr>
<hr>
<button onclick="sendToIframe()">Send Data To Iframe</button>
<button onclick="printIframe()">Print Iframe</button>
<br>
<iframe id="preview"></iframe>
JavaScript
function sendToIframe( iframeID="preview", contentID="demo" ){
alert( "test" );
var iframe = document.getElementById( iframeID ); //default = preview
var content = document.getElementById( contentID ).innerHTML; //default = demo
var docIframe = iframe.contentDocument || iframe.contentWindow.document;
var inlineCSS = "html {font-family: sans-serif} h2 {color: blue}";
var urlPrintCSS = ""; // exp => https://example/print.css
var template = ""
template += "<!DOCTYPE html>";
template += "<html>";
template += "<head>";
template += "<meta charset='UTF-8'>";
template += "<meta content='width=device-width, initial-scale=1' name='viewport'/>";
template += "<title>Test Demo</title>";
template += "<style>"+ inlineCSS +"</style>";
if( urlPrintCSS ){
template += "<link href='"+ urlPrintCSS +"' rel='stylesheet'/>";
}
template += "</head>";
template += "<body>";
template += "<div data-content='layer'>";
template += content;
template += "</div>";
template += "</body>";
template += "</html>";
docIframe.open();
docIframe.write( template );
docIframe.close()
}
/* how to use
sendToIframe( IDselectorIframe, IDselectorElement );
*/
//example
/*
sendToIframe( "iframePrint", "doc-print" );
in html
<iframe id="iframePrint"></ifrme>
<div id="doc-print">hi....</div>
with click button
<button onclick="sendToIframe( parameter1, parameter2 )"></button>
*/
//for this demo
/*
sendToIframe( "preview", "demo" );
//or
sendToIframe(); //without parameter, see default parameter
*/
// print contents iframe
function printIframe( iframeID="preview" ){
var iframe = document.getElementById( iframeID ); //default = preview
iframe.contentWindow.print();
}