简体   繁体   中英

printing an image in HTML5/Javascript

I am new in the web development world and I had the following question

I would like to implement a button in HTML5 that will Print an Image ( and not the whole HTML Page)

I tried the code in this question Print image on website

but I got an unhandled exception :

0x800a138f - Microsoft JScript runtime error : Umable to get value of the property 'innerHTML':object is null or undefined

can anyone guide me how to do this ?

Thanks!

Edit : When I say print , I mean prininting on a physical printer , and not displaying on the screen

Something like this? I whipped this up

<!DOCTYPE>
<html>
<body>
<button onclick="showimage()">Click Here for Image</button>
</body>
<script type="text/javascript">
function showimage() {
    var _body = document.getElementsByTagName('body') [0];
    var img = document.createElement('img');
    //you can replace the link with any image you want
    img.setAttribute('src', 'http://i.123g.us/c/cute_teddy/card/109882.gif');
    img.setAttribute('alt', 'Picture');
    _body.appendChild(img);
}
</script>
</html>

jsFiddle Here

If you need help understanding how this works, don't hesitate to ask. Basically, we have a button and we create the img tag and set the appropriate attributes. Once we have successfully done that, we can then append it to the body of the HTML document so it displays. I suggest you get a good understanding of the DOM (Document Object Model) since you are new to web development/Javascript.

so here is the very simple way of doing it :

<!DOCTYPE>
<html>
<body>
<button onclick="showimage()">Click Here for Image</button>
</body>
<script type="text/javascript">
function showimage() {
     if (typeof img== 'object')
                    img= img.src;
                window.win = open(img);
                setTimeout('win.document.execCommand("Print")', 500);
}
</script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM