-2

I use this method to copy a DIV from my webapp to be printed in a new tab or saved to the database, like a certificate, for example (it is an automated proccess, I can't ask the user to do that): https://stackoverflow.com/a/40389924/1062933 [thanks!]

  printForm(): void {
    let printContents: any = document.getElementById('formTerms').innerHTML;
    let w: any = window.open();
    w.document.write(printContents);
    w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
    w.document.close(); // necessary for IE >= 10
    w.focus(); // necessary for IE >= 10
  }

But the resulting HTML comes unformatted without the CSS it had in the main tab.

Is there a way to also copy the CSS styles used in that DIV?

I am using Angular4 and Teradata Covalent

NaN
  • 8,596
  • 20
  • 79
  • 153

1 Answers1

1

If you know which <style> tags are being used to style the div, you can copy the contents of those into new style tags over in the new window. However, that won't include styles directly on the div itself.

White a bit more manual, the getComputedStyle function can give the current styling of the element, which you can then apply over in the new window. If there are children in the div you're copying, you'll have to do this recursively or resolve common styles into a generated style sheet.

There are examples in the linked page, but I'll copy it here:

// print one or all of the style properties on the element
function dumpComputedStyles(elem,prop) {

  var cs = window.getComputedStyle(elem,null);
  if (prop) {
    console.log(prop+" : "+cs.getPropertyValue(prop));
    return;
  }

  var len = cs.length;
  for (var i=0;i<len;i++) {

    var style = cs[i];
    console.log(style+" : "+cs.getPropertyValue(style));
  }

}
Garrett Johnson
  • 2,413
  • 9
  • 17