2017-09-13 55 views
1

我有一個帶打印按鈕的組件。但是,當我打印來自test.component.css的CSS不包括。任何人都可以請幫我解決這個問題嗎? 注意:我只能在test.component.css中保留css。我不想使用內聯樣式。Angular4:如何在打印中包含test.component.css

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:

這裏是你可能會使用網絡組來運行你的web應用程序的打印輸出

Here is the printing output

回答

0

?如果是這樣,test.component.css在運行時不存在 - 它被捆綁到其他文件中。

您是否考慮過在您的主CSS文件中使用媒體查詢? https://www.w3schools.com/css/css3_mediaqueries.asp

如果你喜歡你目前的做法,你可能需要服務於CSS的靜態資產在您的項目:Whats the default path for static files in Angular2?

+0

**你可能使用網絡包來運行你的網絡應用程序?如果是這樣,test.component.css在運行時不存在 - 它被捆綁到其他文件中。**是的,我正在使用ng serve命令使用angular-cli。寫作媒體查詢並不能解決我的問題。不能將我的CSS文件放置在資產目錄中,因爲它會重複。 –

+0

爲什麼媒體查詢不起作用? – EvanM

+0

另外,您可以創建一個從資產目錄到CSS源代碼的符號鏈接。這將解決同步問題。 – EvanM

0

可以從頭標記您在目前的風格和追加到您的打印html標記爲下面使用jquery($('head')。clone()。html())。此外,如果你正在使用的index.html像你引導外部庫,如下面還添加打印作爲一個媒體在您的index.html: -

<link rel="stylesheet" type="text/css" media="screen,print" href="assets/css/bootstrap.min.css"> 

//代碼打印

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