【问题标题】:Print an image in Chrome using Javascript使用 Javascript 在 Chrome 中打印图像
【发布时间】:2015-01-26 22:11:44
【问题描述】:

在我的网站上,我想创建用于打印各种图像的按钮。我知道这可以使用 Javascript 来实现。经过一番研究,我写了这个:

<script type="text/javascript">
var pwin;
function printImg(imgSrc) {
    pwin = window.open(imgSrc, "_blank");
    setTimeout("pwin.print()", 20);
}
</script>
...
<input class="printAndSolve" type="submit" value="Print"
onclick="printImg('original.png')">

这会在新选项卡中打开图像,但不会显示打印对话框。 我做错了什么?

进一步的研究产生了不同的方法:

<script type="text/javascript">
function printImg(imgSrc) {
    var printWindow = window.open('', 'Print
    Window','height=400,width=600');
    printWindow.document.write('<html><head><title>Print Window</title>');
    printWindow.document.write('</head><body ><img src=\'');
    printWindow.document.write(imgSrc);
    printWindow.document.write('\' /></body></html>');
    printWindow.document.close();
    printWindow.onload = function() { printWindow.print(); };
}
</script>
...
<input class="printAndSolve" type="submit" value="Print"
onclick="printImg('original.png')">

这给了我一个奇怪的结果。尝试打印小图像时,会弹出打印对话框。但是当我尝试打印更大的图像(覆盖整张 A4 纸)时,不会弹出对话框。到底是怎么回事?

考虑到我希望达到的目标,你们认为最好的方法是什么?

提前致谢!

编辑

这实际上似乎是与浏览器相关的问题。上面的代码在 Firefox 和 IE 中运行良好。我遇到这个问题是因为我正在用 Chrome 开发网站。显然 Chrome 在显示打印窗口之前不会等待我的窗口内容加载。其他浏览器似乎都先等待内容加载,然后显示打印窗口。 我当然尝试过使用 setTimeout 函数但没有成功。 因此,我的问题是,谁能告诉我在 Chrome 中打印图像的解决方法?

已解决

这个网站被证明是黄金:http://nice-tutorials.blogspot.se/2014/01/image-printing-problem-in-google-chrome.html

问题解决了!

【问题讨论】:

    标签: javascript google-chrome printing


    【解决方案1】:

    解决方法是在body标签中加入onLoad事件:

    printWindow.document.write('</head><body onLoad="self.print(); self.close()"><img src=\'');
    

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多