Print Image Using Javascript

I want to print an image using javascript. Therefore, I used this code to open the image in a new window and print:

win = window.open(img.src,"_blank");
win.onload = function() { win.print(); }

This works fine with the default image file:

<img id="image1" src="myimage.jpg">

But when I replace the default image with image data read from disk:

var fileElem = document.getElementById("fileElem").files[0];
var reader = new FileReader();
reader.onload = function(event) {
   img.src = event.target.result;
};
reader.readAsDataURL(fileElem); 

And then open a new window and print - the image will appear in a new window, but the print operation is not performed. How to make win.print () work?

+4
source share
2 answers

OK!

I'v tried this in Chrome and it works well:

<html>
    <head>
        <script language="javascript" type="text/javascript">
            function printImage() {
                var fileElem = document.getElementById("fileElem").files[0];
                var reader = new FileReader();
                reader.onload = function(event) {
                    var html  = "<html><head>" +
                        "</head>" +
                        "<body  style ='-webkit-print-color-adjust:exact;'>"+
                        "<img src=\"" + event.target.result + "\" onload=\"javascript:window.print();\"/>" +
                        "</body>";
                    var win = window.open("about:blank","_blank");
                    win.document.write(html);

                };
                reader.readAsDataURL(fileElem); 
            }
       </script>
   </head>
   <body>
       <input type="file" id="fileElem"/>
       <button onclick="printImage()">PRINT</button>
   </body>
</html>

Sincerely.

+4
source

I'm not sure, because I don't know all of your code, but maybe this might work:

var fileElem = document.getElementById("fileElem").files[0];
var reader = new FileReader();
reader.onload = function(event) {
   var win = window.open(event.target.result,"_blank");
   win.onload = function() { win.print(); }
};
reader.readAsDataURL(fileElem); 

"img".

0

All Articles