使用Javascript打印图像 [英] Print image with Javascript
本文介绍了使用Javascript打印图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用javascript打印图片。
所以我用这段代码在新窗口打开图片并打印:
I want to print image with javascript. So I used this code to open image in 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);
然后打开新窗口& print - 新窗口中的图像很好,但没有打印操作。
如何让win.print()工作?
And then open new window & print - the image apears fine in the new window, but no print operation is done. How to make the win.print() to work?
推荐答案
好的!
我在Chrome上尝试过此功能并且运行良好:
I'v tried this on Chrome and it's work 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>
问候。
这篇关于使用Javascript打印图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文