What's the simplest way to get an image to print in a new window when clicked?

☆樱花仙子☆ 提交于 2019-12-05 13:07:57

You'll have to call window.print(). Perhaps something like this?

function printimage(){
    var URL = "http://myimage.jpg";

    var W = window.open(URL);

    W.window.print();
}

Another option may be to put the image on a page that tells the browser to print when loaded. For example...

<body onload="window.print();">
<img src="/img/map.jpg">
</body>

I would recommend you create a page in whatever language or framework you are working in that accepts a querystring argument for the image path, output that image in the document and have an onload / ready call to window.print(). Link to that instead of the image directly, and keep the target="_blank" and you should be set.

Cody Bonney's answer will not work in certain browsers if the full url includes the image extension. The browser will automatically download it as soon as the new tab opens. You can get around this like so.

                    var url = scope.src;
                    var w = window.open('', '');
                    w.document.write('<html><head>');
                    w.document.write('</head><body >');
                    w.document.write('<img id="print-image-element" src="'+url+'"/>');
                    w.document.write('<script>var img = document.getElementById("print-image-element"); img.addEventListener("load",function(){ window.focus(); window.print(); window.document.close(); window.close(); }); </script>');
                    w.document.write('</body></html>');
                    w.window.print();   

This will open a new page with the image, prompt the user to print, and after printing, close the new tab and reset focus to the original tab.

Disregard the scope.src that is angular specific code. Everything else should work as long as you provide your own url value from somewhere else

You have to call window.print() in javascript to trigger the browser print dialog. I'm pretty sure you can't trigger a print without user interaction unless you run a signed applet.

Hey Jag. Although its not exactly what you are looking to do, I did write this tutorial while I was working at a web design firm. You can probably rummage that code to get the link that prints the image. Basically what this code does it add a print button to the fancybox jquery plugin. I dont see why you couldnt just use the print part to add it to whatever you need. Hope it helps.

Add print ability to fancybox jquery plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!