【问题标题】:How to load image dynamically in printview using document.write function如何使用 document.write 函数在 printview 中动态加载图像
【发布时间】:2019-01-18 05:20:00
【问题描述】:

我正在尝试使用document.write 函数动态加载图像。请在下面找到代码。图片有时会加载,有时不显示。

    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>'+"Contract Approval Form"+'</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<div id="headerLogo"></div>');
    mywindow.document.write('<div id="watermarkDiv"></div>');
    mywindow.document.write('<div style="margin-top:50px;" id="content">' +printContent+ '</div>');
    var img = mywindow.document.createElement('img');
    img.setAttribute('src', 'mylogo.png');
    mywindow.document.getElementById("headerLogo").appendChild(img);
    mywindow.document.write('</body></html>');


    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

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

【问题讨论】:

    标签: javascript servicenow


    【解决方案1】:

    等待内容加载

    <script>
    var printContent = '<h1>Hello World</h1>';
    var mywindow = window.open('about:blank', 'PRINT', 'height=400,width=600');
    
    //~ mywindow.onload = function() {
    mywindow.document.write('<html><head><title>'+"Contract Approval Form"+'</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<div id="headerLogo"></div>');
    mywindow.document.write('<div id="watermarkDiv"></div>');
    mywindow.document.write('<div style="margin-top:50px;" id="content">' +printContent+ '</div>');
    var img = mywindow.document.createElement('img');
    img.setAttribute('src', 'mylogo.png');
    img.onload = function() {
        // now you can print, need to wait for image to load - which connotes you need to work out how to wait for all content to load
        mywindow.focus();
        mywindow.print();
    
    }
    
    mywindow.document.getElementById("headerLogo").appendChild(img);
    mywindow.document.write('</body></html>');
    
    </script>
    

    【讨论】:

      【解决方案2】:

      从here找到解决方案:

      看来我需要使用 setTimeout

      setTimeout(function() {
      newWindow.print();
      newWindow.close();
      }, 250);
      

      【讨论】:

      • setTimeout 也可以,但 onload 是更好的解决方案。
      猜你喜欢
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 2013-01-06
      • 2022-01-06
      • 1970-01-01
      • 2018-06-30
      相关资源
      最近更新 更多