title: How to convert (convas chart) to either (Chart , or system.drawing.image , or stream , or []byte ) where I can use it in c# to generate pdf
body: <p><a href="https://i.stack.imgur.com/WAiCn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WAiCn.jpg" alt="this is the page "></a></p>
  
  <p>I have this chart which will print number of visitors per hours in specified year </p>
  
  <p>and this is the function that will take out the data for specified year from database and I will keep them in hidden field X-axis &amp; Y-axis in order to draw the bar chart with great resolution , and  user can interact with it </p>
  
  <pre><code> public bool barchart(string val)
          {
  
              bool exists = false;
  
  
              DataTable dt = new DataTable();
              //  string query = string.Format("select to_char(datetime_in,'HH24:MM') as hour,count(*)  from visits where   to_char(datetime_in,'YYYY')='" + val + "'  group by to_char(datetime_in,'HH24:MM') order by to_char(datetime_in,'HH24:MM')");
              string query = "";
              if (db.dbType == "mysql")
              {
  
                  query = string.Format("Select DATE_FORMAT(datetime_in, '%H')  as hours,count(*) as visits from visits where DATE_FORMAT(datetime_in, '%Y') ='" + val + "'  group by DATE_FORMAT(datetime_in, '%H') order by DATE_FORMAT(datetime_in, '%H')");
                  Debug.WriteLine(" Barchart query : " + query);
                  MySqlCommand cmd = new MySqlCommand(query);
                  String constr = mysqlConnectionString;
                  MySqlConnection con = new MySqlConnection(constr);
                  con.Open();
                  MySqlDataAdapter sda = new MySqlDataAdapter();
                  cmd.CommandType = CommandType.Text;
                  cmd.Connection = con;
                  sda.SelectCommand = cmd;
                  sda.Fill(dt); con.Close();
              }
              else
              {
  
                  query = string.Format("Select TO_CHAR(datetime_in,'HH24') as hour,count(*) from visits where to_char(datetime_in,'YYYY')='" + val + "'  group by TO_CHAR(datetime_in,'HH24') order by TO_CHAR(datetime_in,'HH24')");
                  Debug.WriteLine(" Barchart query : " + query);
                  OracleCommand cmd = new OracleCommand(query);
                  String constr = connectionString;
                  OracleConnection con = new OracleConnection(constr);
                  con.Open();
                  OracleDataAdapter sda = new OracleDataAdapter();
                  cmd.CommandType = CommandType.Text;
                  cmd.Connection = con;
                  sda.SelectCommand = cmd;
                  sda.Fill(dt); con.Close();
              }
  
  
  
  
              string yAxis = "";
              string xAxis = "";
              DataView vieww = new DataView(dt);
              foreach (DataRowView roww in vieww)
              {
                  exists = true;
  
                  xAxis += roww["hours"] + ",";
                  yAxis += roww["visits"] + ",";
  
  
              }
              hdn_Yaxis.Value = yAxis;
              hdn_Xaxis.Value = xAxis;
  
              return exists;
  
  
          }
  </code></pre>
  
  <p>after I take x-axis and y-axis in hidden field I will draw them in page using Canvas element </p>
  
  <pre><code>     &lt;canvas height='300' id='canvas_barchart' width='750'&gt;&lt;/canvas&gt;
       &lt;asp:HiddenField ID="hdn_Yaxis" runat="server" /&gt;
       &lt;asp:HiddenField ID="hdn_Xaxis" runat="server" /&gt;
  </code></pre>
  
  <p>and I will use this script to draw the bar chart with help of X-axis and Y-Axis hidden fields</p>
  
  <pre><code>     &lt;script src="Chart_js/prefixfree.min.js"&gt;&lt;/script&gt;
           &lt;script src='js/Chart.min.js'&gt;&lt;/script&gt;
  
  &lt;script language="javascript" &gt;
  
      var Bar_yAxis = document.getElementById('&lt;%=hdn_Yaxis.ClientID%&gt;').value;
      var Bar_xAxis = document.getElementById('&lt;%=hdn_Xaxis.ClientID%&gt;').value;
  
  
      //alert("Y = " + yAxis + " X = " + xAxis);
      Bar_yAxis = Bar_yAxis.substring(0, Bar_yAxis.length - 1);
      Bar_xAxis = Bar_xAxis.substring(0, Bar_xAxis.length - 1);
  
  
      var Bar_arrayx = Bar_xAxis.split(',');
  
  
  
      var Bar_arrayY = Bar_yAxis.split(',').map(function (item) {
          return parseInt(item, 10);
      });
  
  
     var ctx = document.getElementById("canvas_barchart");
  
   var myBarChart = new Chart(ctx,
  {
  
      type : 'bar',
  
     data: {
  
  labels: Bar_arrayx,
  datasets: [
      {
  
          fill: true,
          fillColor: "rgba(255, 153, 29,.8)",
          lineTension: 0.1,
          backgroundColor: "rgba(255, 153, 29,.8)",
  
          borderColor: "rgba(255, 153, 29,1)",
          borderCapStyle: 'butt',
          borderDash: [],
          borderDashOffset: 0,
          borderJoinStyle: 'miter',
  
  
          pointBorderColor: "rgba(255, 153, 29,1)",
          pointBackgroundColor: "#fff",
          pointBorderWidth: 1,
          pointHoverRadius: 5,
          pointHoverBackgroundColor: "rgba(255, 153, 29,1)",
          pointHoverBorderColor: "rgba(255, 153, 29,1)",
          pointHoverBorderWidth: 2,
          pointRadius: 1,
          pointHitRadius: 10,
  
  
          data: Bar_arrayY,
          spanGaps: false,
      } 
  ]
  } ,
  options : 
  { 
  
          scales: {
                     yAxes: [{
                      ticks: {
                                  beginAtZero: true
                              }
                              }]
                  },
          tooltips : {
  
              callbacks : { // HERE YOU CUSTOMIZE THE LABELS
                 title : function() {
                      return null; //'eVMS';
                  },
                  beforeLabel : function(tooltipItem, data) {
                      return null; //'Date' + ': ' + tooltipItem.xLabel;
                  },
                  label : function(tooltipItem, data) {
                      return   null;
                  },
                     afterLabel : function(tooltipItem, data) {
                     if( parseInt(tooltipItem.yLabel) == 1) return tooltipItem.yLabel + " hours";
                     else return tooltipItem.yLabel + " hours";
                  }
  
              }
  
     }
      }
  });
  
  
  &lt;/script&gt;
  </code></pre>
  
  <p>now I have to print the chart into pdf using this function :</p>
  
  <pre><code> using (MemoryStream stream1 = new MemoryStream())
              {
                  Paragraph p2 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.Color.BLACK, Element.ALIGN_LEFT, 1)));
                  pdfDoc.Add(p2);
  
                  pdfDoc.Add(new Phrase("\n"));
                  pdfDoc.Add(new Phrase("\n"));
  
                  PieChart.SaveImage(stream1, ChartImageFormat.Png);
                  iTextSharp.text.Image chartImage1 = iTextSharp.text.Image.GetInstance(stream1.GetBuffer());
                  chartImage1.ScalePercent(75f); 
                  chartImage1.SpacingBefore = 100f;
  
                  chartImage1.SpacingAfter = 110f;
                  pdfDoc.Add(chartImage1); pdfDoc.Add(new Phrase("\n"));// pdfDoc.Add(new Phrase("\n")); pdfDoc.Add(new Phrase("\n"));
                  //byte[] bytes1 = stream.ToArray();
  
              }
  </code></pre>
  
  <p>now I have 3 options to pint the chart into pdf :</p>
  
  <p>1) from front-end try to convert canvas element into C# Chart variable  and then  use SaveImage() to save the stream and then print it as pdf </p>
  
  <p>2) from front-end try to convert canvas element into C# system.drawing.image and then use iTextSharp.text.Image.GetInstance(system.drawing.image img) and I can print it in pdf </p>
  
  <p>3) from front-end try to convert canvas element into stream or []byte and then use iTextSharp.text.Image.GetInstance(stream.getbuffer()) and I can print it in pdf </p>
  
  <p>I don't want to use the barchart itself like <code>barchart.saveimage()</code> because the resolution in not at all good , I prefer to draw it in canvas for high resolution </p>
  
  <p>I don't want to print it directly from javascript because its only picture and we already built the whole report using iTextsharp in C#, and I don't want to write the report again , so  I want to print the chart image  only in some places and the rest of report is already built</p>
  
  <p>I know that i can save it in my server then from the server I can print it but, this is not good way for my project because we have multiple users and the images will be conflicted </p>
  
  <p>And if you have another ways please let me know</p>
  
  <p>please help </p>