printing div content with css applied

后端 未结 8 820
北海茫月
北海茫月 2020-12-28 17:13

I am working on a project and I want to print div content.The code which I am using is fulfilling my requirements,but I am getting simple output without Css applied to it an

相关标签:
8条回答
  • 2020-12-28 17:39

    A possible cause of your rendering issue may be due to the relative paths you're using for the CSS file and images. First, try to use absolute paths. The fact that the HTML structure is rendered excludes problems with the generation of the new HTML document. Also, add media="print"to the linkelement.

    This code works, though partially:

        (function() {
    
    function createPopup( data ) {
        var mywindow = window.open( "", "new div", "height=400,width=600" );
        mywindow.document.write( "<html><head><title></title>" );
        mywindow.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\"/>" );
        mywindow.document.write( "</head><body >" );
        mywindow.document.write( data );
        mywindow.document.write( "</body></html>" );
    
        mywindow.print();
        //mywindow.close();
    
        return true;
    
    }
    document.addEventListener( "DOMContentLoaded", function() {
        document.getElementById( "print" ).addEventListener( "click", function() {
            createPopup( document.getElementById( "content" ).innerHTML );
    
        }, false );
    
    });
    
       })();
    

    I've removed the .close() call. Bear in mind that some CSS styles may not work with print.

    0 讨论(0)
  • 2020-12-28 17:43

    If you wanna render the CSS you must add a timeout before printing it because it takes some time for CSS to be applied to the HTML and then you will be able to print it.

    Try this:

    function Popup(data) {
          var mywindow = window.open('', 'new div', 'height=400,width=600');
          mywindow.document.write('<html><head><title></title>');
          mywindow.document.write('<link rel="stylesheet" href="css/midday_receipt.css" type="text/css" />');
          mywindow.document.write('</head><body >');
          mywindow.document.write(data);
          mywindow.document.write('</body></html>');
          mywindow.document.close();
          mywindow.focus();
          setTimeout(function(){mywindow.print();},1000);
          mywindow.close();
    
          return true;
    }
    
    0 讨论(0)
提交回复
热议问题