0

I want to add the style for the section which I am going to print.

 let popupWinindow
 let innerContents = this.printDiv.nativeElement.innerHTML;
 popupWinindow = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
 popupWinindow.document.open();
 popupWinindow.document.write('<html><head><link href="styles.css" rel="stylesheet" type="text/css"></head><body onload="window.print();">' + innerContents + '</html>');
 popupWinindow.document.close();

When I am adding styles internally in the style tag then everything works fine. But when I tried to add it in external way it does not apply to the printDiv.

This is the error I have in console.

Refused to apply style from 'http://localhost:4200/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Hubert Kubiak
  • 511
  • 5
  • 23
swapnil jain
  • 184
  • 2
  • 18
  • Check this [post](https://stackoverflow.com/questions/48248832/stylesheet-not-loaded-because-of-mime-type) – DShadrin Aug 21 '19 at 06:52
  • 1
    Try downloading http://localhost:4200/styles.css, enter it in the address bar in your browser and verify that you get a css document and not a 404 html error page – MikNiller Aug 21 '19 at 07:00
  • i am getting an error page so what should i do for it ?So, that it will automatically get access – swapnil jain Aug 21 '19 at 07:03
  • You should use the full absolute path to your style sheet (including protocol and domain) – yunzen Aug 21 '19 at 07:09

2 Answers2

0

For printing you should add a mediaquery print

@media print {
   // Your styles
}

Also check the path to the styles.css file. For example here you can find more info Stylesheet not loaded because of MIME-type

igor_c
  • 1,009
  • 1
  • 6
  • 16
0

The opened window is somewhat unrelated to to opening window. It doesn't know of the path to your file and the domain and the protocol. You should insert the complete absolute URL to your style sheet in your code.

So if your style sheet file resides on https://example.com/path/to/file/style.css, you should use

 popupWinindow.document.write('<html><head><link href="https://example.com/path/to/file/style.css" rel="stylesheet" type="text/css"></head><body onload="window.print();">' + innerContents + '</html>');

See https://codepen.io/HerrSerker/pen/70cdc072c09f04b850b67febe7ef0f34 for a working demonstration

You can get the path information to your html file dynamically in JS with

location.protocol + "//" + location.host + location.pathname.replace(/\/(?!.*\/).*$/, '/')
yunzen
  • 30,001
  • 10
  • 64
  • 93