if you want to generate a pdf file from datatable / Array or content in HTML Div :

  1. run this :
npm i jspdf
npm i html2canvas

2. import :

import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';

3. create the datatable or the content to print in html div:


<div #contentToConvert>  
 // here the content or the datatable to print in pdf file
</div>

4. Create a button to generate PDF and put the as click action “generatePdf(contentToConvert)”

     <button  (click)="generatePdf(contentToConvert)">Export pdf</button> 

5. Finaly past this function into the TS file of the component

generatePdf(data) {
    html2canvas(data, { allowTaint: true }).then(canvas => {
      let HTML_Width = canvas.width;
      let HTML_Height = canvas.height;
      let top_left_margin = 15;
      let PDF_Width = HTML_Width + (top_left_margin * 2);
      let PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
      let canvas_image_width = HTML_Width;
      let canvas_image_height = HTML_Height;
      let totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
      canvas.getContext('2d');
      let imgData = canvas.toDataURL("image/jpeg", 1.0);
      let pdf = new jspdf.jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
      pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
      for (let i = 1; i <= totalPDFPages; i++) {
        pdf.addPage([PDF_Width, PDF_Height], 'p');
        pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
      }
      pdf.save("Historique_véhicules.pdf");
    });
  }

Laisser un commentaire