在窗口加载时使用JS打印html表

I need to print the contents of a table element to a POS receipt printer, I am doing it like this:

    <?php
    private function message(){
    return '<!DOCTYPE html><html moznomarginboxes mozdisallowselectionprint><body style="padding:30px;">'
.'<table id="print-area" style="height: 501px; border:1px solid red;padding:1em;margin:0 0 1em" width="364" ><tr><td>example</td></tr></table></table>'
.'<p>&nbsp;</p></body> </html>'}
    ?>

What I am doing is that I am passing the return of that PHP function to a new function. Please ignore the php functions structure and logic, these are just an example of how I am doing this, I know that this might not be the best way to do this, but on what I really need help is on the JavaScript part. Why is it not printing and closing the new window?.

I need to print just the table and make it fit to the POS receipt page, without printing a whole blank space.... I have already tried with this version of the PrintReceipt function but it prints a lot of white space on the receipt.

    public function PrintReceipt($content) {

    echo"<!DOCTYPE html><script type='application/javascript'>
                    window.onload=function(){          
                        var myWindow = window.open('', 'MsgWindow', 'width=200,height=100');
                        myWindow.document.write('" . $content . "');
                        myWindow.print();
                        myWindow.close();              
                    }
    </script>";
}

If you aren't using frames the there is no point in declaring the following lines:

myWindow.frames['print_frame'].document.title = document.title; 
myWindow.document.getElementById('print-area').contentWindow.print();   

Which means that your 2nd attempt in OP is correct. If there's empty space then that's absolutely a css problem. If you want the table to occupy 100% of the page width do:

return '<table id="print-area" style="height: 100%; border:1px solid red;padding:1em;margin:0 0 1em" width="100%" ><tr><td>example</td></tr></table></table>';

instead of

return '<!DOCTYPE html><html moznomarginboxes mozdisallowselectionprint><body style="padding:30px;">' .'<table id="print-area" style="height: 501px; border:1px solid red;padding:1em;margin:0 0 1em" width="364" ><tr><td>example</td></tr></table></table>' .'<p>&nbsp;</p></body> </html>'}