Javascript 如何在打印时显示JS生成的img
我有以下代码:Javascript 如何在打印时显示JS生成的img,javascript,html,printing,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>
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;
});
jQuery('#print')。在(“单击”,函数(){
var mywindow=window.open(“”,'my div','height=400,width=600');
mywindow.document.write('Title');
mywindow.document.write(“”);
mywindow.document.write(“”);
mywindow.document.write(“”);
mywindow.print();
mywindow.close();
返回true;
});
它的作用是,当有人点击#打印按钮时,包含谷歌徽标的小窗口就会出现,并且已经打开了打印弹出窗口。不幸的是,当我把它打印在纸上或PDF上时,图像并没有出现——而是显示它的alt属性
如何修复此问题?我刚刚在Windows 8.1上使用Chrome进行的一次工作中尝试了您的代码,它似乎与您在打印到.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));
});
});
jQuery('#print')。在(“单击”,函数(){
var mywindow=window.open(“”,'my div','height=400,width=600');
mywindow.document.write('Title');
mywindow.document.write(“”);
mywindow.document.write(“”);
mywindow.document.write(“”);
$(mywindow).ready(函数(){
//稍后在堆栈中调用-实际上应该是onload事件或base64映像内联
设置超时(
函数(){
mywindow.print();
},(1000));
});
});
可能分段过程有助于确保在打开和构建新窗口时,所有内容都可以打印
工作副本:
参考文献: