26

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 print, the popup closes.

Is this easily attainable?

andrew
  • 261
  • 1
  • 4
  • 4

9 Answers9

31

Another great solution!! All credit goes to Codescratcher

<script>

    function ImageToPrint(source)
    {
        return "<html><head><scri"+"pt>function step1(){\n" +
                "setTimeout('step2()', 10);}\n" +
                "function step2(){window.print();window.close()}\n" +
                "</scri" + "pt></head><body onload='step1()'>\n" +
                "<img src='" + source + "' /></body></html>";
    }
    
    function PrintImage(source)
    {
        var Pagelink = "about:blank";
        var pwa = window.open(Pagelink, "_new");
        pwa.document.open();
        pwa.document.write(ImageToPrint(source));
        pwa.document.close();
    }

</script>

<a href="#" onclick="PrintImage('YOUR_IMAGE_PATH_HERE.JPG'); return false;">PRINT</a>

See the full example here.

Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78
ricardo_escovar
  • 447
  • 4
  • 5
  • 1
    why is there a 10 ms timeout? Why not simply `` – Shasak Nov 27 '15 at 10:54
  • 2
    That codescratcher site is a little confusing I uploaded this code to my github account: See working demo here https://rawgit.com/orellabac/printFromJavascript/master/Print_Image.htm code is at: https://github.com/orellabac/printFromJavascript/ – orellabac Jun 12 '17 at 21:14
  • Updated: `function printImage(source) { var pwa = window.open(source, "_new") pwa.document.open() pwa.document.write("function step1(){\n" + "setTimeout('step2()', 10);}\n" + "function step2(){window.print();window.close()}\n" + "\n" + "") pwa.document.close() }` – RixTheTyrunt Oct 14 '22 at 09:22
  • @RixTheTyrunt What if I have multiple images (N) to print ? How do I await every single one of them to load ? How to prepare them for print ? – emre-ozgun Oct 17 '22 at 15:21
  • Good question tho ツ – RixTheTyrunt Oct 18 '22 at 09:03
  • Thank you so much! after all solution. this worked – Parth Developer Oct 25 '22 at 21:28
25
popup = window.open();
popup.document.write("imagehtml");
popup.focus(); //required for IE
popup.print();
p.campbell
  • 98,673
  • 67
  • 256
  • 322
Javier Parra
  • 2,020
  • 2
  • 18
  • 32
  • How would this work using a button? The button would initiate this action, but actually prints a separate image. – andrew May 25 '10 at 23:04
  • 2
    I'm not going to write all the code for you, the point of this place is to learn. ;) You'd do it using the onmouseup event on the button: http://www.w3schools.com/jsref/event_onmouseup.asp – Javier Parra May 25 '10 at 23:12
  • 2
    I don't want you to write it for me... just want to be pointed to the right resources. I need a place to start. Thanks. – andrew May 25 '10 at 23:13
  • 2
    Found fix for IE: before `popup.print();` you need to call `popup.focus();` – Igor Jerosimić Jun 04 '14 at 08:51
10

Use this in the head block

<script type="text/javascript">
function printImg() {
  pwin = window.open(document.getElementById("mainImg").src,"_blank");
  pwin.onload = function () {window.print();}
}
</script>

use this in the body block

<img src="images.jpg" id="mainImg" />
<input type="button" value="Print Image"  onclick="printImg()" />
Matthew F. Robben
  • 1,906
  • 1
  • 12
  • 6
Zahid Habib
  • 715
  • 3
  • 12
  • 23
  • Brilliant solution. However it worked well using php server but when I moved to lighttpd it did not print the image alone but the page where it came from. Still looking for a solution to this. – Noel Oct 29 '20 at 16:59
6

A cross browser solution printImage(document.getElementById('buzzBarcode').src)

/**
 * Prints an image by temporarily opening a popup
 * @param {string} src - image source to load
 * @returns {void}
 */
function printImage(src) {
    var win = window.open('about:blank', "_new");
    win.document.open();
    win.document.write([
        '<html>',
        '   <head>',
        '   </head>',
        '   <body onload="window.print()" onafterprint="window.close()">',
        '       <img src="' + src + '"/>',
        '   </body>',
        '</html>'
    ].join(''));
    win.document.close();
}
img {
  display: block;
  margin: 10px auto;
}

button {
  font-family: tahoma;
  font-size: 12px;
  padding: 6px;
  display: block;
  margin: 0 auto;
}
<img id="buzzBarcode" src="https://barcode.orcascan.com/qrcode/buzz.png?text=to infinity and beyond" width="150" height="150" />
user12133161
  • 61
  • 1
  • 1
5

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

Igor Jerosimić
  • 13,621
  • 6
  • 44
  • 53
1

Yea, just put the image on the screen, and then call window.print(); in javascript and it should popup.

(This is how Google Maps/Google Calendar do printing)

Mitch Dempsey
  • 38,725
  • 6
  • 68
  • 74
  • 1
    Cool. But what if I want a different image to show that initiates the popup window? – andrew May 25 '10 at 22:47
  • Check out the CSS styles for printing. You can basically have an image hidden on the screen view, and then visible for the print view. – Mitch Dempsey May 25 '10 at 23:14
0

This works in Chrome:

  <body ><img  src="image.jpg" alt="" style="display: block; width: 100%; height: 100%;">

            <script type="text/javascript">
                window.onload = function() {
                    window.print();
                    setTimeout(function() {
                        window.close();
                    }, 1);
                };
            </script>
    </body>
DD.
  • 21,498
  • 52
  • 157
  • 246
0

I just spent 45 minutes on this "SIMPLE" problem, trying to get it the way I wanted it to operate.

I had an image inside an img tag, dynamically generated by a jQuery Barcode plugin that I had to print. I wanted it to print in another window and afterwards close the window. This was all supposed to happen after the user clicked a button inside a jQuery Grid plugin, inside a jQuery-UI dialog along with jQuery-UI dialog extender applied to it.

I adjusted everyone answers till I finally came up with this, maybe it can help someone.

w = window.open(document.getElementById("UB-canvas").src);
w.onload = function () { w.print(); }
w.onbeforeunload = setTimeout(function () { w.close(); },500);
w.onafterprint = setTimeout(function () { w.close(); },500);

The setTimeout is not just for shits and giggles, it's the only way I found Firefox 42 would hit those functions. It would just simply skip the .close() functions until I added a breakpoint to it, then it worked perfectly. So I'm assuming it created those window instances before it could apply the onbeforeload event function and onafterprint event functions, or something.

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Kickass
  • 1,114
  • 9
  • 16
0

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)