window.print() 尝试在完成呈现之前打印一个页面(动态创建的)

window.print() tries to print a page( which is created dynamically) before it finishes rendering

我正在尝试在新 window 中打印 table。 问题是,print 尝试在呈现页面之前打印。 我怀疑 document.write 是异步的。 我尝试使用 document.outerHTML / document.innerHTML 而不是 document.write(),但是 CSS/JS 文件没有被正确解析为 CSS。 table 的单元格中有从缓存中加载的图像,也在 window.print().

之后

拜托,任何想法都会有所帮助。

function printData() {
    let newWin = window.open("");
    styles="";

    //read styles in different page
    Array.prototype.forEach.call(
      document.querySelectorAll("link, style"), 
      function(el){
      styles += (el.outerHTML);
    });

   //DOESNT WORK NOT RENDER STYLES
   // newWin.document.document.querySelector("html").innerHTML=(styles + document.querySelector("table").outerHTML);
    //THIS FINISHES RENDERING AFTER PRINT
      newWin.document.write(styles + document.querySelector("table").outerHTML);

      //DOESNT WORK 
      newWin.document.addEventListener("DOMContentLoaded", function(){
      if(newWin.document.addEventListener === "loading"){
          newWin.print();
      }
      //DOESNT WORK
      newWin.window.onload= function(){
          newWin.print();
      }

      //WORKS
      setTimeout(function(){
        newWin.print();
        newWin.close();
      }, 2000);
    });
}

使用 window.onload 来触发您的函数,因为它会等待页面的所有内容加载完毕并得到广泛支持。

试试这样的东西:

let printAndClose = '<script>onload = function() { window.print(); window.close(); }</sc' + 'ript>';

newWin.document.write(
  styles +
  document.querySelector("table").outerHTML) +
  printAndClose
);

我通过将以下代码附加到 <body> 的末尾解决了类似的问题。它适用于 IE11、Chrome 和 Firefox。调用 window.close() 而不在 setTimeout() 中换行会导致 IE11 在显示打印对话框之前关闭 window。

<script type="text/javascript">
    setTimeout(function() {
        window.print();
        setTimeout(function() {window.close();});
    });
</script>