How to convert HTML content to PDF in Angular

Issue

I am trying to generate the PDF file from HTML content.
contentDataURL is having the empty image data. I have tried changing the HTML content also but the same empty image is getting generated.
What’s wrong with my canvas.toDataURL() implementation?
PDF file generation is working fine.

my code app link
https://stackblitz.com/edit/angular-ivy-1aug8i

<div class="test" id="test">
     <button (click)="sendToPdf()"> 
         testpdf</button> </div>
         <div class="abc" id="testdivid">
            <table style="width:100%">
                <tr>
                  <th>Firstname</th>
                  <th>Lastname</th>
                  <th>Age</th>
                </tr>
                <tr>
                  <td>Jill</td>
                  <td>Smith</td>
                  <td>50</td>
                </tr>
                <tr>
                  <td>Eve</td>
                  <td>Jackson</td>
                  <td>94</td>
                </tr>
              </table>
         </div>
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';


sendToPdf(){
  let data = document.getElementById("test"); 
    // let data = document.getElementById("maindiv");
    console.log(data);  
    html2canvas(data).then(canvas => {
      const contentDataURL = canvas.toDataURL('image/jpeg', 1.0)
      console.log(contentDataURL);  
      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');   
    }); 
}

Solution

after reinstalling html2canvas worked fine

import html2canvas from 'html2canvas';
import jspdf from 'jspdf';


sendToPdf(){
  let data = document.getElementById("test"); 
    // let data = document.getElementById("maindiv");
    console.log(data);  
    html2canvas(data).then(canvas => {
      const contentDataURL = canvas.toDataURL('image/jpeg', 1.0)
      console.log(contentDataURL);  
      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');   
    }); 
}

Answered By – Virendra

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.