In this article, we saw how to export or open PDF in angular using JSPDF. In the last article, we discuss how to read CSV we have added option their to open PDF & export PDF. Let’s create a new project that you need to run following command
ng new pdf-generate
“pdf-generate” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd pdf-generate”. To Run angular applications, it required to run “ng serve”.
After we need to install “JSPDF”
npm install jspdf
After install module we can use these module in our component. we need to import “jsPDF”.
import jspdf from 'jspdf';
We need to create function for open pdf & download pdf functions. In that functions we use “new jsPDF()” we need tp pass the PDF size. We have used element refrance to get the html to print the pdf.
Open Pdf Function
@ViewChild('htmlData', {static: false}) htmlData:ElementRef;
//Open Pdf File
openPDF(){
let DATA = this.htmlData.nativeElement;
let doc = new jspdf('p','pt', 'a4');
doc.setProperties({
title: "new Report"
});
doc.fromHTML(DATA.innerHTML,30 ,30);
window.open(URL.createObjectURL(doc.output("blob")))
}
Download Pdf Function
//Download Pdf File
downloadPDF(){
let DATA = this.htmlData.nativeElement;
let doc = new jspdf('p','pt', 'a4');
let handleElement = {
'#editor':function(element,renderer){
return true;
}
};
doc.fromHTML(DATA.innerHTML,15,15,{
'width': 200,
'elementHandlers': handleElement
});
doc.save('csvpdf.pdf');
}
Display below is the code for the app.component.ts ,app.component.html,app.component.css
Output
Below is the full embeded code export or Open PDF in Angular using JSPDF. you can easily used in your application.
Example