Live Razor Page Samples
Simple Chart Image
This sample shows how to create an image of a chart and stream the image directly to the browser.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Website.Pages.Support.Samples.RazorPages.Imaging
{
public partial class SimpleChartImageModel : PageModel
{
public FileResult OnGet()
{
// Create a new workbook and reference to Sheet1.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
// Load some sample data.
SpreadsheetGear.IRange dataRange = worksheet.Cells["A1:E5"];
dataRange.Value = new string[,] {
{ "", "North", "South", "East", "West" },
{ "Q1", "$7,923", "$5,954", "$5,522", "$3,701" },
{ "Q2", "$7,681", "$8,665", "$5,836", "$4,851" },
{ "Q3", "$4,739", "$2,107", "$3,298", "$1,211" },
{ "Q4", "$6,459", "$7,385", "$7,125", "$7,070" }, };
// Add a chart to the worksheet's shape collection.
// NOTE: Calculate coordinates in points (72 points per inch)
SpreadsheetGear.Shapes.IShape shape =
worksheet.Shapes.AddChart(0, 0, 4 * 72, 3 * 72);
SpreadsheetGear.Charts.IChart chart = shape.Chart;
// Set the chart's source data range, plotting series in columns.
chart.SetSourceData(dataRange, SpreadsheetGear.Charts.RowCol.Columns);
// Set the chart type.
chart.ChartType = SpreadsheetGear.Charts.ChartType.BarStacked;
// Set the distance between bars as a percentage of the bar width.
chart.ChartGroups[0].GapWidth = 50;
// Add a chart title and change the font size.
chart.HasTitle = true;
chart.ChartTitle.Text = "Combined Sales by Quarter";
chart.ChartTitle.Font.Size = 12;
// Create the image class from the chart shape.
SpreadsheetGear.Drawing.Image image = new SpreadsheetGear.Drawing.Image(shape);
// Get a new bitmap image of the represented chart.
using (System.Drawing.Bitmap bitmap = image.GetBitmap())
{
// Stream the chart image to the client in PNG format.
System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
bitmap.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png);
// Reset position to the beginning of the stream.
imageStream.Seek(0, System.IO.SeekOrigin.Begin);
// Stream the image to the client.
return File(imageStream, "image/png");
}
}
}
}