Hi rani,
Refer below sample.
Namespaces
using System.Data;
using System.IO;
Controller
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("BirthDate", typeof(DateTime))
});
dt.Rows.Add(1, "Nancy Davolio", "1948-12-08");
dt.Rows.Add(2, "Andrew Fuller", "1952-02-19");
dt.Rows.Add(3, "Janet Leverling", "1963-08-30");
dt.Rows.Add(4, "Margaret Peacock", "1937-09-19");
DataTable dtChart = new DataTable();
dtChart.Columns.AddRange(new DataColumn[]
{
new DataColumn("Product", typeof(string)),
new DataColumn("Total", typeof(int))
});
dtChart.Rows.Add("Chair", 56);
dtChart.Rows.Add("Table", 69);
dtChart.Rows.Add("Stool", 5);
ViewBag.Product = string.Join(",", dtChart.AsEnumerable().Select(r => r.Field<string>("Product")).ToArray());
ViewBag.Total = string.Join(",", dtChart.AsEnumerable().Select(r => r.Field<int>("Total")).ToArray());
return View(dt);
}
public void Image()
{
byte[] bytesImage = Convert.FromBase64String(Request.Form["base64data"].ToString());
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
System.IO.File.WriteAllBytes(path + "\\Chart.png", bytesImage);
}
public virtual ActionResult Download()
{
byte[] data = System.IO.File.ReadAllBytes(Path.Combine(this.Environment.WebRootPath, "Uploads/Chart.png"));
return File(data, "image/png", "Chart.png");
}
}
View
@model System.Data.DataTable
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/datetime/1.0.2/js/dataTables.dateTime.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.0.2/css/dataTables.dateTime.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script type="text/javascript">
$.fn.dataTable.render.moment = function (from, to, locale) {
// Argument shifting
if (arguments.length === 1) {
locale = 'en';
to = from;
from = 'DD-MM-YYYY';
}
else if (arguments.length === 2) {
locale = 'en';
}
return function (d, type, row) {
if (!d) {
return type === 'sort' || type === 'type' ? 0 : d;
}
var m = window.moment(d, from, locale, false);
return m.format(type === 'sort' || type === 'type' ? 'x' : to);
};
};
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function PopulateChart() {
var labels = '@ViewBag.Product';
var datas = '@ViewBag.Total';
var labelsArray = new Array();
var dataArray = new Array();
var colorArray = new Array();
for (var i = 0; i < labels.split(',').length; i++) {
labelsArray.push(labels.split(',')[i]);
dataArray.push(datas.split(',')[i]);
colorArray.push(getRandomColor());
}
new Chart(document.getElementById("chart").getContext('2d'), {
type: 'pie',
data: {
labels: labelsArray,
datasets: [{
backgroundColor: colorArray,
data: dataArray
}]
},
options: {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius) / 2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle) / 2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3) {
ctx.fillStyle = '#444';
}
var percent = String(Math.round(dataset.data[i] / total * 100)) + "%";
if (dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
ctx.fillText(percent, model.x + x, model.y + y + 30);
}
}
});
}
}
}
});
};
$(function () {
$("#myTable").dataTable({
bLengthChange: true,
lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
bFilter: true,
bSort: true,
bPaginate: true,
columns: [
{ data: 'Id' },
{ data: 'Name' },
{ data: 'BirthDate', render: $.fn.dataTable.render.moment('MM/DD/YYYY') }
],
});
PopulateChart();
$('.download').click(function () {
var imgData = $('#chart')[0].toDataURL("image/png", 1.0);
$('input[name=hfHTML]').val($('#myTable')[0].outerHTML);
$('input[name=hfChartData]').val(imgData);
});
$('#btnImage').click(function () {
var imgData = $('#chart')[0].toDataURL("image/png", 1.0);
$('input[name=hfHTML]').val($('#myTable')[0].outerHTML);
$('input[name=hfChartData]').val(imgData);
$('#dvImage').append($('#myTable')[0].outerHTML).append('<img height="300" width="400" src="' + imgData + '"/>');
$('#dvImage').show();
html2canvas($('#dvImage')[0], {
onrendered: function (canvas) {
var base64 = canvas.toDataURL("image/png").replace('data:image/png;base64,', '');
$.ajax({
type: "POST",
url: '/Home/Image',
dataType: 'text',
data: { base64data: base64 },
success: function (result) {
window.location = '/Home/Download';
$('#dvImage').hide();
}
});
}
});
});
});
</script>
</head>
<body>
<form asp-controller="Home" method="post">
<input type="hidden" name="hfHTML" value="" />
<input type="hidden" name="hfChartData" value="" />
<input type="hidden" name="hfTableImage" value="" />
<button id="btnImage" type="button">Image</button>
</form>
<hr />
<section class="content">
<div class="container-fluid">
<table class="table table-bordered table-responsive-lg table-hover" width="100%" id="myTable">
<thead class="thead-dark text-center">
<tr>
<th>Id</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody class="text-center">
@for (int i = 0; i < Model.Rows.Count; i++)
{
<tr>
<td>@Model.Rows[i]["Id"]</td>
<td>@Model.Rows[i]["Name"]</td>
<td>
@Convert.ToDateTime(Model.Rows[i]["BirthDate"]).ToString("dd/MM/yyyy")
</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<div class="box-body">
<div class="chart-container">
<canvas id="chart" style="width:50%; height:50%"></canvas>
</div>
</div>
<div id="dvImage" style="display:none;"></div>
</body>
</html>