Introduction
Sometimes, we need to provide the important data of an application in the form of a document like a PDF or an image. Those times we need to convert the HTML layout into the document, and here, we are going to do the same task to convert the HTML into PDF.
I went through many links but was unable to find a quick solution. In the end, I found a JavaScript named JSPDF.
You can find their official documentation here.
And also, I have used another npm package named html2canvas, which is used to convert the HTML into Canvas and then, we can put the image files into our pdf document. For that, we need to download their dependencies.
Just use the below npm commands.
- npm install jspdf
And to install html2canvas package, use given npm command.
- npm install html2canvas
- import * as jspdf from 'jspdf';
- import html2canvas from 'html2canvas';
- <div id="content" #content>
- <mat-card>
- <div class="alert alert-info">
- <strong>Html To PDF Conversion - Angular 6</strong>
- </div>
- <div>
- <input type="button" value="CPTURE" (click)="captureScreen()"/>
- </div>
- </mat-card>
- </div>
- <div >
- <mat-card>
- <table id="contentToConvert">
- <tr>
- <th>Column1</th>
- <th>Column2</th>
- <th>Column3</th>
- </tr>
- <tr>
- <td>Row 1</td>
- <td>Row 1</td>
- <td>Row 1</td>
- </tr>
- <tr>
- <td>Row 2</td>
- <td>Row 2</td>
- <td>Row 2</td>
- </tr>
- <tr>
- <td>Row 3</td>
- <td>Row 3</td>
- <td>Row 3</td>
- </tr>
- <tr>
- <td>Row 4</td>
- <td>Row 4</td>
- <td>Row 4</td>
- </tr>
- <tr>
- <td>Row 5</td>
- <td>Row 5</td>
- <td>Row 5</td>
- </tr>
- <tr>
- <td>Row 6</td>
- <td>Row 6</td>
- <td>Row 6</td>
- </tr>
- </table>
- </mat-card>
- </div>

I have used a capture button to generate the PDF of an HTML table. So, when I click the Capture button, it will generate a PDF in A4 size of paper. Now, open app.component.ts file and write the method as described below.
- import { Component, OnInit, ElementRef ,ViewChild} from '@angular/core';
- import * as jspdf from 'jspdf';
- import html2canvas from 'html2canvas';
- @Component({
- selector: 'app-htmltopdf',
- templateUrl: './htmltopdf.component.html',
- styleUrls: ['./htmltopdf.component.css']
- })
- export class HtmltopdfComponent{
- public captureScreen()
- {
- var data = document.getElementById('contentToConvert');
- html2canvas(data).then(canvas => {
- // Few necessary setting options
- var imgWidth = 208;
- var pageHeight = 295;
- var imgHeight = canvas.height * imgWidth / canvas.width;
- var heightLeft = imgHeight;
- const contentDataURL = canvas.toDataURL('image/png')
- let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
- var position = 0;
- pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
- pdf.save('MYPdf.pdf'); // Generated PDF
- });
- }
- }
For that, I have provided a few settings, like image height, width, left margin, etc.
JsDF has a syntax that decides its layout when it generates the PDF.
- new JsPDF(
- Orientation, // Landscape or Portrait
- unit, // mm, cm, in
- format // A2, A4 etc
- );
Other similar methods are given below.
- addHTML()
- addFont()
- addPage()
- addMetaData()
Now, it's time to execute our application using ng serve -o command, and see the expected output.

Conclusion
This is how we can convert our HTML code into PDF format, including font settings, images, metadata, etc. For more functionalities, you can refer to their official documentation.
Follow my other blogs in Angular.
If you have any doubts, feel free to ask me via comments. Thanks for reading.

