Javascript - Print HTML Template in Angular 2 (Ng-Print in Angular 2) - Stack Overflow

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

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


Asked 3 years, 11 months ago Active 5 months ago Viewed 127k times

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

48 Any suggestion would be appreciated

javascript angularjs angular

28
edited Dec 29 '16 at 12:29 asked Dec 29 '16 at 11:58
Neeraj Rathod
1,325 3 12 21

11 Answers Active Oldest Votes

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

91 <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(`
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
<html>
<head>
https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 1/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow
<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.

edited Nov 26 '18 at 18:36 answered Dec 29 '16 at 12:39


selem mn
7,467 4 27 46

3 is there a way to easily include the styles if printContents as appeared in the original site screen? – amit Jun 13 '17 at 9:22

@amit actually I didnt try to think about it. – selem mn Jun 13 '17 at 11:10

@selemmn i spend many hours trying to figure it out without success. If you do find a way, i would love to know – amit Jun 13 '17 at 11:14

@amit could you provide a plunker for your issue ? – selem mn Jun 13 '17 at 12:25

@selemmn it is a bit hard because it is a complex angular 2 project with many components and many styles... – amit Jun 13 '17 at 12:40

In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your
print page. You can then simply attach a print function to your html button and in your component call window.print();
21
component.html:

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 2/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

<div class="doNotPrint">
Header is here.
</div>

<div>
all my beautiful print-related material is here.
</div>

<div class="doNotPrint">
my footer is here.
<button (click)="onPrint()">Print</button>
</div>

component.ts:

onPrint(){
window.print();
}

component.css:

@media print{
.doNotPrint{display:none !important;}
}

You can optionally also add other elements / sections you do not wish to print in the media query.

You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is
one that seems comprehensive: https://www.sitepoint.com/create-a-customized-print-stylesheet-in-minutes/ It also means you don't have to
create a separate script to create a 'print version' of the page or use lots of javascript.

edited Jul 10 '18 at 16:45 answered Dec 28 '17 at 1:48


Sabyasachi Patra Farasi78
580 3 10 810 7 15

3 YouBy using
could our
also site,
use theyou acknowledge
:not() that
selector from cssyou have
thus, read
using anda understand
only class on theour Cookie
element Policy
that , Privacy
will be printed.Policy, and<div
Example: our Terms of Service. something to print
class="print_this">

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 3/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

</div> then on css file: @media print{ :not(.print_this){display:none;!important} } – Charleston Mar 19 '18 at 17:06

How could I use this to print the content of a sub-child div? Hierarchically I have this situation: MainComponent > DashboardComponent > DivToPrint. It's a chain
of router-outlets. How could I set this up to use this @media query? – Luca Effe Federzoni Apr 23 '19 at 7:34

@LucaEffeFederzoni I believe it works regardless of your hierarchy, as long as you mark each div appropriately. I.e. in DashboardComponent, mark everything
that should not be printed as 'do not print', it can get a bit complicated, and in that case, you may want to do what others suggest which is to create a single page
for printing. If you use Angular, To avoid repeating CSS, put the do not print rule in your app.component.css and add it to the styleUrls for each component you
need it. – Farasi78 Apr 23 '19 at 12:54

@Farasi78 It works indeed, but not entirely. I created a directive that prints the contents of the dive which is applied but the print is a bit odd. Thanks for the help
by the way, at least I managed to progress. – Luca Effe Federzoni Apr 23 '19 at 13:31

I am trying to print a table with 50 column but on print document template it displays only 20 columns rest of all are hidden. Could you please help me how to
solve this issue and display entire table's column in single row? – aman jain Jul 16 '19 at 11:55

you can do like this in angular 2

11 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=

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
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 4/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

<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>

edited Dec 29 '16 at 13:59 answered Dec 29 '16 at 12:29


Neeraj Rathod Vikash Dahiya
1,325 3 12 21 4,745 3 16 22

Your answer needs some correction, You were very close. thank for your quick response, I upvoted answer :) – Neeraj Rathod Dec 29 '16 at 13:03

Actually i gave this answer without testing , i will update it soon – Vikash Dahiya Dec 29 '16 at 13:09

I have updated it, It's working for me. test it, do the correction if needed – Neeraj Rathod Dec 29 '16 at 13:10

if i enter any text in text feild it not printed – nilesh Nov 14 '17 at 13:31

EDIT: updated the snippets for a more generic approach

6 Just as an extension to the accepted answer,

For getting the existing styles to preserve the look 'n feel of the targeted component, you can:
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
1. make a query to pull the <style> and <link> elements from the top-level document
https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 5/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

2. inject it into the HTML string.

To grab a HTML tag:

private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string


{
const htmlStr: string[] = [];
const elements = document.getElementsByTagName(tagName);
for (let idx = 0; idx < elements.length; idx++)
{
htmlStr.push(elements[idx].outerHTML);
}

return htmlStr.join('\r\n');
}

Then in the existing snippet:

const printContents = document.getElementById('print-section').innerHTML;


const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');

const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');


popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
${linksHtml}
${stylesHtml}
^^^^^^^^^^^^^ add them as usual to the head
</head>
<body onload="window.print(); window.close()">
${printContents}
</body>
</html>
`
);
popupWin.document.close();

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 6/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap,
MaterialDesign, Bulma) it should look like a snippet of the existing screen

edited Nov 13 '18 at 1:23 answered Oct 8 '18 at 6:35


lenard-bernardo-ei
61 1 4

Use the library ngx-print.

3 Installing:

yarn add ngx-print


or
npm install ngx-print --save

Change your module:

import {NgxPrintModule} from 'ngx-print';


