如何使用 TS 在 Angular 4 中打印页面

新手上路,请多包涵

我有一个网络应用程序,而在某些页面中我需要让打印机打印页面,但我有一个侧边栏,其余部分是一个组件的页面,怎么可能只打印这个组件的侧边栏,我有在 TS 中使用此代码。

 print() {
window.print();
}

html代码从这一段开始。

 div class="container">
//Here I have all the HTML source

</div>

原文由 TheCoderGuy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 525
2 个回答

首先为该组件分配一个 id,然后:

 const printContent = document.getElementById("componentID");
const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
WindowPrt.document.write(printContent.innerHTML);
WindowPrt.document.close();
WindowPrt.focus();
WindowPrt.print();
WindowPrt.close();

原文由 Mohd Tabish Baig 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以尝试此解决方案。

html文件

<div class="container" id="component1">
//Here I have all the HTML source

</div>

<div class="container" id="component2">
//Here I have all the HTML source

</div>

<button (click)="printComponent('component1')">Print</button>

文件

printComponent(cmpName) {
     let printContents = document.getElementById(cmpName).innerHTML;
     let originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

原文由 Krishna Rathore 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题