Pixelated text chart using Charting Library in ASP - c#

I want to create a chart with this Library, I have created one but the text is pixelated so the feel is very ugly.
I'm passing this charts to a PDF file with iText Sharp to create a report.
Here is the code:
private static byte[] ObtenerBarraDoble(IList<ValorBarraDTO> valores)
{
var newColor1 = Color.FromArgb(187, 189, 191);
var newColor2 = Color.FromArgb(0, 138, 209);
using (var graficoPie = new Chart { Height = 200, Width = 600, RenderType = RenderType.BinaryStreaming })
{
var chartAreaPie = new ChartArea();
chartAreaPie.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
chartAreaPie.AxisX.MajorGrid.LineColor = Color.White;
chartAreaPie.AxisY.MajorGrid.LineColor = Color.White;
chartAreaPie.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 2);
chartAreaPie.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 2);
graficoPie.ChartAreas.Add(chartAreaPie);
var serieNuevo = new Series("Cartera Actual")
{
ChartType = SeriesChartType.Column,
XValueMember = "label",
YValueMembers = "valor1",
Color = newColor1,
Legend = "Cartera Actual",
IsValueShownAsLabel = true,
};
graficoPie.Series.Add(serieNuevo);
var serie = new Series("Cartera Recomendada")
{
ChartType = SeriesChartType.Column,
XValueMember = "label",
YValueMembers = "valor2",
Color = newColor2,
Legend = "Cartera Propuesta",
IsValueShownAsLabel =true,
};
graficoPie.Series.Add(serie);
graficoPie.DataSource = valores;
return PdfHelper.ChartABinario(graficoPie);
}
}
Here is ChartABinario method:
internal static byte[] ChartABinario(Chart graficoPie)
{
using (var ms = new MemoryStream())
{
graficoPie.SaveImage(ms, ChartImageFormat.Png);
byte[] retorno = ms.ToArray();
return retorno;
}
}
This creates the chart and it's displaying it well, but the text is bad. What can I do to make that the text doesn't display pixelated letters?

Related

C# Saving Live Chart to PNG in WinForms