praveen kumarPosted Mar 22, 2021, 8:19 AM
I have more content , only single page is display9ing print pdf
Darshan MalaniPosted Jan 21, 2021, 2:56 PM
How to add logo on top ?
Amit ShirkePosted Apr 12, 2020, 1:25 AM
Hi Manav, I am able to generate pdf using this code. But My html page contains bar chart and its bar colors are in different colors. This code is not able to get those colors in pdf. plz help. Thanks
Abhishek RonanPosted Apr 9, 2020, 4:14 AM
Let pdf = new jspdf('p', 'mm', 'a4'); / modify it as let pdf = new jsPDF('p', 'mm', 'a4'); // A4 size page of PDF
Eugine SagayamPosted Jan 28, 2020, 9:20 PM
How to add Header and Footer for Each page.
shiva gPosted Jan 28, 2020, 12:41 AM
Here's the code how I implemented. doc.addHTML(this.pdfPage.nativeElement, 0, 0, {pagesplit: true }, function () { const blob = doc.output('blob'); if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob); } else { window.open(URL.createObjectURL(blob)); } });
shiva gPosted Jan 28, 2020, 12:40 AM
How can I improve quality of the pdf? How can I calculate height and set the fields accordingly to move the fields to next page? Currently fields are splitting in 2 pages while pdf conversion.
shiva gPosted Jan 28, 2020, 12:35 AM
My page has many form fields, word warp and break work properties are not applying while page is converting to pdf.
Former memberPosted Dec 16, 2019, 1:40 AM
Very use full
Chittaranjan SwainPosted Nov 27, 2019, 9:05 PM
Very useful article.
Guest UserPosted Oct 1, 2019, 4:12 PM
I wrote a efficient answer oh how to generate HTML to PDF with page breaks, larger dynamic images and Repeated headers. Follow this link https://stackoverflow.com/questions/55019343/how-to-generate-a-pdf-using-angular-7/58142786#58142786
Uthpala PathiranaPosted Sep 4, 2019, 11:03 PM
I have canvas elements in my HTML page which are some charts generated through charts.js. How can I include them in the PDF?
Arun KumarPosted Sep 3, 2019, 8:39 AM
Manav example is really good and express with nice manner, but when I install jspdf and canvas that is not installed, pls check error: npm ERR! code ENOENTnpm ERR! syscall spawn gitnpm ERR! path git npm ERR! errno ENOENT npm ERR! enoent Error while executing: npm ERR! enoent undefined ls-remote -h -t ssh://[email protected]/eligrey/FileSaver.js.git npm ERR! enoent npm ERR! enoent npm ERR! enoent spawn git ENOENT npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\arunkumar.sr\AppData\Roaming\npm-cache\_logs\2019-09-03T13_37_43_575Z-debug.log
Ngọc HuỳnhPosted Aug 8, 2019, 2:49 AM
Remove current html2canvas package version and reinstall: npm [email protected]. to resolve it
Nikunj GhelaniPosted Aug 7, 2019, 1:18 AM
And my function is like this html2canvas(data).then(canvas => { // Few necessary setting options var imgWidth = 208; var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; const contentDataURL = canvas.toDataURL('../assets/ReportPdf') let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF var position = 0; pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight) pdf.save('MYPdf.pdf'); // Generated PDF }); }
Nikunj GhelaniPosted Aug 7, 2019, 1:17 AM
Hi i use your code in to my system and i got this error Error: Supplied Data is not a valid base64-String jsPDF.convertStringToImageData
Nikunj GhelaniPosted Aug 7, 2019, 1:17 AM
Hi i am nikunj and i got this error while i set your example to my system
Ntr TraPosted Jul 17, 2019, 3:16 AM
Hi, I implemented the pdf printing and it works, except that I have a long page and the printing only takes into account the beginning. A track for me?
Ajit BhomkarPosted Jun 27, 2019, 1:22 AM
How to remove white show paces at the bottom of PDF
Sathya VPosted May 22, 2019, 7:32 AM
Hello sir, In angular 7 JSPDF is not working. Please help me to resolve this.
Bittan SharmaPosted May 20, 2019, 5:05 AM
Actually I want pdf serchable and added custom header and footer .Is this possible or not
Vignesh MohanrajPosted May 5, 2019, 3:13 AM
Nice but I am using amcharts and export as PDF , the charts are showing ugly how to correct this.?
shahabaz bossPosted Apr 7, 2019, 1:07 AM
How do you handle the same for multiple pages ?
Former memberPosted Mar 31, 2019, 2:54 AM
Awesome, I just need to know How to give margins to that pdf?
Muhammad khanPosted Mar 15, 2019, 7:50 AM
How to use for multiple tables
Erwin BustilloPosted Mar 5, 2019, 11:43 AM
This words with graphics for example ng2charts or chartjs?. This supports html content with bootstrap 4 classes ?. I want to used in angular 7.2
Aawlad RajibPosted Feb 26, 2019, 12:42 AM
Hello sir, In angular 7 JSPDF does it work?
Sylvain CGIPosted Feb 6, 2019, 10:57 AM
Not works on Internet Explorer Edge :(
AminPosted Jan 26, 2019, 6:04 AM
Thank you, and how can we create report PDF customised ?
Vipul NanavarePosted Nov 23, 2018, 7:05 AM
How to handle if data is to large because its just create one pdf page
IsmaȜil ShnAidarPosted Oct 4, 2018, 11:06 AM
But it's not printing Images with the document, any help pls <3?
PRUDHVI RAJPosted Oct 4, 2018, 8:41 AM
Actually i am a beginner, i tried window.open("data:MYPdf.pdf,"); thisone but i am unable to get file,
PRUDHVI RAJPosted Oct 4, 2018, 8:39 AM
Actually in your code we can download pdf but i want to view without download.
PRUDHVI RAJPosted Oct 4, 2018, 8:38 AM
Hi bro, i have requirement in my project of showing pdf file without downloading,
mohamed testPosted Oct 2, 2018, 12:16 AM
Is there a a way to do the same thing with svg ?? because i a getting an error while using this method with svg charts
Manjunath KPosted Sep 26, 2018, 3:54 PM
How to save pdf file in specific location...?
Alfarish Fizikri MPosted Sep 26, 2018, 12:18 PM
Is this worked with mat-table too?
Sitaramaiah EkkurthiPosted Sep 25, 2018, 1:35 PM
Its working superb in all browsers except internet explorer. however I am facing issue in internet explorer. I am not able to print it.
Usama WahidPosted Sep 24, 2018, 6:40 AM
Any example for Angular 5. if someone has please let me know. thanks
pranjal vermaPosted Sep 19, 2018, 6:16 AM
Will it also convert input text field values to? which are entered by user?
Ram ThakurPosted Aug 22, 2018, 3:37 AM
Html2canvas is not working in Anuglar 6.1.1. Please let me know if I need to add something to make it workable.
Luis HernándezPosted Aug 19, 2018, 4:14 PM
What do you make when the image is big ? when image is more big than page size?
Raju SPosted Aug 1, 2018, 4:52 AM
$("#load").button('loading'); $("#contentToConvert").show(); var data = document.getElementById('contentToConvert'); html2canvas(data).then(canvas => { // Few necessary setting options var imgWidth = 208; var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; const contentDataURL = canvas.toDataURL('image/png') var options = { pagesplit: true }; let pdf = new jsPDF('p', 'mm', 'a4'); // A4 size page of PDF var position = 0; pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight,options) pdf.save('DailySales.pdf'); // Generated PDF $("#load").button('reset'); $("#contentToConvert").hide(); }); }
Raju SPosted Aug 1, 2018, 4:52 AM
Which place i will add "pagesplit: true" option,here my code
Maricris FajutaganaPosted Jul 31, 2018, 10:53 PM
Hi Manav, can this also be used for cross-origin images that will be put inside the generated pdf file?
Raju SPosted Jul 30, 2018, 1:54 AM
Sir super ,but i cannot get 2 page pdf view .i only got single page ..please explain multi-page..
Ravi RaghavPosted Jul 30, 2018, 1:15 AM
Hi Manav, nice article, as per my understanding it would take the screenshot of the visible part and then convert it into pdf but what if my page has a scroll and there is some content below the visible part of browser? how can we handle that?
Hiten PandyaPosted Jul 27, 2018, 7:43 AM
Good Article Manav.
Bhavesh JadavPosted Jul 27, 2018, 7:28 AM
Nice article Manav.....
dery febriantaraPosted Jul 26, 2018, 5:03 AM
You saved my life dude....
julius knownPosted Jul 18, 2018, 2:21 PM
When I add this as a component to my Angular 6 app I get "An unhandled exception occurred while processing the request. NodeInvocationException: Prerendering failed because of error: ReferenceError: window is not defined".
Viknaraj ManogararajahPosted Jul 14, 2018, 11:04 PM
Nice Article, Thank you for sharing.........
Nour SroujiPosted Jul 13, 2018, 11:59 AM
Good article it worked but if I have a long html page it crops the page so not everything shows.Do you know how to fix that? Thank you
Bhairab DuttPosted Jul 6, 2018, 3:40 AM
Nice Article ......
Dharmraj ThakurPosted Jul 6, 2018, 1:23 AM
Nice one article manav
Mahesh VermaPosted Jul 6, 2018, 12:37 AM
Nice article Manav :-)