6

In plain JavaScript, you are able to print an element by getting the element ID, putting it in a new window, and using window.print().

What is the "Angular 2" way to do such a thing? I have gotten as far as getting a ViewChild of the component I wish to print, but I'm not sure how to access its html and subsequently print it, or if that's even what I'm supposed to do.

Alex Palacios
  • 389
  • 2
  • 4
  • 19
  • 5
    Possible duplicate of [Print Html template in Angular 2 (ng-print in Angular 2)](http://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2) – sloth May 15 '17 at 06:57
  • 1
    The best way i found is create your print component, give it a route to highest hierachy on your routing. Open the route with window.open(url). And on that component afterviewinit call window.print() . You can include any of your component into print component after the view created print it. Dont forget to add css @media print{} on the print component. – Shri Brahmana Manike Nov 06 '17 at 11:43

2 Answers2

1

If you need to print some custom HTML, this method doesn't need a new window.

ts:

    let control_Print;

    control_Print = document.getElementById('__printingFrame');

    let doc = control_Print.contentWindow.document;
    doc.open();
    doc.write("<div style='color:red;'>I WANT TO PRINT THIS, NOT THE CURRENT HTML</div>");
    doc.close();

    control_Print = control_Print.contentWindow;
    control_Print.focus();
    control_Print.print();

html:

<iframe title="Lets print" id="__printingFrame" style="width: 0; height: 0; border: 0"></iframe>
Pablo Chvx
  • 1,809
  • 18
  • 31
-3

HTML

    <div id="printSection"></div>
    <button (click)="print()">PRINT</button>

TS

    print(): void {
       let printContents, popupWin;
       printContents = document.getElementById('printSection').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();
    }
Deepak swain
  • 3,380
  • 1
  • 30
  • 26
  • Ok. I can understand why someone would downvote this answer (for a multitude of reasons) but .. this is the perfect hammer right now! – MoshMage Aug 04 '17 at 16:45
  • It's just copypaste of accepted answer from similar question https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 – Olga Akhmetova Oct 19 '17 at 11:55