I would like to know if it\'s possible to use javascript to open a popup window containing an image, and at the same time have the print dialog show. Once someone clicks on
I wrote a coffee script function that does that (but without opening a new window):
@print_img = (url) ->
$children = $('body').children().hide()
$img = $('<img>', src: url)
$img.appendTo('body')
$img.on 'load', ->
window.print()
$(this).remove()
$children.show()
Or if you prefer in javascript:
this.print_img = function(url) {
var $children, $img;
$children = $('body').children().hide();
$img = $('<img>', {
src: url
});
$img.appendTo('body');
$img.on('load', function() {
window.print();
$(this).remove();
$children.show();
});
};
This function makes sure that the elements on the body are hidden and not redrawn into the DOM. It also makes sure that the image is loaded before calling print (if the image is too large and the internet connection is slow, it may take a while to load the img, if you call print too soon, it will print an empty page)
popup = window.open();
popup.document.write("imagehtml");
popup.focus(); //required for IE
popup.print();
This code will open YOUR_IMAGE_URL in a popup window, show print dialog and close popup window after print.
var popup;
function closePrint () {
if ( popup ) {
popup.close();
}
}
popup = window.open( YOUR_IMAGE_URL );
popup.onbeforeunload = closePrint;
popup.onafterprint = closePrint;
popup.focus(); // Required for IE
popup.print();
MDN Reference code