I am having difficulties in exporting LiveCharts PieChart to a .png file.
So far what I have done is trying to draw the control to a bitmap (DrawToBitmap), but it is just outputting a black image. I have discarded other alternatives such as screenshots because the chart is not created to be deployed in a custom form for visualization. Its main purpose is just graphic statistic exporting.
This is my main code:
LiveCharts.WinForms.PieChart chart = initializePieChart2DFolder(true);
Bitmap bmp = new Bitmap(chart.Width, chart.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
chart.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save("graphFolder.png", System.Drawing.Imaging.ImageFormat.Png);
This is the method I use to create the Pie chart:
private LiveCharts.WinForms.PieChart initializePieChart2DFolder()
{
LiveCharts.WinForms.PieChart chart = new LiveCharts.WinForms.PieChart();
chart.Anchor = System.Windows.Forms.AnchorStyles.None;
chart.Location = new System.Drawing.Point(17, 56);
chart.Name = "pieChart2DFolder";
chart.Size = new System.Drawing.Size(364, 250);
chart.TabIndex = 0;
chart.BackColorTransparent = false;
chart.BackColor = Color.White;
chart.ForeColor = Color.Black;
SeriesCollection chartData = new SeriesCollection();
foreach(var annot in numAnnotsPerLabel)
{
System.Windows.Media.Color newColor = System.Windows.Media.Color.FromArgb(color[annot.Key].A, color[annot.Key].R, color[annot.Key].G, color[annot.Key].B);
chartData.Add( new PieSeries { Title = annot.Key,
Values = new ChartValues<int> { annot.Value },
DataLabels = true,
Stroke = System.Windows.Media.Brushes.DimGray,
Foreground = System.Windows.Media.Brushes.Black,
FontSize = 9,
Fill = new
System.Windows.Media.SolidColorBrush(newColor)});
}
chart.Series = chartData;
DefaultLegend customLegend = new DefaultLegend();
customLegend.BulletSize = 15;
customLegend.Foreground = System.Windows.Media.Brushes.Black;
customLegend.Orientation = System.Windows.Controls.Orientation.Vertical;
customLegend.FontSize = 10;
chart.DefaultLegend = customLegend;
chart.LegendLocation = LegendLocation.Right;
var tooltip = chart.DataTooltip as DefaultTooltip;
tooltip.SelectionMode = LiveCharts.TooltipSelectionMode.OnlySender;
return chart;
}
Thank you very much in advance!

chart.DrawToBitmap blank

I have some code that uses System.Windows.Forms.DataVisualization.Charting; to generate a chart and create a bitmap image
private Bitmap GetTargetGradingImage(int sessionsTrained, int target, int height, int width)
{
const string TargetSeries = "TargetSeries";
var chart = new Chart
{
Height = height,
Width = width
};
chart.ChartAreas.Add(new ChartArea()
{
Name = "ChartArea1"
});
chart.Series.Clear();
chart.Series.Add(new Series()
{
Name = TargetSeries,
IsVisibleInLegend = true,
ChartType = SeriesChartType.Column,
Color = Color.Green
});
chart.Series[TargetSeries].ChartArea = chart.ChartAreas[0].Name;
string[] XPointMember = new string[2];
int[] YPointMember = new int[2];
XPointMember[0] = "Sessions";
YPointMember[0] = sessionsTrained;
XPointMember[1] = "Target";
YPointMember[1] = target;
chart.Series[TargetSeries].Points.DataBindXY(XPointMember, YPointMember);
chart.Invalidate();
var bitmap = new Bitmap(chart.Size.Width, chart.Size.Height, PixelFormat.Format32bppArgb);
chart.DrawToBitmap(bitmap, chart.Bounds);
//chart.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height));
return bitmap;
}
This works fine on my dev system but not when published to an Azure website. The images are blank.
The images are being used for inclusion in html emails.
Any ideas?
Cracked it.
Didn't need the chart.DrawToBitmap bit at all
This works
using (var chartImage = new MemoryStream())
{
chart.SaveImage(chartImage, ChartImageFormat.Png);
targetBuf = Convert.ToBase64String(chartImage.ToArray());
}
This gives me a Base64 encoded string that I can use in an img tag

Chart font style always bold when background is transparent

I have a basic asp.net chart writing into the response stream.
Changing BackColor to Color.Transparent and every text being bold automaticly. Searched many posts/forums about this issue but couldnt find any solution.
This my Chart builder Code.
public static void BuildChart(Chart chart, IEnumerable<MultiMeasureData> source, Measure[] measures,bool transparent)
{
var ca = chart.ChartAreas.FirstOrDefault();
if (ca == null)
chart.ChartAreas.Add(ca = new ChartArea());
//added for transparency support.
ca.BackImageTransparentColor = Color.White;
ca.BackColor = Color.Transparent;
Series s = new Series("Ölçümler");
s.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
chart.Series.Add(s);
var leg = new Legend("legend1");
leg.Docking = Docking.Top;
//added for transparenct support.
leg.BackColor = Color.Transparent;
leg.Font = new Font("Arial", 8, FontStyle.Regular);
chart.Legends.Add(leg);
chart.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Berry;
//Transparency.
chart.BackColor = transparent ? Color.Transparent : Color.White;
//chart.BackSecondaryColor = Color.FromArgb(187, 205, 237);
//chart.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.LeftRight;
if (source != null)
{
if (measures.Length > 0)
{
ca.AxisX.LabelStyle.Format = "dd.MM.yy";
ca.AxisX.MinorGrid.Enabled = true;
ca.AxisX.MinorGrid.Interval = 12;
ca.AxisX.MinorGrid.IntervalType = DateTimeIntervalType.Hours;
ca.AxisX.MinorGrid.LineColor = Color.LightGray;
ca.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.HorizontalCenter;
// ca.BackColor = Color.FromArgb(134, 218, 239);
ca.AxisY.LabelStyle.Format = "{0}" + measures.First().Type.Unit;
ca.AxisY.LabelStyle.ForeColor = Color.Black;
ca.AxisY.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
ca.AxisX.LabelStyle.ForeColor = Color.Black;
ca.AxisX.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
ca.AxisX.MajorGrid.LineColor = Color.Silver;
ca.AxisY.MajorGrid.LineColor = Color.Silver;
// var tm = (e - s).TotalMinutes / 10;
var data = source
.Select(a =>
{
var ret = new { Time = a.Time, Values = new double?[measures.Length] };
for (int i = 0; i < measures.Length; i++)
ret.Values[i] = a.Values[i].HasValue ? a.Values[i] / measures[i].Type.ValueScale:null;
return ret;
}
).OrderBy(a => a.Time);
var times = data.Select(a => a.Time).ToArray();
for (int i = 0; i < measures.Length; i++)
{
var serie = new Series(measures[i].Type.Name) { ChartType = SeriesChartType.Spline };
serie.XValueType = ChartValueType.DateTime;
serie.ShadowColor = Color.Gray;
serie.BorderWidth = 2;
serie.ShadowOffset = 1;
serie.Points.DataBindXY(times, new[] { data.Select(a => a.Values[i]).ToArray() });
serie.LegendText = measures[i].Type.Name;
serie.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
chart.Series.Add(serie);
}
}
}
}
this is mainly stream writer method using BuildChart method
public static void SaveChart(System.IO.Stream stream, System.Drawing.Imaging.ImageFormat format, int w, int h, IEnumerable<MultiMeasureData> source, Measure[] measures,bool transparent)
{
var c = new Chart() { Width = w, Height = h};
BuildChart(c, source, measures,transparent);
c.SaveImage(stream, format);
}
And here is both results.
Background.White (transparent parameter is false)
Background.Transparent (transparent parameter is true)
look at this answer :MS Chart Control: Formatting Axis Labels
This solved my problems
Regards
Nemanja

Radar chart selective label rotation in System.Web.UI.DataVisualization.Charting?

I am trying to reproduce a radar chart in ASP.NET MVC.
This is what I should have
This is what I actually have
So far, it works, the odd colors are just for development.
But the label rotation of the bottom 3 labels is quite bad, and I can't seem to find out how to rotate them properly. Anyone ?
Also, why is it setting markers in a 20 interval step, when I set 25 ?
And addtionally, just for fun, is it possible to rotate the y-axis thick markers by 22.5 degrees, as in the sample ?
Here my code:
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;
// http://stackoverflow.com/questions/6047961/c-sharp-chart-rotate-labels
public FileResult RadarSample()
{
int pixelWidth = 1000;
int pixelHeight = 1000;
// Populate series data
//string[] xValues = { "France", "Canada", "Germany", "USA", "Italy", "Spain", "Russia", "Sweden", "Japan" };
string[] xValues = { "Offene Aussenpolitik", "Liberale Wirtschaftspolitik", "Restriktive Finanzpolitik", "Law & Order", "Restriktive Migrationspolitik", "Ausgebauter Umweltschutz", "Ausgebauter Sozialstaat", "Liberale Gesellschaft" };
double[] yValues = { 80, 90, 45, 75, 37.5, 40, 28, 54 };
//double[] yValues = { 65.62, 75.54, 60.45, 34.73, 85.42, 55.9, 63.6, 55.1, 77.2 };
//double[] yValues2 = { 76.45, 23.78, 86.45, 30.76, 23.79, 35.67, 89.56, 67.45, 38.98 };
var Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
Chart1.BackColor = System.Drawing.Color.HotPink;
var area = new System.Web.UI.DataVisualization.Charting.ChartArea("ca1");
area.Area3DStyle.Enable3D = false;
area.AxisX.Interval = 1;
area.BackColor = System.Drawing.Color.Red;
//area.AxisY.Interval = 5;
area.AxisY.MajorTickMark.Enabled = false;
area.AxisY.MajorGrid.LineColor = Color.Gray;
area.AxisY.MajorGrid.Interval = 25;
area.AxisY.MinorTickMark.Enabled = false;
area.AxisY.MinorGrid.Interval = 5;
area.AxisY.MinorGrid.LineColor = Color.Yellow;
Chart1.ChartAreas.Add(area);
var series1 = new System.Web.UI.DataVisualization.Charting.Series();
var series2 = new System.Web.UI.DataVisualization.Charting.Series();
series1.Name = "Series1";
series2.Name = "Series2";
//series1.Color = System.Drawing.Color.Yellow;
series1.Color = System.Drawing.Color.FromArgb(100, 0, 0, 255);
//series1.SmartLabelStyle.Enabled = true;
//series1.LabelAngle = 90;
//Legend legend = new Legend();
////legend.Name = "mylegend";
//legend.Title = "Hello world";
//legend.BackColor = Color.Transparent;
//legend.BackColor = Color.Tomato;
//Chart1.Legends.Add(legend);
// series1.Legend = "mylegend";
series1.LegendText = "A";
series2.LegendText = "B";
// series1.Label = "kickme";
// series2.Label = "bar";
//series1.ChartArea = "ca1";
series1.ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Radar;
series2.ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Radar;
series1.ChartArea = "ca1";
series2.ChartArea = "ca1";
Chart1.Series.Add(series1);
//Chart1.Series.Add(series2);
Chart1.Series["Series1"].Points.DataBindXY(xValues, yValues);
//Chart1.Series["Series2"].Points.DataBindXY(xValues, yValues2);
string[] astrRadarStyleList = new string[] { "Area", "Line", "Marker" }; // Fill, Line, or point
string[] astrAreaDrawingStyleList = new string[] { "Circle", "Polygon" }; // Shape
string[] astrLabelStyleList = new string[] { "Circular", "Radial", "Horizontal" };
string strRadarStyle = astrRadarStyleList[0];
string strAreaDrawingStyle = astrAreaDrawingStyleList[0];
string strLabelStyle = astrLabelStyleList[0];
Chart1.Width = System.Web.UI.WebControls.Unit.Pixel(pixelWidth);
Chart1.Height = System.Web.UI.WebControls.Unit.Pixel(pixelHeight);
// Set radar chart style
Chart1.Series["Series1"]["RadarDrawingStyle"] = strRadarStyle; // RadarStyleList.SelectedItem.Text;
//Chart1.Series["Series2"]["RadarDrawingStyle"] = strRadarStyle; // RadarStyleList.SelectedItem.Text;
if (strRadarStyle == "Area")
{
Chart1.Series["Series1"].BorderColor = Color.FromArgb(100, 100, 100);
Chart1.Series["Series1"].BorderWidth = 1;
// Chart1.Series["Series2"].BorderColor = Color.FromArgb(100, 100, 100);
// Chart1.Series["Series2"].BorderWidth = 1;
}
else if (strRadarStyle == "Line")
{
Chart1.Series["Series1"].BorderColor = Color.Empty;
Chart1.Series["Series1"].BorderWidth = 2;
// Chart1.Series["Series2"].BorderColor = Color.Empty;
// Chart1.Series["Series2"].BorderWidth = 2;
}
else if (strRadarStyle == "Marker")
{
Chart1.Series["Series1"].BorderColor = Color.Empty;
// Chart1.Series["Series2"].BorderColor = Color.Empty;
}
// Set circular area drawing style
Chart1.Series["Series1"]["AreaDrawingStyle"] = strAreaDrawingStyle; // AreaDrawingStyleList.SelectedItem.Text;
//Chart1.Series["Series2"]["AreaDrawingStyle"] = strAreaDrawingStyle; // AreaDrawingStyleList.SelectedItem.Text;
// Set labels style
Chart1.Series["Series1"]["CircularLabelsStyle"] = strLabelStyle; // LabelStyleList.SelectedItem.Text;
//Chart1.Series["Series2"]["CircularLabelsStyle"] = strLabelStyle; //LabelStyleList.SelectedItem.Text;
return Chart2Image(Chart1);
}
public FileResult Chart2Image(System.Web.UI.DataVisualization.Charting.Chart chart)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
chart.SaveImage(ms, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Png);
ms.Seek(0, System.IO.SeekOrigin.Begin);
return File(ms.ToArray(), "image/png", "mychart.png");
} // End Using ms
}
Try this for text direction of labels:
Chart1.Series["Series1"]["CircularLabelsStyle"] = "Horizontal";

