I've one component with a print button. But, when I'm printing the css from test.component.css is not including. Can anyone please help me with this issue? Note: I've to keep css only in test.component.css. I don't want to use inline styling.
test.component.html:
<div class='container'>
<div>
<button (click)='printContent()' class="btn btn-default">
<span class="glyphicon glyphicon-print"></span> Print
</button>
</div>
<div id='content'>Hello World</div>
</div>
test.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
}
printContent() {
let popupWin = window.open('', '_blank', 'width=1080,height=595');
let printContents = document.getElementById("content").innerHTML;
popupWin.document
.write('<html><head>' +
'<link rel="stylesheet" type="text/css" href="/test.component.css"/>' +
'</head><body onload="window.print();">'
+ printContents + '</body></html>');
popupWin.document.close();
}
}
test.component.css:
#content{
background-color: cyan;
font-weight: bold;
}
Here is the output in browser:

Here is the printing output

You Can get your current styles from the Head tag and append to your print html tag as below using jquery($('head').clone().html()). Also if you are using external library like bootstrap in you index.html, Add print also as a media as below in your index.html:-
<link rel="stylesheet" type="text/css" media="screen,print" href="assets/css/bootstrap.min.css">
//Code for print
printContent() {
let popupWin = window.open('', '_blank', 'width=1080,height=595');
let printContents = document.getElementById("content").innerHTML;
popupWin.document
.write(`<html>
${$('head').clone().html()}
<body onload="window.print();">${printContents}</body></html>`);
popupWin.document.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With