Convert HTML to PDF in Angular 6

后端 未结 6 1691
执念已碎
执念已碎 2021-02-05 04:50

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

6条回答
  •  梦如初夏
    2021-02-05 05:46

    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');   
        }); 
      }
    

提交回复
热议问题