Pavan Elthepu
Pavan Elthepu

Reputation: 109

Angular4: How to include test.component.css in printing

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 output in browser:

Here is the printing output

Here is the printing output

Upvotes: 3

Views: 2665

Answers (2)

crystalthinker
crystalthinker

Reputation: 1182

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();
}

Upvotes: 3

EvanM
EvanM

Reputation: 687

You're probably using web pack to run your web app? If so, test.component.css doesn't exist at runtime - it's bundled into other files.

Have you considered using a media query in your main CSS file? https://www.w3schools.com/css/css3_mediaqueries.asp

If you like your current approach, you probably need to serve the CSS as as static asset in your project: Whats the default path for static files in Angular2?

Upvotes: 0

Related Questions