As a developer, many times we can be required to convert HTML content to PDF files. So, here I’ll explain about converting HTML content into PDF files in an angular application. For the task, I will use jspdf.
Using the below code, the developer easily converts HTML to PDF files. and using this code convert images to pdf format.
So, let’s see below example from here:
Step 1: Create an Angular app using CLI
Create an Angular Folder and create an angular app with this command
ng new generate-pdf cd generate-pdf
Step 2: Run the following commands in CLI to install latest packages
This package used to convert HTML data to pdf format
npm i jspdf npm i html2canvas
Step 3: Update app.component.ts file
Open the app. component.ts file and add the below code.
open the ts file for update code and then put the below code.
import { Component } from '@angular/core'; import { jsPDF } from 'jspdf' import html2canvas from 'html2canvas'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { captureScreen() { let data = document.getElementById('contentToConvert'); html2canvas(data as any).then(canvas => { var imgWidth = 210; var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; const contentDataURL = canvas.toDataURL('image/png'); let pdfData = new jsPDF('p', 'mm', 'a4'); var position = 0; pdfData.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight) pdfData.save(`MyPdf.pdf`); }); } }
Step 4: Update app.component.html file
<div> <input type="button" value="Convert" (click)="captureScreen()"/> </div> <div id="contentToConvert"> <h2>HTML Table</h2> <div> <img src="../assets/capture.png" width="300px"> </div> <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> <tr> <td>Island Trading</td> <td>Helen Bennett</td> <td>UK</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Yoshi Tannamuri</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Giovanni Rovelli</td> <td>Italy</td> </tr> </table> </div>
In the above file, We have a table That will convert HTML to PDF files. Click on the top button and HTML convert to pdf
Step 5: Run The App
ng serve
Code in action
how to change download path of PDF File when pdf file download????????????