...
imports: [
NgxPrintModule,
...

Template:

<div id="print-section">
// print content
</div>
<button ngxPrint printSectionId="print-section">Print</button>

More details

answered
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of ServiceJul
. 25 '19 at 16:53
progm
https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 7/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

1,504 1 9 27

Can you provide details on custom css file – San Jaisy Jun 22 at 13:05

yes, you can add custom style or existing style. Check ngx-print documentation – Suroor Ahmmad Sep 3 at 11:25

Print service

3 import { Injectable } from '@angular/core';

@Injectable()
export class PrintingService {

public print(printEl: HTMLElement) {


let printContainer: HTMLElement = document.querySelector('#print-container');

if (!printContainer) {
printContainer = document.createElement('div');
printContainer.id = 'print-container';
}

printContainer.innerHTML = '';

let elementCopy = printEl.cloneNode(true);


printContainer.appendChild(elementCopy);
document.body.appendChild(printContainer);

window.print();
}
}

Сomponent that I want to print

@Component({
selector: 'app-component',
templateUrl: './component.component.html',
styleUrls: ['./component.component.css'],
encapsulation: ViewEncapsulation.None
})
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
export class MyComponent {

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 8/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow
@ViewChild('printEl') printEl: ElementRef;

constructor(private printingService: PrintingService) {}

public print(): void {


this.printingService.print(this.printEl.nativeElement);
}

Not the best choice, but works.

answered Nov 13 '17 at 6:27


Kliment Ru
1,575 8 15

1 Isn't this going to print the whole page instead of juts that element? – Reza Oct 25 '18 at 16:02

don't forget to add css @media print and play with display and visibility to make the above code works – yohanes Feb 24 at 3:27

Shortest solution to be assign the window to a typescript variable then call the print method on that, like below

1 in template file

<button ... (click)="window.print()" ...>Submit</button>

and, in typescript file

window: any;
constructor() {
this.window = window;
}

answered
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of ServiceJul
. 3 '19 at 19:41
Shubhasish Bhunia
https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 9/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

49 6

I ran into the same issue and found another way to do this. It worked for in my case as it was a relatively small application.

1 First, the user will a click button in the component which needs to be printed. This will set a flag that can be accessed by the app component.
Like so

.html file

<button mat-button (click)="printMode()">Print Preview</button>

.ts file

printMode() {
this.utilities.printMode = true;
}

In the html of the app component, we hide everything except the router-outlet. Something like below

<div class="container">
<app-header *ngIf="!utilities.printMode"></app-header>
<mat-sidenav-container>
<mat-sidenav *ngIf="=!utilities.printMode">
<app-sidebar></app-sidebar>
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
</div>

With similar ngIf conidtions, we can also adjust the html template of the component to only show or hide things in printMode. So that the user
will see only what needs to get printed when print preview is clicked.

We canBynow
using our site,
simply youoracknowledge
print go back to that you mode
normal have read
withand
theunderstand
below codeour Cookie Policy, Privacy Policy, and our Terms of Service.

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 10/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

.html file

<button mat-button class="doNotPrint" (click)="print()">Print</button>


<button mat-button class="doNotPrint" (click)="endPrint()">Close</button>

.ts file

print() {
window.print();
}

endPrint() {
this.utilities.printMode = false;
}

.css file (so that the print and close button's don't get printed)

@media print{
.doNotPrint{display:none !important;}
}

answered Feb 5 '19 at 14:16


Bharat Raj Saya
9 2

The best option I found to solve this without getting into trouble with my styles was using a separate route for my printed output and load this
route into an iframe.
0
My surrounding component is shown as a tab page.

@Component({
template: '<iframe id="printpage" name="printpage" *ngIf="printSrc" [src]="printSrc">
</iframe>',
By using
styleUrls : [our site, you acknowledge
'previewTab.scss' ] that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
})
https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 11/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow
export class PreviewTabPage {
printSrc: SafeUrl;

constructor(
private navParams: NavParams,
private sanitizer: DomSanitizer,
) {
// item to print is passed as url parameter
const itemId = navParams.get('itemId');

// set print page source for iframe in template


this.printSrc =
this.sanitizer.bypassSecurityTrustResourceUrl(this.getAbsoluteUrl(itemId));
}

getAbsoluteUrl(itemId: string): string {


// some code to generate an absolute url for your item
return itemUrl;
}
}

The iframe just loads the print route that renders a print component in the app. In this page the print might be triggered after the view is fully
initialized. Another way could be a print button on the parent component that triggers the print on the iframe by
window.frames["printpage"].print(); .

@Component({
templateUrl: './print.html',
styleUrls: [ 'print.scss' ]
})
export class PrintPage implements AfterViewInit {

constructor() {}

ngAfterViewInit() {
// wait some time, so all images or other async data are loaded / rendered.
// print could be triggered after button press in the parent component as well.
setTimeout(() => {
// print current iframe
window.print();
}, 2000);
}

} By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 12/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

answered May 24 '18 at 18:50


Dave Gööck
306 1 11

Windows applications usually come with build in print capability, but for a web application, I would choose to simply generate a PDF file.

0 The simplest way that I found is to generate a PDf file using PDFMake (www.pdfmake.org). You can then offer the user the choice to open or
download the generated PDF file.

answered May 28 '19 at 11:29


Edwin Teisman
16 1

If you need to print some custom HTML, you can use this method:

0 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">


By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
</iframe>

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 13/14
12/8/2020 javascript - Print Html template in Angular 2 (ng-print in Angular 2) - Stack Overflow

answered Oct 26 '19 at 0:03


Pablo Chvx
1,181 12 27

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.

https://stackoverflow.com/questions/41379274/print-html-template-in-angular-2-ng-print-in-angular-2 14/14

You might also like