Issues regarding image and random row color for a table in openxml?

I'm using an HTML to OpenXML convertor, gridview HTML code is assigned to a stringbuilder. Using that we convert that HTML to OpenXML, but when it comes to word the following below issues are found.
I have to fill background of a row of a table with grainsboro color but only text background is filled and not cell completely.
I wanted to align the image of the header to the right.
This is an asp.net application done in C#
A***building image code plz tell me how to align the image to right***
d=DocumentFormat.OpenXml.Drawing;
int emuWidth = (int)(pixelWidth * EMU_PER_PIXEL);
int emuHeight = (int)(pixelHeight * EMU_PER_PIXEL);
Drawing drawing = new Drawing();
d.Wordprocessing.Inline inline = new d.Wordprocessing.Inline { DistanceFromTop = 130, DistanceFromBottom = 430, DistanceFromLeft = 260, DistanceFromRight = 330 };
d.Wordprocessing.Anchor anchor = new d.Wordprocessing.Anchor { DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 };
d.Wordprocessing.SimplePosition simplePos = new d.Wordprocessing.SimplePosition { X = 0, Y = 0 };
d.Wordprocessing.Extent extent = new d.Wordprocessing.Extent { Cx = emuWidth, Cy = emuHeight };
d.Wordprocessing.DocProperties docPr = new d.Wordprocessing.DocProperties { Id = 1, Name = imageName };
d.Wordprocessing.HorizontalPosition h = new d.Wordprocessing.HorizontalPosition(new d.Wordprocessing.HorizontalAlignment("right"));
d.Graphic graphic = new d.Graphic();
// We don’t have to hard code a URI anywhere else in the document but if we don’t do it here
// we end up with a corrupt document.
d.GraphicData graphicData = new d.GraphicData { Uri = GRAPHIC_DATA_URI };
d.Pictures.Picture pic = new d.Pictures.Picture();
d.Pictures.NonVisualPictureProperties nvPicPr = new d.Pictures.NonVisualPictureProperties();
d.Pictures.NonVisualDrawingProperties cNvPr = new d.Pictures.NonVisualDrawingProperties { Id = 2, Name = imageName };
d.Pictures.NonVisualPictureDrawingProperties cNvPicPr = new d.Pictures.NonVisualPictureDrawingProperties();
d.Pictures.BlipFill blipFill = new d.Pictures.BlipFill();
d.Blip blip = new d.Blip { Embed = imageRelationshipID };
d.Stretch stretch = new d.Stretch();
d.FillRectangle fillRect = new d.FillRectangle();
d.Pictures.ShapeProperties spPr = new d.Pictures.ShapeProperties();
d.Transform2D xfrm = new d.Transform2D();
d.Offset off = new d.Offset { X = 0, Y = 0 };
d.Extents ext = new d.Extents { Cx = emuWidth, Cy = emuHeight };
d.PresetGeometry prstGeom = new d.PresetGeometry { Preset = d.ShapeTypeValues.Rectangle };
d.AdjustValueList avLst = new d.AdjustValueList();
xfrm.Append(off);
xfrm.Append(ext);
prstGeom.Append(avLst);
stretch.Append(fillRect);
spPr.Append(xfrm);
spPr.Append(prstGeom);
blipFill.Append(blip);
blipFill.Append(stretch);
nvPicPr.Append(cNvPr);
nvPicPr.Append(cNvPicPr);
pic.Append(nvPicPr);
pic.Append(blipFill);
pic.Append(spPr);
graphicData.Append(pic);
graphic.Append(graphicData);
inline.Append(extent);
inline.Append(docPr);
inline.Append(graphic);
//anchor.Append(extent);
//anchor.Append(docPr);
//anchor.Append(h);
//anchor.Append(graphic);
drawing.Append(inline);
return drawing;
I think in OpenXML there is a property highlight text color. How do I get that in C# code?
Actually you don't set the alignment of drawing directly. You place it in paragraph for example and set its property alignment.
this is the code I'm using:
public void AddImageParagraph(Drawing element, JustificationValues alignment = JustificationValues.Left)
{
Paragraph paragraph = new Paragraph();
ParagraphProperties paragraphProperties = new ParagraphProperties();
Justification justification = new Justification()
{
Val = alignment
};
paragraphProperties.Append(justification);
Run run = new Run(element);
paragraph.Append(run);
paragraph.Append(paragraphProperties);
mBody.Append(paragraph);
}

Categories

Resources