How to convert your HTML Page to PDF in Angular 8 9 10

How to convert your HTML Page to PDF in Angular 8 9 10

Hello Friends, In this Article I will tell you to convert your html page into pdf in angular, also will learn how to download your pdf file or open pdf file into new tab directly on click event into some simple steps.

Step1:

First you have create a fresh angular app or you can add it into your existing project but i recommend for create a new angular app follow by simple below command, open your command prompt and type below command

ng new my-new-app

after run this command. It will take 2 or three minutes and your new angular application created successfully. Now we have to install packages for pdf.

Step2:

Next step We need to run some below command into our project

npm install –save pdfmake

npm install html-to-pdfmake

npm install jspdf –save

Step3:

Now add this below code into your app-component.ts file

import { Component, ViewChild, ElementRef  } from '@angular/core';

import jsPDF from 'jspdf';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import htmlToPdfmake from 'html-to-pdfmake';

export class AppComponent {
  @ViewChild('pdfDiv') pdfDiv: ElementRef;
  public downloadAsPDF() {
    const doc = new jsPDF();
    const pdfDiv= this.pdfDiv.nativeElement;
    var html = htmlToPdfmake(pdfDiv.innerHTML);
    const documentDefinition = { content: html };
    pdfMake.createPdf(documentDefinition).open(); // Open your pdf file into new tab
  }  
}

Step4:

Next step Just add below code in your HTML file.

<button class="btn btn-primary" (click)="downloadAsPDF()">Download or open PDF file</button>
<div id="pdfDiv" #pdfDiv>
    <h2>HTML To PDF</h2>  
   <h1>Your HTML code successfully convert to pdf file</h1>
</div>

Please feel free to ask question on our developer Channel

Leave a Comment

Show Buttons
Hide Buttons