Search code examples
csshtmlkendo-gridprinting-web-page

Unable to insert stylesheet/script into window.open


I have been fighting this issue for quite some time now, and have been (still) unable to print my div with its styling.

Currently, my script is:

$('#printMeButton').click(function () {
    //alert("a");
    var data = document.getElementById('thisPrintableTable').outerHTML;

    var mywindow = window.open('', data);
    mywindow.document.write('<html><head><title>Print Me!!!</title>');
    // mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">');
    mywindow.document.write('</head><body>');
    mywindow.document.write(data);
    mywindow.document.write('</body></html>');

    mywindow.document.close();
    mywindow.focus();
    mywindow.print();
    mywindow.close();
    return true;

});

which is nested within a $(document).ready function.

When I include the desired stylesheet (currently commented out), Nothing appears in the print preview.

I also have some script that has an effect on the appearance of the table, and, as such, I believe this may hold the key of having these included into the popup window.

How can i include this into the new popup?

Could someone please suggest a way of printing this as it stands?

Edit History

  • removed space at end of </head><body>
  • Changed var data to have outerHTML instead of innerHTML
  • Altered Question/details from better understanding of issue

Solution

  • Try to open a local html file using window.open with css linked within it. And set the content html to be printed to the local html file using js.

    Here is the page to be printed:-

    <html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="test.css" rel="stylesheet" type="text/css" />
        <script src="jquery.js"></script>
    </head>
    <body>
        <div id="print">
            <div class="red">TODO write content</div>
        </div>
        <button id="print_btn">Print</button>
        <script>
            $('#print_btn').click(function(){
                var newWindow = window.open('print.html','_blank');
                $(newWindow).load(function(){
                   $(newWindow.document).find('body').html($('#print').html());
                });
            })
        </script>
    </body>
    </html>
    

    The css file test.css is linked here, and I'm opening print.html at the time of window.open, the test.css is also linked in the print.html

    Now, in print.html I'll write:-

    <html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <link href="test.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    
    </body>
    </html>