如何在打印时显示JS生成图像

时间:2014-07-24 11:00:55

标签: javascript html printing

我有以下代码:

jQuery('#print').on("click", function(){
    var mywindow = window.open('', 'my div', 'height=400,width=600');

    mywindow.document.write('<html><head><title>Title</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<img src="https://www.google.pl/images/srpr/logo11w.png" alt="logo"/>');
    mywindow.document.write('</body></html>');

    mywindow.print();
    mywindow.close();

    return true;
});

它的作用是,当有人点击#print按钮时,会出现包含谷歌徽标的小窗口,其中已打开的打印弹出窗口。不幸的是,当我在纸上或PDF上打印时,图像不会出现 - 显示它的alt属性。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

我刚刚在Windows 8.1上使用Chrome在JSBin http://jsbin.com/catubuwa/1/edit?html,js,output中运行了您的代码,并且在打印到.pdf文件时,它似乎正常运行。但是,我似乎注意到可能存在竞争条件和负载计时问题。也许在您的情况下,页面正在加载并在页面或图像完全加载之前准备打印?

如果发生了这种情况,我已经为myWindow添加了一个基本的.ready()然后打印:但如果你注意到我已经结束了。这似乎也有帮助。原因是实际上在该窗口上调用了打印功能,因此是打印对话框。这将取决于浏览器,但关闭也似乎也会对打印产生影响。

jQuery('#print').on("click", function(){
    var mywindow = window.open('', 'my div', 'height=400,width=600');

    mywindow.document.write('<html><head><title>Title</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<img id="myImage" src="https://www.google.pl/images/srpr/logo11w.png" alt="logo"/>');
    mywindow.document.write('</body></html>');


   $(mywindow).ready(function() {  
  // Call Later In Stack - really should be onload events or base64 images inline
  setTimeout(
    function(){
        mywindow.print(); 
    },(1000));
});

});

也许暂存这个过程可能有助于确保在打开和构建新窗口时可以打印所有内容。

工作副本:

http://jsbin.com/catubuwa/1/edit?html,js,output

<强>参考文献:

相关问题