2017-09-13 60 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(); 
}