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

Problem

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

Problem courtesy of: Neeraj Rathod

Solution

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();
}
Solution courtesy of: selem mn

Discussion

you can do like this in angular 2

in ts file

 export class Component{          
      constructor(){
      }
       printToCart(printSectionId: string){
        let popupWinindow
        let innerContents = document.getElementById(printSectionId).innerHTML;
        popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWinindow.document.open();
        popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>');
        popupWinindow.document.close();
  }

 }

in html

<div id="printSectionId" >
  <div>
    <h1>AngularJS Print html templates</h1>
    <form novalidate>
      First Name:
      <input type="text"  class="tb8">
      <br>
      <br> Last Name:
      <input type="text"  class="tb8">
      <br>
      <br>
      <button  class="button">Submit</button>
      <button (click)="printToCart('printSectionId')" class="button">Print</button>
    </form>
  </div>
  <div>
    <br/>
   </div>
</div>
Discussion courtesy of: Vikash Dahiya
import { Directive, ElementRef, Input,HostListener,AfterViewInit } from '@angular/core';
declare const jQuery :  any;

@Directive({ selector: '[printDirective]' })

export class PrintDirective implements AfterViewInit { 

constructor(public e:ElementRef){}
@Input() printelement: string;

button = this.e.nativeElement;

ngAfterViewInit(){


    let self = this;
    jQuery(this.button).on("click", function(){ 

       var html = jQuery("#"+self.printelement).prop('outerHTML');

        let sheets = document.styleSheets;
        let array = [];
        for(var c = 0; c < sheets.length; c++) {

            array.push(sheets[c].href);

        }

        let printStyles:any="";

        array.forEach(function(value:any,index:any){
            var res = value.substring(value.indexOf(":") + 1);
            printStyles = "<link rel='stylesheet' type='text/css'  href="+value+" media='print'>\n"+printStyles ;

        });

        let printContents =  html;

        let  popupWin;

        popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
        popupWin.document.open();
        popupWin.document.write(`
        <html>
            <head>
            <title>Print tab</title>


            ${printStyles}

            </head>
        <body onload="window.print();window.close()">${printContents}</body>
        </html>`
        );
        popupWin.document.close();


        }

)}; 






 }

It could be done like this. I made a directive to print the html page. It just takes the input element's id as an input from the component template.

app.component.html

<div id="print">
     <div id="mydiv">Hello 1st div</div>
     <div id="seconddiv">Hello second div</div>
<img src="pic.jpg">
<div id="main">
    <div>Hello ...how are you
        <p> demo demo</p>
    </div>
    <div>JHADVSJVCJHCSJHB</div>
    <div>CJHAEV</div>
</div>

   <button [printelement]="'print'" printDirective>print</button>

This is the way to use it in the template. Tested on angular 4 on chrome. On firefox the background color can be added if missing using css :

 background-color: red !important;
-webkit-print-color-adjust: exact;
color-adjust: exact;
Discussion courtesy of: ayush gupta

This recipe can be found in it's original form on Stack Over Flow.