Search code examples
c#.nethiqpdf

HiQPdf isn't rendering Chart.js chart on pdf


My organization uses HiQPdf to create PDFs from .Net MVC Razor views. I am wanting to include a chart using the Chart.js library in the view/pdf. The problem is that when the pdf is rendered from the view the chart doesn't show up on the page. The chart shows up fine when rendered as a view.

Here is the chart.js code:

var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '# of Complaints',
                    data: data,
                    backgroundColor: 'rgba(11, 73, 150, 1)',
                    borderColor: 'rgba(11, 73, 150, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true,
                            precision: 0,
                            fontSize: 18,
                            fontColor: '#000'
                        }
                    }],
                    xAxes: [{
                        ticks: {
                            fontSize: 18,
                            fontColor: '#000'
                        }
                    }]
                },
                responsive: false
            }
        });

Solution

  • It turns out that the javascript creating the chart wasn't getting a chance to create the chart and include it in the HTML before HiQPdf started converting it to the PDF.

    I needed a way for HiQPdf to wait for the chart to be rendered before starting the conversion.

    I found this demo in HiQ's documentation. It explains how you can manually trigger the conversion using javascript.

    In the C# code:

    HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
    htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Manual;
    

    (There are also 'Auto' and 'WaitTime' trigger modes)

    And then on the webpage to trigger the conversion using javascript:

    hiqPdfConverter.startConversion();
    

    Awesome! so now all I needed was a way to call the startConversion() function when I knew the chart had finished rendering. Chart.js offers a few options to customize the chart animation process found here.

    Among those options is an onComplete callback. So to pull it all together I added this to the Chart object:

    options: {
       animation: {
          onComplete: function() {
             hiqPdfConverter.startConversion();
          }
       },
       ...
    }
    

    Now the chart is fully rendered and part of the html that gets converted to the pdf via HiQPdf!