【问题标题】:JavaScript - opening new window in print mode after document is readyJavaScript - 文档准备好后以打印模式打开新窗口
【发布时间】:2017-02-15 05:43:40
【问题描述】:

我想在加载所有图像(并且文档准备好)后以打印模式打开一个新窗口。 这是我的代码:

var win = window.open();
//css ltr
win.document.write('<style>body { direction: rtl; unicode-bidi: bidi-override; }</style>');
//insert img
win.document.write('<img src="assets/imgs/logo.png">' + '<br>');
//insert txt
win.document.write(pdf);
win.document.write('<br>');
win.document.write('<img src="assets/imgs/buttomLogo.png">' + '<br>');
win.print();
win.close();

我曾尝试使用onLoad(),但它打印的文档没有图片:

win.onload = function () {
   win.print();
   win.close();                           
}

如何以打印模式打开包含所有图像的文档? 小提琴 - printer.

谢谢。

【问题讨论】:

  • 如果有几张图片?

标签: javascript


【解决方案1】:

相当 hacky - 但是我这样做是为了等待图像加载,是在新窗口中写入 script 标记,并为图像添加侦听器:

mywindow.document.write('<script type="text/javascript">var img = document.getElementById("js-company-logo"); var src = img.src; img.addEventListener("load", function() { window.print(); window.close(); }); img.src = ""; img.src = src;</script>');

我还必须每次都设置图像的src(Chrome 缓存图像并且在第一次使用后不显示在打印预览中的问题)

【讨论】:

  • 尝试并发布结果。
【解决方案2】:

方式 1: 试试下面的代码。在 HTML 开始前添加 body 标签,并在其上添加 onload 函数并在 body onload 函数中定义 window.print() 函数。

var win = window.open();
//css ltr
win.document.write('<style>body { direction: rtl; unicode-bidi: bidi-override; }</style>');
//insert img
win.document.write('<body onload="javascript:PrintMe()"><img src="assets/imgs/logo.png">' + '<br>');
//insert txt
win.document.write(pdf);
win.document.write('<br>');
win.document.write('<img src="assets/imgs/buttomLogo.png">' + '<br><body>');

function PrintMe()
{   
    win.print();
    win.close();
} 

方式2:使用图片事件监听器image.attachEvent("onload"

var win = window.open();
//css ltr
win.document.write('<style>body { direction: rtl; unicode-bidi: bidi-override; }</style>');
//insert img
win.document.write('<body onload="javascript:PrintMe()"><img src="assets/imgs/logo.png">' + '<br>');
//insert txt
win.document.write(pdf);
win.document.write('<br>');
win.document.write('<img src="assets/imgs/buttomLogo.png">' + '<br><body>');
image.attachEvent("onload", function() {
    win.print();
    win.close();
});

【讨论】:

    【解决方案3】:

    onLoad 不是最好的解决方案。 关于 onLoad 有一个很好的信息: Javascript callback for knowing when an image is loaded

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多