I have a component (Angular 6) which is an aggregation of several components. This produces a long HTML (I am using Bootstrap 4). Now I want to convert this HTML to PDF. I have
The following code was used and worked for my project
Step 1 : Run following commands to install npm packages
> npm install jspdf
> npm install html2canvas
Step 2: Import installed packages in app.components.ts. I haven't imported those packages in constructor()
> import * as jspdf from 'jspdf';
> import html2canvas from 'html2canvas';
Step 3: Give an id for the HTML div that has to be exported as PDF. Add a button that activates the function too.
Step 4 : Write the code for generating PDF as follows
exportAsPDF(div_id)
{
let data = document.getElementById(div_id);
html2canvas(data).then(canvas => {
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('l', 'cm', 'a4'); //Generates PDF in landscape mode
// let pdf = new jspdf('p', 'cm', 'a4'); Generates PDF in portrait mode
pdf.addImage(contentDataURL, 'PNG', 0, 0, 29.7, 21.0);
pdf.save('Filename.pdf');
});
}