Print button to print a attached image

前端 未结 1 561
误落风尘
误落风尘 2021-01-24 05:45

I would like to add a print button in my webpage. upon clicking the print icon, it should automatically start print the attached image

How can i achieve this?

相关标签:
1条回答
  • 2021-01-24 05:55
    1. Open new window using window.open.
    2. Write to it the img tag.
    3. Once the image was loaded, print the document using window.print().
    4. Close the window using window.close()

    You can do this with code like this:

    function printImg(url) {
      var win = window.open('');
      win.document.write('<img src="' + url + '" onload="window.print();window.close()" />');
      win.focus();
    }
    
    <img src="http://i.stack.imgur.com/hCYTd.jpg" />
    <button onclick="printImg('http://i.stack.imgur.com/hCYTd.jpg')">Print</button>
    

    http://jsbin.com/qaruze/edit?html,js

    0 讨论(0)
提交回复
热议问题