代码之家  ›  专栏  ›  技术社区  ›  usman610

第一次单击时打印图像不会显示图像

  •  0
  • usman610  · 技术社区  · 4 年前

    下面的java脚本打印图像onClick工作不正常。它不会在第一次单击时加载图像。当用户单击按钮时,它会打开空白/损坏的图像。关闭第一个打印窗口后,再单击第二个窗口将显示图像。

    <a href="#" onclick="VoucherPrint('output/image.jpg'); return false;">Print Voucher</a>
    
    function VoucherSourcetoPrint(source) {
        return "<html><head><script>function step1(){\n" +
        "setTimeout('step2()', 10);}\n" +
        "function step2(){window.print();window.close()}\n" +
        "</scri" + "pt></head><body onload='step1()'>\n" +
        "<img src='" + source + "' /></body></html>";
    }
    function VoucherPrint(source) {
        Pagelink = "about:blank";
        var pwa = window.open(Pagelink, "_new");
        pwa.document.open();
        pwa.document.write(VoucherSourcetoPrint(source));
        pwa.document.close();
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   mplungjan Gvidas    4 年前

    你的代码太复杂了。

    试试这个

    document.getElementById("printVoucher").addEventListener("click",function(e) {
      const img = e.target.dataset.src;
      const html = `<body onload="window.print();setTimout(function() {window.close()},500)"><img src="${img}" /></body>`;
      const pwa = window.open("", e.target.target);
      if (pwa) {
        pwa.document.open();
        pwa.document.write(html);
        pwa.document.close();
        e.preventDefault(); // cancel the link
      }
      else e.target.href=img; // popup blocker. Open the image in a new tab
    })
    
    <a href="#" target="_blank" id="printVoucher" data-src="output/image.jpg">Print Voucher</a>