使用 Javascript 打印图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20612870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print image with Javascript
提问by Joe
I want to print image with javascript. So I used this code to open image in new window and print:
我想用 javascript 打印图像。所以我用这个代码在新窗口中打开图像并打印:
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 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?
然后打开新窗口并打印 - 图像在新窗口中显示良好,但未进行任何打印操作。如何使 win.print() 工作?
采纳答案by Sayris
OK!
行!
I'v tried this on Chrome and it's work well :
我在 Chrome 上试过这个,效果很好:
<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>
Regards.
问候。
回答by Sayris
I'm not sure because I don't know all of your code, but maybe this could 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);
you don't need anymore "img" tag.
你不再需要“img”标签。