如何在Html2Pdf中添加ChartJS代码以查看图像

时间:2018-10-05 06:21:54

标签: php chart.js html2pdf

我正在使用Chart.js

这是我的php文件,我使用过javascript,通过它我可以简单地创建图表并在此之后创建图表图像。

<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>

这绝对正常,但是现在我在html2pdf中仍然做同样的事情。我想包含两个JS文件,并使用script标签生成图表,然后将图像放入PDF文件中。

这是我所做的一切,没有任何运气。

<?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();

?>

当我尝试生成PDF文件时,出现一条错误消息,

  

致命错误:未捕获Spipu \ Html2Pdf \ Exception \ HtmlParsingException:Html2Pdf未知html标签[canvas]。您可以创建它并将其推送到Html2Pdf GitHub项目上。在/var/www/html/htmlpdf/vendor/spipu/html2pdf/src/Html2Pdf.php:1435堆栈跟踪中:#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 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('

有人可以指导我如何在此处生成脚本并将仅将图像放入PDF。

2 个答案:

答案 0 :(得分:2)

,因为错误消息提示:您将在Github上转到Html2Pdf并在那里创建新的问题;为了将标记aws s3api put-object-acl --bucket [MY BUCKET] --key video_1.mp4 --grant-read添加到库的下一个版本中-或尝试使用canvas之外的其他方式来绘制图表;其他制图库也可以使用标签canvasdiv

好吧,请参见issue 372 ...作者无意添加标签svg

因此,您只能解决例如。 canvas,以创建画布的屏幕截图,然后将其用作静态图像资源,以将其呈现为PDF。

答案 1 :(得分:1)

我认为您的问题不是HTML2PDF,而是错误在于创建HTML2PDF的事件序列。我所了解的事件发生方式为:

1.  Loading PHP Code
2.  Loading according to PHP and creating Charts/Canvas through JS
3.  Pringing HTML2PDF Output through PHP Code

真正的问题是第3步没有等待第2步的完成。因此,您必须创建一个触发器/事件以在完成步骤2之后开始步骤3。通常,HTML2PDF是通过JS创建的,如下所示: