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

Joel Glovier picture Joel Glovier · Feb 22, 2011 · Viewed 16.8k times · Source

I'm trying to create a simple click to print link for an image, and what I'd like to happen is when the link is clicked, a new window opens with the image, and the browser opens the print command dialogue box.

My question is whether this is possible just from a URL parameter, or from the anchor element on the initiating page? Or do I have to build a target page with javascript to do this?

Here's a sample of what I've got:

<p class="click-2-print">
  <a href="/img/map.jpg" target="_blank">Click here to print the map above</a>
</p>

Obviously the code above will open the image in a new window, but still requires to user to hit Ctrl+P, Cmd+P or use the browser commands. My client wants the image to "just print" when the user clicks the link, so I'm trying to find the simplest way to accomplish this.

So is there any parameters or attributes that I can add to the above markup to accomplish what I have described?

Answer

Cody Bonney picture Cody Bonney · Feb 22, 2011

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>