I am trying to create some elements to print and use the CSS of a stylesheet I already have, but the style is not applied:
let printWindow = window.open('', 'Print', 'height=600,width=800');
printWindow.document.write('<html><head><title>Print</title>');
printWindow.document.write('<link rel="stylesheet" href="https://my.website/css/mystylesheet.css" type="text/css" />');
printWindow.document.write('</head><body>');
printWindow.document.write('<p id="test">Hello</p>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
And in the css file:
#test {
color: green;
}
But it doesn’t work. Why?
Update: The following did not work either:
let printData = '';
printData += '<link rel="stylesheet" href="https://my.website/css/mystylesheet.css" type="text/css" />';
printData += '<p id="test">Hello</p>'
let printWindow = window.open('', 'Print', 'height=600,width=800');
printWindow.document.write(data);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
2
Answers
I write the same code but delete printWindow.close() to see the output
this the result when I clicked on ‘test’ word:
result image
So make sure that you put the right path to the css file
You need to give the css time to load. It won’t need much but this snippet gives it generous time just to prove a point.