angularjspdfng2-charts

How to I insert ng2-chart into jsPdf document?


I have a few line charts that I made using ng2-charts in my program. I was able to tabulate the data onto a jsPdf document with the help of AutoTable

autoTable(doc, {
      startY: 190,                    
      theme: 'grid',
      headStyles: {
        fillColor: [32,42,68]
      },
      head: [//Arry],
      body: //detArr,
     // bodyStyles: {lineColor: [0, 0, 0]}
    });

Is there a way that I can directly position the HTML DOM Canvas element of the chart into the pdf file so that I can prepare it for printing and presentation?

<canvas baseChart width="1000" height="250" [type]="'line'" [data]="chartData" [options]="lineChartOptions" [legend]="lineChartLegend"></canvas>


Solution

  • Pre-requisites:

    <canvas #baseChart width="1000" height="250" [type]="'line'" [data]="chartData" 
        [options]="lineChartOptions" [legend]="lineChartLegend"></canvas>
    
    import { Component, ElementRef, Inject, ViewChild } from '@angular/core';
    
    @ViewChild('baseChart', { static: true })
      canvasElem: ElementRef<HTMLCanvasElement>;
    
    1. Create a jsPDF instance.

    2. Convert the <canvas> element to image.

    3. Add the image into PDF via addImage method. You may also customize your image such as coordinates, sizes, etc.

    4. Export the PDF.

    const pdf = new jsPDF({
      unit: 'px',
      format: [595, 842],
    });
    
    let img = this.canvasElem.nativeElement.toDataURL('image/png');
    pdf.addImage(img, 'PNG', 10, 10, 580, 300);
    
    pdf.save(/* File name */);