Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Html template in Angular 2 (ng-print in Angular 2)

I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1

Any suggestion would be appreciated

like image 380
Neeraj Rathod Avatar asked Dec 29 '16 11:12

Neeraj Rathod


1 Answers

That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:

<div id="print-section">   // your html stuff that you want to print </div> <button (click)="print()">print</button> 

and in your TS file :

print(): void {     let printContents, popupWin;     printContents = document.getElementById('print-section').innerHTML;     popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');     popupWin.document.open();     popupWin.document.write(`       <html>         <head>           <title>Print tab</title>           <style>           //........Customized style.......           </style>         </head>     <body onload="window.print();window.close()">${printContents}</body>       </html>`     );     popupWin.document.close(); } 

UPDATE:

You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.

like image 53
SeleM Avatar answered Oct 09 '22 12:10

SeleM