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, 4:19 AM EDT
I have more content , only single page is display9ing print pdf
Darshan MalaniPosted Jan 21, 2021, 9:56 AM EST
How to add logo on top ?
Amit ShirkePosted Apr 11, 2020, 9:25 PM EDT
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, 12:14 AM EDT
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, 4:20 PM EST
How to add Header and Footer for Each page.
shiva gPosted Jan 27, 2020, 7:41 PM EST
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 27, 2020, 7:40 PM EST
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 27, 2020, 7:35 PM EST
My page has many form fields, word warp and break work properties are not applying while page is converting to pdf.
Former memberPosted Dec 15, 2019, 8:40 PM EST
Very use full
Chittaranjan SwainPosted Nov 27, 2019, 4:05 PM EST
Very useful article.
Guest UserPosted Oct 1, 2019, 12:12 PM EDT
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, 7:03 PM EDT
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, 4:39 AM EDT
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 7, 2019, 10:49 PM EDT
Remove current html2canvas package version and reinstall: npm [email protected]. to resolve it
Nikunj GhelaniPosted Aug 6, 2019, 9:18 PM EDT
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 6, 2019, 9:17 PM EDT
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 6, 2019, 9:17 PM EDT
Hi i am nikunj and i got this error while i set your example to my system
Ntr TraPosted Jul 16, 2019, 11:16 PM EDT
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 26, 2019, 9:22 PM EDT
How to remove white show paces at the bottom of PDF
Sathya VPosted May 22, 2019, 3:32 AM EDT
Hello sir, In angular 7 JSPDF is not working. Please help me to resolve this.
Bittan SharmaPosted May 20, 2019, 1:05 AM EDT
Actually I want pdf serchable and added custom header and footer .Is this possible or not
Vignesh MohanrajPosted May 4, 2019, 11:13 PM EDT
Nice but I am using amcharts and export as PDF , the charts are showing ugly how to correct this.?
shahabaz bossPosted Apr 6, 2019, 9:07 PM EDT
How do you handle the same for multiple pages ?
Former memberPosted Mar 30, 2019, 10:54 PM EDT
Awesome, I just need to know How to give margins to that pdf?
Muhammad khanPosted Mar 15, 2019, 3:50 AM EDT
How to use for multiple tables
Erwin BustilloPosted Mar 5, 2019, 6:43 AM EST
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 25, 2019, 7:42 PM EST
Hello sir, In angular 7 JSPDF does it work?
Sylvain CGIPosted Feb 6, 2019, 5:57 AM EST
Not works on Internet Explorer Edge :(
AminPosted Jan 26, 2019, 1:04 AM EST
Thank you, and how can we create report PDF customised ?
Vipul NanavarePosted Nov 23, 2018, 2:05 AM EST
How to handle if data is to large because its just create one pdf page
IsmaȜil ShnAidarPosted Oct 4, 2018, 7:06 AM EDT
But it's not printing Images with the document, any help pls <3?
PRUDHVI RAJPosted Oct 4, 2018, 4:41 AM EDT
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, 4:39 AM EDT
Actually in your code we can download pdf but i want to view without download.
PRUDHVI RAJPosted Oct 4, 2018, 4:38 AM EDT
Hi bro, i have requirement in my project of showing pdf file without downloading,
mohamed testPosted Oct 1, 2018, 8:16 PM EDT
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, 11:54 AM EDT
How to save pdf file in specific location...?
Alfarish Fizikri MPosted Sep 26, 2018, 8:18 AM EDT
Is this worked with mat-table too?
Sitaramaiah EkkurthiPosted Sep 25, 2018, 9:35 AM EDT
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, 2:40 AM EDT
Any example for Angular 5. if someone has please let me know. thanks
pranjal vermaPosted Sep 19, 2018, 2:16 AM EDT
Will it also convert input text field values to? which are entered by user?
Ram ThakurPosted Aug 21, 2018, 11:37 PM EDT
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, 12:14 PM EDT
What do you make when the image is big ? when image is more big than page size?
Raju SPosted Aug 1, 2018, 12:52 AM EDT
$("#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, 12:52 AM EDT
Which place i will add "pagesplit: true" option,here my code
Maricris FajutaganaPosted Jul 31, 2018, 6:53 PM EDT
Hi Manav, can this also be used for cross-origin images that will be put inside the generated pdf file?
Raju SPosted Jul 29, 2018, 9:54 PM EDT
Sir super ,but i cannot get 2 page pdf view .i only got single page ..please explain multi-page..
Ravi RaghavPosted Jul 29, 2018, 9:15 PM EDT
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, 3:43 AM EDT
Good Article Manav.
Bhavesh JadavPosted Jul 27, 2018, 3:28 AM EDT
Nice article Manav.....
dery febriantaraPosted Jul 26, 2018, 1:03 AM EDT
You saved my life dude....
julius knownPosted Jul 18, 2018, 10:21 AM EDT
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 ManogararajahTOP 100Posted Jul 14, 2018, 7:04 PM EDT
Nice Article, Thank you for sharing.........
Nour SroujiPosted Jul 13, 2018, 7:59 AM EDT
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 5, 2018, 11:40 PM EDT
Nice Article ......
Dharmraj ThakurPosted Jul 5, 2018, 9:23 PM EDT
Nice one article manav
Mahesh VermaPosted Jul 5, 2018, 8:37 PM EDT
Nice article Manav :-)