0

I have an application that create chart by Google chart API. Now I want to send image of the chart to users by email or Telegram messenger. This is the code that display image chart in the browser and send this image to the an action of controller by AJAX. How can I run this html script on the server?

<html>
<head>
</head>
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load("current", {packages:['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {

      data2 = [['Time', 'Temp'],[1456099200,7.4],[1456102800,7.7],[1456106400,8.6],[1456110000,8.6],[1456113600,9.4]]

      var data = google.visualization.arrayToDataTable(
        data2
      );

      var options = {
        title: "Darestan Monitoring",
        legend: 'none',
        hAxis: {
          ticks: [{v: 1456099200, f: '1'},{v: 1456102800, f: '2'},{v: 1456106400, f: '3'},{v: 1456110000,f: '4'},{v: 1456113600, f: '5'}]
        },
        annotations: {
          style: 'line'
        }
      };

      var chart_div = document.getElementById('chart_div');
      var chart = new google.visualization.LineChart(chart_div);
      // Wait for the chart to finish drawing before calling the getImageURI() method.
      google.visualization.events.addListener(chart, 'ready', function () {
        var image_tag = '<img src="' + chart.getImageURI() + '">';
        chart_div.innerHTML = image_tag;
        console.log(chart_div.innerHTML);
        $.ajax({
          url: '/generate_chart/image_data',
          type: 'POST',
          data: {"image_data_tag": chart.getImageURI()},
          dataType: 'json',
          beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}
        });
      });
      chart.draw(data, options);
    }
  </script>

<div id='chart_div'></div>
</body>
</html>

1 Answer 1

1

wkhtml2image is exactly what you want.

We use a lot of PDFkit + wkhtml2pdf inside ruby applications.

Our setup:

ActiveJob + SuckerPunch + PDFKit. render_to_string helps to create the HTML file then passing it by PDFKit to wkhtml2pdf. Get the PDF, save it into a model with paperclip. Ensure to wait for javascript (option of wkhtml2image/pdf)

It's not so trivial, but works well,

Good luck,

Yacine.

Sign up to request clarification or add additional context in comments.

1 Comment

I have try Imgkit but it was not loaded javascript lib.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.