سؤال

I have a sample fiddle here where I have a print preview button. On click of that button, it opens a new popup window which is created as,

function printpage() {
    var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + document.getElementsByTagName('table')[0].innerHTML + '</table>';
    data += '<br/><button onclick="window.print()"  class="noprint">Print the Report</button>';
    data += '<style type="text/css" media="print"> .noprint {visibility: hidden;} </style>';
    myWindow = window.open('', '', 'width=800,height=600');
    myWindow.innerWidth = screen.width;
    myWindow.innerHeight = screen.height;
    myWindow.screenX = 0;
    myWindow.screenY = 0;
    myWindow.document.write(data);
    myWindow.focus();
}

When viewing its source using google chrome developer tools, I can get the following codes.

<html>
<head></head>
<body>
<table border="1" cellspacing="0"><tbody><tr><td colspan="4">Sample Report</td></tr>
    </tbody>
    <tbody>
    <tr><th>Sl.No</th><th>Value 1</th><th>Value 2</th><th>Value 3</th></tr>
    <tr><td>1</td><td>5</td><td>0</td><td>2</td></tr>
    <tr><td>2</td><td>7</td><td>0</td><td>4</td></tr>
    <tr><td>3</td><td>1</td><td>0</td><td>10</td></tr>
    <tr><td>4</td><td>8</td><td>0</td><td>3</td></tr>
    <tr><td>5</td><td>13</td><td>0</td><td>6</td></tr>
</tbody></table><br>
<button onclick="window.print()" class="noprint">Print the Report</button><style type="text/css" media="print"> .noprint {visibility: hidden;} </style>
</body>
</html>

Is it possible to add some extra javascript/jquery codes inside that pop up window?

هل كانت مفيدة؟

المحلول

You can add a script to data variable like so:

var data = '<script>/* CODE */ <\/script>' +
    '<table ...>' +
           :
    '<style...>';

The ending script tag within a string must somehow be broken, so that it doesn't appear as a literal </script>. If it does, the script will break, when the tag is found.

Also you need to take care, that quotes within a script string are not breaking the string. Use "s and escape ' with a backslash when needed.

Actually there are more elegant ways to style a page (or part of it) for printing, you could use for example Media Queries, or link (see media) a separate stylesheet to style prints.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top