Skip to content

How to add ChartJS code in Html2Pdf to view image #5759

Closed
@mittultechnobrave

Description

@mittultechnobrave

I am using Chart.js.

This is my php file and I have used javascript through which I am simply creating a chart and creating chart image after that.

<script>
    
            function done(){
      
                    var url=myLine.toBase64Image();
                    document.getElementById("url").src=url;
            }
    
    
        var MONTHS = [<?php echo '"' . implode('","', array_reverse($close_date_arr)) . '"' ?>];
            
        
        var config = {
          type: 'line',
          data: {
            
            labels: [<?php echo '"' . implode('","', array_reverse($close_date_arr)) . '"' ?>],
            
            datasets: [{
              label: "<?php echo $asx_code ?>",
              backgroundColor: '#ff6384', 
              borderColor:'#ff6384', 
              
              data: [<?php echo '"' . implode('","', array_reverse($close_price_arr)) . '"' ?>],
              fill: false,
            }]
          },
          options: {
               bezierCurve : false,
      animation: {
        onComplete: done
      },
            responsive: true,
            title: {
              display: true,
              text: ''
            },
            tooltips: {
              mode: 'index',
              intersect: false,
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: 'Month'
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: 'Value'
                }
              }]
            }
          }
        };
    
        
          var ctx = document.getElementById('canvascode').getContext('2d');
          window.myLine = new Chart(ctx, config);
        
    
        document.getElementById('randomizeData').addEventListener('click', function() {
          config.data.datasets.forEach(function(dataset) {
            dataset.data = dataset.data.map(function() {
              return randomScalingFactor();
            });
    
          });
    
          window.myLine.update();
        });
    
        var colorNames = Object.keys(window.chartColors);
        
      </script>

This is working absolutely fine but now I am stuck doing the same thing in html2pdf . I want to include couple of JS files and generate my chart using script tag and then put image into my PDF file.

This is what I have done without any luck.

<?php 
require __DIR__.'/vendor/autoload.php';

use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;


$html2pdf = new Html2Pdf();
$html2pdf->pdf->IncludeJS('Chart.bundle.js');
$html2pdf->pdf->IncludeJS('chart_utils.js');




$asx_code = 'CHK';

$url = 'https://www.asx.com.au/asx/1/share/' . $asx_code . '/prices?interval=daily&count=365';
  //  Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
$record_decode = json_decode($result);

$close_date_arr = array();
$close_price_arr = array();


    foreach ($record_decode->data as $current_data) {

        $close_price_arr[] = $current_data->close_price;

        $close_date_arr[] = date('F Y', strtotime($current_data->close_date));


    }

$str = '<canvas id="canvascode" style="display:none"></canvas>
<img id="url" style="width:400px; height:400px" />';

?>

<script>

        function done(){
  
                var url=myLine.toBase64Image();
                document.getElementById("url").src=url;
        }


    var MONTHS = [<?php echo '"' . implode('","', array_reverse($close_date_arr)) . '"' ?>];
        
    
    var config = {
      type: 'line',
      data: {
        
        labels: [<?php echo '"' . implode('","', array_reverse($close_date_arr)) . '"' ?>],
        
        datasets: [{
          label: "<?php echo $asx_code ?>",
          backgroundColor: '#ff6384', 
          borderColor:'#ff6384', 
          
          data: [<?php echo '"' . implode('","', array_reverse($close_price_arr)) . '"' ?>],
          fill: false,
        }]
      },
      options: {
           bezierCurve : false,
  animation: {
    onComplete: done
  },
        responsive: true,
        title: {
          display: true,
          text: ''
        },
        tooltips: {
          mode: 'index',
          intersect: false,
        },
        hover: {
          mode: 'nearest',
          intersect: true
        },
        scales: {
          xAxes: [{
            display: true,
            scaleLabel: {
              display: true,
              labelString: 'Month'
            }
          }],
          yAxes: [{
            display: true,
            scaleLabel: {
              display: true,
              labelString: 'Value'
            }
          }]
        }
      }
    };

    
      var ctx = document.getElementById('canvascode').getContext('2d');
      window.myLine = new Chart(ctx, config);
    

    document.getElementById('randomizeData').addEventListener('click', function() {
      config.data.datasets.forEach(function(dataset) {
        dataset.data = dataset.data.map(function() {
          return randomScalingFactor();
        });

      });

      window.myLine.update();
    });

    var colorNames = Object.keys(window.chartColors);
    
  </script>

 <?php  
$html2pdf->writeHTML($str);
$html2pdf->output();

?>

When I try to generate PDF file, I am getting an error saying,

Fatal error: Uncaught Spipu\Html2Pdf\Exception\HtmlParsingException: The html tag [canvas] is not known by Html2Pdf. You can create it and push it on the Html2Pdf GitHub project. in /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php:1435 Stack trace: #0 /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php(1043): Spipu\Html2Pdf\Html2Pdf->_executeAction(Object(Spipu\Html2Pdf\Parsing\Node)) #1 /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php(749): Spipu\Html2Pdf\Html2Pdf->_setNewPositionForNewLine(NULL) #2 /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php(1415): Spipu\Html2Pdf\Html2Pdf->_setNewPage() #3 /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php(1401): Spipu\Html2Pdf\Html2Pdf->_executeAction(Object(Spipu\Html2Pdf\Parsing\Node)) #4 /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php(595): Spipu\Html2Pdf\Html2Pdf->_makeHTMLcode() #5 /var/www/html/htmlpdf/test.php(138): Spipu\Html2Pdf\Html2Pdf->writeHTML('<canvas id="can...') #6 {main} thrown in /var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php on line 1435

Can someone guide me how can I generate my script here and put only my image into PDF.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions