I know you can use window.print() to print the current page... but what I want to know is can I build a document using javascript in order to populate it with data and print it
My first thought:
You could create an iframe programmatically, assign the HTML to be printed, call the print()
function on the context of the iframe.contentWindow, and then remove the iframe from the DOM:
function printHTML(input){
var iframe = document.createElement("iframe"); // create the element
document.body.appendChild(iframe); // insert the element to the DOM
iframe.contentWindow.document.write(input); // write the HTML to be printed
iframe.contentWindow.print(); // print it
document.body.removeChild(iframe); // remove the iframe from the DOM
}
printHTML('Test!
');
You can test the above snippet here.