1

To copy a new page you could do something like this:

var yourDOCTYPE = "<!DOCTYPE html..."; // your doctype declaration
var printPreview = window.open('about:blank', 'print_preview');
var printDocument = printPreview.document;
printDocument.open();
printDocument.write(yourDOCTYPE+
           "<html>"+
               document.documentElement.innerHTML+
           "</html>");
printDocument.close();

Source: Copy Current Webpage Into a New Window

How would I write this

printDocument.write(yourDOCTYPE+
"<html>"+
document.documentElement.innerHTML+
"</html>");

so it's just includes #report? I want the css to be intact, so it's not possible to do this:

printDocument.write(yourDOCTYPE+
"<html>"+
document.getElementById('report').innerHTML+
"</html>");

because then the styling of the origin page is gone.

UPDATE One option would be to hide all hide all elements in dom except #report when opened up the new popup-window.

But how do I that in pure js?

If I do something like this in jquery:

$('body > :not(#report)').hide(); //hide all nodes directly under the body
$('#report').appendTo('body');

it would hide eveything except #report in the original window (of course). I do not understand how to apply this to printDocument.write (so it applies to the popup window)

I does not have to be a popup window either. It could as well be a new window that opens in browser if someone can give me an idea how to solve this.

Community
  • 1
  • 1
bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72

2 Answers2

2

You can get your style tag and report element, and add them into the new page:

var printPreview = window.open('about:blank', 'print_preview');
var printDocument = printPreview.document;
printDocument.open();
printDocument.write("<!DOCTYPE html><html><head>" +
    document.getElementsByTagName("style")[0].outerHTML + "</head><body>" +
    document.getElementById("report").outerHTML + "</body></html>");
printDocument.close();
<!DOCTYPE html>
<html>

<head>
  <style>
    .report {
      color: red;
    }
  </style>

</head>

<body>
  <div id="report" class="report">report</div>
  <div id="e">e</div>
</body>

</html>
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
0

If someone stumbles upon the same issue, put an ID on the css-element and then fetch the style based on that id.

function openPP() {
    var printPreview = window.open('about:blank', 'print_preview', "resizable=yes,scrollbars=yes,status=yes");
    var printDocument = printPreview.document;
    printDocument.open();
    printDocument.write("<!DOCTYPE html><html>"+              
    document.getElementById('csslink').outerHTML +
    document.getElementById('report').innerHTML+
    "</html>");
    printDocument.close();
}
window.openPP = openPP;
bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72