Using javascript to print images

andrew picture andrew · May 26, 2010 · Viewed 86.6k times · Source

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?

Answer

ricardo_escovar picture ricardo_escovar · Aug 11, 2015

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.