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
Jack, have you tried window.print() inside the iframe after loading the document?
Why not just make everything invisible for media=print and then make visible only some blocks with your special code?
Print() is a method on the window object. If you create a document in a window using javascript, then call print on that window object, it should work.
<script type="text/javascript">
var myWindow = window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
myWindow.print();
</script>
Example modified from w3schools.com window open example.
If you are doing this while the document is being loaded, you can use document.write
to write the current document, then print it.
If the page has finished loading, you can use functions to manipulate the DOM, or preferably use a library such as jQuery or Prototype, then print the current document.
print() essentially just calls up the native print dialog for a given window.
But as you're are thinking, it will work on any window or (i)frame.
thus if you write content to a frame, you can then call this to print it.
window.frameName.print();
note the only drawback (and its a big one), is that this calls up the print dialog... not the print preview window... thus the user doesn't really get a chance to see what they are printing and/or scale it to fit their printer/paper.
I personally wish that all browsers would implement the following to handle the above issue. ;-)
window.printPreview();
There are three approaches to printing two of which will work.
Print the entire window: window.print();
will work.
Print only a specific frame: window.parent._frame_id_.print();
will work.
Print a documentFragment
will not work (at least in Firefox):
document.createDocumentFragment().print();//undefined