How to print C# chart with more pages - c#

I have C# project already done but im having issue with printing it's charts when comes out with more pages of data points, i got the scroll bar work when start getting more pages so the user can review all data on all pages but i could not find how to make the print preview shows them or print them,
when click on print, it shows only the first page on the print preview and same thing when print it out.
her is the print code:
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = this.chart1.Printing.PrintDocument;
((Form)ppd).WindowState = FormWindowState.Maximized;
chart1.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Left = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Right = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Top = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Bottom = 0;
ppd.ShowDialog();
and here is the chart load code:
public void loadChart(string sqlvalue)//load chart method
{
chart1.ChartAreas[0].AxisY.Maximum = 55;
chart1.ChartAreas[0].AxisY.Minimum = 35;
chart1.ChartAreas[0].AxisY.Interval = 5;//control how many lines/Interval
chart1.ChartAreas[0].AxisY.ScrollBar.Enabled = true;
chart1.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.Minimum = 0;
// chart1.ChartAreas[0].AxisX.Maximum = 10;
chart1.ChartAreas[0].AxisX.Interval = 1;
//X AXES label angle
chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 60;
da = new SqlDataAdapter(sqlvalue, cn.connect());
da.Fill(dt);
this.chart1.DataSource = dt;
this.chart1.Series["left"].XValueMember = dt.Columns[3].ToString();//date data
this.chart1.Series["left"].YValueMembers = dt.Columns[1].ToString();//spindle 1 data
this.chart1.Series["Right"].YValueMembers = dt.Columns[2].ToString();//spindle 2 data
//label the series lines, Backcolor and forcolor
chart1.Series[0].LabelBackColor = Color.Red;
chart1.Series[0].LabelForeColor = Color.White;
//datapoint marker's color, bordercolor,style and size
chart1.Series[0].MarkerColor = Color.White;
chart1.Series[0].MarkerBorderColor = Color.Black;
chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
chart1.Series[0].MarkerSize = 8;
//datapoint marker's color, style and size
chart1.Series[1].MarkerColor = Color.White;
chart1.Series[1].MarkerBorderColor = Color.Black;
chart1.Series[1].MarkerStyle = MarkerStyle.Circle;
chart1.Series[1].MarkerSize = 8;
chart1.Series[1].LabelBackColor = Color.Blue;
chart1.Series[1].LabelForeColor = Color.White;
//Chart background lines color
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Silver;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Silver;
this.chart1.DataBind();
cn.disconnect();
// enable autoscroll
chart1.ChartAreas[0].CursorX.AutoScroll = true;//------------
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoom(0, 15);
chart1.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
// set scrollbar small change to the target size
chart1.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = 15;
Legend left = new Legend();
Legend LC = CustomCloneLegend(chart1, left);
chart1.Legends.Add(LC);
chart1.Padding = Padding.Empty;
ChartArea CA = chart1.ChartAreas[0];
CA.Position = new ElementPosition(4,6, 100, 90);
}
Thank you for your time and help, here is the chart code update:
private static Image MergeImages(List<Image> imageList)
{
var finalSize = new Size();
foreach (var image in imageList)
{
if (image.Width > finalSize.Width)
{
finalSize.Width = image.Width;
}
finalSize.Height += image.Height;
}
var outputImage = new Bitmap(finalSize.Width, finalSize.Height);
using (var gfx = Graphics.FromImage(outputImage))
{
var y = 0;
foreach (var image in imageList)
{
gfx.DrawImage(image, 0, y);
y += image.Height;
}
}
return outputImage;
}
The second method:
List<Image> ChartsToImages(List<Chart> charts)
{
var imageList = new List<Image>();
foreach (var c in charts)
{
using (var ms = new MemoryStream())
{
c.SaveImage(ms, ChartImageFormat.Png);
var bmp = System.Drawing.Bitmap.FromStream(ms);
imageList.Add(bmp);
}
}
return imageList;
}
and this code
var chartList = new List<Chart> { chart1 };
var imageList = ChartsToImages(chartList);
var finalImage = MergeImages(imageList);
finalImage.Save("D:\\Junk.png", ImageFormat.Png);
Im not sure is that what you mean by your first comment, but i found this code here under Converting chart to image questions. this code convert and saves the chart in the same amount of pages but i need to show them in the printpreviewcontrol and print them.

Below code refers to the as per page count starting point and ending point based printing. And Grid view value chars are row loop based counting the page.
private int numberOfItemsPerPage = 0;
private int numberOfItemsPrintedSoFar = 0;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int height = 480; //page height stating point
for (int l = numberOfItemsPrintedSoFar; l < dataGridView2.Rows.Count; l++)
{
numberOfItemsPerPage = numberOfItemsPerPage + 1;
if (numberOfItemsPerPage <= 25) // 25 is Page Line Item
{
numberOfItemsPrintedSoFar++;
if (numberOfItemsPrintedSoFar <= dataGridView2.Rows.Count)
{
height += dataGridView2.Rows[0].Height;
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[0].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(5, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[1].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(170, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[2].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(290, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[3].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(345, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
}
else
{
e.HasMorePages = false;
}
}
else
{
numberOfItemsPerPage = 0;
e.HasMorePages = true;
return;
}
}
numberOfItemsPerPage = 0;
numberOfItemsPrintedSoFar = 0;
}

Related

Object not shown on Canvas (WPF Application)

In this Application, i have a car class with a method called Spawn (which should draw the object on a Canvas which i defined in the XAML file). I call the Method in MainWindow, but when I run my program, there is no car being drawn onto the Canvas.
Here is the Spawn method:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Canvas.SetLeft(carBody, SpawnLocation.X);
Canvas.SetTop(carBody, SpawnLocation.Y);
Rectangle[] tires = new Rectangle[4];
Rectangle[] windows = new Rectangle[2];
Label lblBrand = new Label();
RotateTransform rotation = new RotateTransform();
// Reifen
tires[0] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[0], -9);
Canvas.SetTop(tires[0], 18);
tires[1] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[1], 61);
Canvas.SetTop(tires[1], 18);
tires[2] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[2], -9);
Canvas.SetTop(tires[2], 80);
tires[3] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[3], 61);
Canvas.SetTop(tires[3], 80);
// Fenster
windows[0] = new Rectangle() // Front
{
Fill = Brushes.White,
Width = 50,
Height = 40
};
Canvas.SetLeft(windows[0], 0);
Canvas.SetTop(windows[0], 0);
windows[1] = new Rectangle() // rear
{
Fill = Brushes.White,
Width = 50,
Height = 50
};
Canvas.SetLeft(windows[1], 0);
Canvas.SetTop(windows[1], 0);
// Label Automarke
lblBrand.Width = 40;
lblBrand.Height = 23;
lblBrand.Content = Brand;
// Add2Canvas
for (int i = 0; i < tires.Length; i++)
carBody.Children.Add(tires[i]);
for (int i = 0; i < windows.Length; i++)
carBody.Children.Add(windows[i]);
carBody.Children.Add(lblBrand);
if (Direction == "nord")
{
rotation.Angle = 0;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "süd")
{
rotation.Angle = 180;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "west")
{
rotation.Angle = 90;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "ost")
{
rotation.Angle = 270;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
cvs.Children.Add(carBody);
}
Calling the methodMainWindow:
Car car1;
public MainWindow()
{
InitializeComponent();
car1 = new Car("Audi", Colors.Red);
car1.Direction = "west";
car1.SpawnLocation = new Point(550, 340);
car1.Spawn(gameScreen);
}
Thanks in advance!
Fixed it! I initialized the argmument of my Spawn method, it now works after I deleted it.
My method looked like this first:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
I initialized my the Argument, but since i don't wanna create a new Canvas, i deleted these two first lines of my method.
public void Spawn(Canvas cvs)
{
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Now its working fine.

Print all data in the DataGrid in WPF

I am working on WPF application. I have data in the DataGrid which I have to print all the data present in it. I tried like this...
publicMainWindow()
{
InitializeComponent();
DataTabledt = newDataTable();
dt.Columns.Add("S.No");
dt.Columns.Add("Name");
dt.Columns.Add("Father's Name");
dt.Columns.Add("D-O-B");
dt.Columns.Add("Qualification");
dt.Columns.Add("Gender");
dt.Columns.Add("SSC %");
dt.Columns.Add("+2 %");
dt.Columns.Add("Graduation %");
dt.Columns.Add("Work Experience");
dt.Columns.Add("Company");
object[] rowValues = {"01","Gopi","Ravi","31","Degree","M", "88","85", "80","2 Years","Blah Blah"};
dt.Rows.Add(rowValues);
dt.AcceptChanges();
myGrid.DataContext = dt.DefaultView;
}
privatevoidPrint_Click(object sender, RoutedEventArgs e)
{
PrintDialogprintDlg = newPrintDialog();
if ((bool)printDlg.ShowDialog().GetValueOrDefault())
{
Sizepagesize = newSize(printDlg.PrintableAreaWidth,printDlg.PrintableAreaHeight);
myGrid.Measure(pagesize);
myGrid.Arrange(newRect(5, 5, pagesize.Width, pagesize.Height));
printDlg.PrintVisual(myGrid, "Personal Information");
}
}
when I click on print button it is printing only the data which we can see as below
But in my case it is not printing work experience and company columns. How can I Print all the fields. Please help me out
EDIT: I think FlowDocument is used, but suppose I have 50 rows I cannot use FlowDocument. How can I Print in this case.
I have done code recently. It is tested code.It will print every datagrid with all records.It is easy and simple code.You would add a class. If you want to decorate a datagrid then go to PrintDG class then decorate it according to your own requirement.
Follow these steps.
Step1: Add these references on top.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
public class PrintDG
{
public void printDG(DataGrid dataGrid, string title)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
FlowDocument fd = new FlowDocument();
Paragraph p = new Paragraph(new Run(title));
p.FontStyle = dataGrid.FontStyle;
p.FontFamily = dataGrid.FontFamily;
p.FontSize = 18;
fd.Blocks.Add(p);
Table table = new Table();
TableRowGroup tableRowGroup = new TableRowGroup();
TableRow r = new TableRow();
fd.PageWidth = printDialog.PrintableAreaWidth;
fd.PageHeight = printDialog.PrintableAreaHeight;
fd.BringIntoView();
fd.TextAlignment = TextAlignment.Center;
fd.ColumnWidth = 500;
table.CellSpacing = 0;
var headerList = dataGrid.Columns.Select(e => e.Header.ToString()).ToList();
List<dynamic> bindList = new List<dynamic>();
for (int j = 0; j < headerList.Count; j++)
{
r.Cells.Add(new TableCell(new Paragraph(new Run(headerList[j]))));
r.Cells[j].ColumnSpan = 4;
r.Cells[j].Padding = new Thickness(4);
r.Cells[j].BorderBrush = Brushes.Black;
r.Cells[j].FontWeight = FontWeights.Bold;
r.Cells[j].Background = Brushes.DarkGray;
r.Cells[j].Foreground = Brushes.White;
r.Cells[j].BorderThickness = new Thickness(1, 1, 1, 1);
var binding = (dataGrid.Columns[j] as DataGridBoundColumn).Binding as Binding;
bindList.Add(binding.Path.Path);
}
tableRowGroup.Rows.Add(r);
table.RowGroups.Add(tableRowGroup);
for (int i = 0; i < dataGrid.Items.Count; i++)
{
dynamic row;
if (dataGrid.ItemsSource.ToString().ToLower() == "system.data.linqdataview")
{ row = (DataRowView)dataGrid.Items.GetItemAt(i); }
else
{
row = (BalanceClient)dataGrid.Items.GetItemAt(i);
}
table.BorderBrush = Brushes.Gray;
table.BorderThickness = new Thickness(1, 1, 0, 0);
table.FontStyle = dataGrid.FontStyle;
table.FontFamily = dataGrid.FontFamily;
table.FontSize = 13;
tableRowGroup = new TableRowGroup();
r = new TableRow();
for (int j = 0; j < row.Row.ItemArray.Count(); j++)
{
if (dataGrid.ItemsSource.ToString().ToLower() == "system.data.linqdataview")
{
r.Cells.Add(new TableCell(new Paragraph(new Run(row.Row.ItemArray[j].ToString()))));
}
else
{
r.Cells.Add(new TableCell(new Paragraph(new Run(row.GetType().GetProperty(bindList[j]).GetValue(row, null)))));
}
r.Cells[j].ColumnSpan = 4;
r.Cells[j].Padding = new Thickness(4);
r.Cells[j].BorderBrush = Brushes.DarkGray;
r.Cells[j].BorderThickness = new Thickness(0, 0, 1, 1);
}
tableRowGroup.Rows.Add(r);
table.RowGroups.Add(tableRowGroup);
}
fd.Blocks.Add(table);
printDialog.PrintDocument(((IDocumentPaginatorSource)fd).DocumentPaginator, "");
}
}
}
Step2: Then go to print button click event and create object of PrintDG class then call printDG pass to It two parameters datagridname and title.
Like :
private void print_button_Click(object sender, RoutedEventArgs e)
{
PrintDG print = new PrintDG();
print.printDG(datagridName, "Title");
}
If any error occurs during execution tell me and I will solve It.This is running code only, you need copy and paste.
Edited:
I declared row as dynamic. The dynamic keyword decides at run time which type to instantiate, either DataTable or another.
I work with This :
// Author : Kadi Okba
public class WpfPrinting
{
public const double cm = 37;
public double Margin = 0.5 * cm;
public double PageWidth = 21 * cm;
public double PageHeight = 29 * cm;
public double RowHeight = 0.7 * cm;
public bool PageNumberVisibility = true;
public bool DateVisibility = true;
public double FontSize = 14;
public double HeaderFontSize = 14;
public bool IsBold = false;
public void PrintDataGrid(FrameworkElement header, DataGrid grid, FrameworkElement footer, PrintDialog printDialog)
{
if (header == null) { header = new FrameworkElement(); header.Width = 1; header.Height = 1; }
if (footer == null) { footer = new FrameworkElement(); footer.Width = 1; footer.Height = 1; }
if (grid == null) return;
Size pageSize = new Size(PageWidth, PageHeight);
FixedDocument fixedDoc = new FixedDocument();
fixedDoc.DocumentPaginator.PageSize = pageSize;
double GridActualWidth = grid.ActualWidth == 0 ? grid.Width : grid.ActualWidth;
double PageWidthWithMargin = pageSize.Width - Margin * 2;
double PageHeightWithMargin = pageSize.Height - Margin * 2;
// scale the header
double headerScale = (header?.Width ?? 0) / PageWidthWithMargin;
double headerWidth = PageWidthWithMargin;
double headerHeight = (header?.Height ?? 0) * headerScale;
header.Height = headerHeight;
header.Width = headerWidth;
// scale the footer
double footerScale = (footer?.Width ?? 0) / PageWidthWithMargin;
double footerWidth = PageWidthWithMargin;
double footerHeight = (footer?.Height ?? 0) * footerScale;
footer.Height = footerHeight;
footer.Width = footerWidth;
int pageNumber = 1;
string Now = DateTime.Now.ToShortDateString();
//add the header
FixedPage fixedPage = new FixedPage();
fixedPage.Background = Brushes.White;
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
FixedPage.SetTop(header, Margin);
FixedPage.SetLeft(header, Margin);
fixedPage.Children.Add(header);
// its like cursor for current page Height to start add grid rows
double CurrentPageHeight = headerHeight + 1 * cm;
int lastRowIndex = 0;
bool IsFooterAdded = false;
for (;;)
{
int AvaliableRowNumber;
var SpaceNeededForRestRows = (CurrentPageHeight + (grid.Items.Count - lastRowIndex) * RowHeight);
//To avoid printing the footer in a separate page
if (SpaceNeededForRestRows > (pageSize.Height - footerHeight - Margin) && (SpaceNeededForRestRows < (pageSize.Height - Margin)))
AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin - footerHeight) / RowHeight);
// calc the Avaliable Row acording to CurrentPageHeight
else AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin) / RowHeight);
// create new page except first page cause we created it prev
if (pageNumber > 1)
{
fixedPage = new FixedPage();
fixedPage.Background = Brushes.White;
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
}
// create new data grid with columns width and binding
DataGrid gridToAdd;
gridToAdd = GetDataGrid(grid, GridActualWidth, PageWidthWithMargin);
FixedPage.SetTop(gridToAdd, CurrentPageHeight); // top margin
FixedPage.SetLeft(gridToAdd, Margin); // left margin
// add the avaliable rows to the cuurent grid
for (int i = lastRowIndex; i < grid.Items.Count && i < AvaliableRowNumber + lastRowIndex; i++)
{
gridToAdd.Items.Add(grid.Items[i]);
}
lastRowIndex += gridToAdd.Items.Count + 1;
// add date
TextBlock dateText = new TextBlock();
if (DateVisibility) dateText.Visibility = Visibility.Visible;
else dateText.Visibility = Visibility.Hidden;
dateText.Text = Now;
// add page number
TextBlock PageNumberText = new TextBlock();
if (PageNumberVisibility) PageNumberText.Visibility = Visibility.Visible;
else PageNumberText.Visibility = Visibility.Hidden;
PageNumberText.Text = "Page : " + pageNumber;
FixedPage.SetTop(dateText, PageHeightWithMargin);
FixedPage.SetLeft(dateText, Margin);
FixedPage.SetTop(PageNumberText, PageHeightWithMargin);
FixedPage.SetLeft(PageNumberText, PageWidthWithMargin - PageNumberText.Text.Length * 10);
fixedPage.Children.Add(gridToAdd);
fixedPage.Children.Add(dateText);
fixedPage.Children.Add(PageNumberText);
// calc Current Page Height to know the rest Height of this page
CurrentPageHeight += gridToAdd.Items.Count * RowHeight;
// all grid rows added
if (lastRowIndex >= grid.Items.Count)
{
// if footer have space it will be added to the same page
if (footerHeight < (PageHeightWithMargin - CurrentPageHeight))
{
FixedPage.SetTop(footer, CurrentPageHeight + Margin);
FixedPage.SetLeft(footer, Margin);
fixedPage.Children.Add(footer);
IsFooterAdded = true;
}
}
fixedPage.Measure(pageSize);
fixedPage.Arrange(new Rect(new Point(), pageSize));
fixedPage.UpdateLayout();
PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
pageNumber++;
// go to start position : New page Top
CurrentPageHeight = Margin;
// this mean that lastRowIndex >= grid.Items.Count and the footer dont have enough space
if (lastRowIndex >= grid.Items.Count && !IsFooterAdded)
{
FixedPage ffixedPage = new FixedPage();
ffixedPage.Background = Brushes.White;
ffixedPage.Width = pageSize.Width;
ffixedPage.Height = pageSize.Height;
FixedPage.SetTop(footer, Margin);
FixedPage.SetLeft(footer, Margin);
TextBlock fdateText = new TextBlock();
if (DateVisibility) fdateText.Visibility = Visibility.Visible;
else fdateText.Visibility = Visibility.Hidden;
dateText.Text = Now;
TextBlock fPageNumberText = new TextBlock();
if (PageNumberVisibility) fPageNumberText.Visibility = Visibility.Visible;
else fPageNumberText.Visibility = Visibility.Hidden;
fPageNumberText.Text = "Page : " + pageNumber;
FixedPage.SetTop(fdateText, PageHeightWithMargin);
FixedPage.SetLeft(fdateText, Margin);
FixedPage.SetTop(fPageNumberText, PageHeightWithMargin);
FixedPage.SetLeft(fPageNumberText, PageWidthWithMargin - PageNumberText.ActualWidth);
ffixedPage.Children.Add(footer);
ffixedPage.Children.Add(fdateText);
ffixedPage.Children.Add(fPageNumberText);
ffixedPage.Measure(pageSize);
ffixedPage.Arrange(new Rect(new Point(), pageSize));
ffixedPage.UpdateLayout();
PageContent fpageContent = new PageContent();
((IAddChild)fpageContent).AddChild(ffixedPage);
fixedDoc.Pages.Add(fpageContent);
IsFooterAdded = true;
}
if (IsFooterAdded)
{
break;
}
}
PrintFixedDocument(fixedDoc, printDialog);
}
private DataGrid GetDataGrid(DataGrid grid, double GridActualWidth, double PageWidthWithMargin)
{
DataGrid printed = new DataGrid();
// styling the grid
Style rowStyle = new Style(typeof(DataGridRow));
rowStyle.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.White));
rowStyle.Setters.Add(new Setter(Control.FontSizeProperty, FontSize));
if (IsBold) rowStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.Bold));
rowStyle.Setters.Add(new Setter(Control.HeightProperty, RowHeight));
Style columnStyle = new Style(typeof(DataGridColumnHeader));
columnStyle.Setters.Add(new Setter(Control.FontSizeProperty, HeaderFontSize));
columnStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
columnStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0.5, 0, 1.5)));
columnStyle.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.White));
columnStyle.Setters.Add(new Setter(Control.BorderBrushProperty, Brushes.Black));
columnStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.SemiBold));
printed.RowStyle = rowStyle;
printed.VerticalGridLinesBrush = Brushes.Black;
printed.HorizontalGridLinesBrush = Brushes.Black;
printed.FontFamily = new FontFamily("Arial");
printed.RowBackground = Brushes.White;
printed.Background = Brushes.White;
printed.Foreground = Brushes.Black;
// get the columns of grid
foreach (var column in grid.Columns)
{
if (column.Visibility != Visibility.Visible) continue;
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.HeaderStyle = columnStyle;
textColumn.Header = column.Header;
textColumn.Width = column.ActualWidth / GridActualWidth * PageWidthWithMargin;
textColumn.Binding = ((DataGridTextColumn)column).Binding;
printed.Columns.Add(textColumn);
}
printed.BorderBrush = Brushes.Black;
return printed;
}
public void PrintFixedDocument(FixedDocument fixedDoc, PrintDialog printDialog)
{
XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);
writer.Write(fixedDoc, printDialog.PrintTicket);
}
}

ASP.NET Bar Chart labels

In my project, I have a bar chart with 12 bars. The chart displays the x axis labels every 2 bars. I want a label for every bar.
How can I do this ?
public ActionResult TekenGrafiek(ApplicationUser user, string naam)
{
Product p = user.Verlanglijst.Producten.First(pr=>pr.Artikelnaam == naam);
int totaal = p.AantalInCatalogus;
DateTime[] weken = new DateTime[12];
int[] aantal = new int[12];
DateTime nu = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
for (int j = 0; j < 11; j++)
{
weken[j] = nu;
aantal[j] = p.GeefAantalReserveerbaarInPeriode(nu, nu.AddDays(7));
nu = nu.AddDays(7);
}
Bitmap image = new Bitmap(300, 50);
Graphics g = Graphics.FromImage(image);
Chart c = new Chart();
ChartArea a = new ChartArea();
a.AxisX.MajorGrid.Enabled = false;
a.ShadowColor = Color.DeepSkyBlue;
a.BackColor = Color.AliceBlue;
c.Titles.Add("Aantal beschikbaar komende weken");
c.ChartAreas.Add(a);
c.Width = 1000;
c.Height = 250;
Series mySeries = new Series();
mySeries.Points.DataBindXY(weken, aantal);
mySeries.IsValueShownAsLabel = true;
c.Series.Add(mySeries);
MemoryStream imageStream = new MemoryStream();
c.SaveImage(imageStream, ChartImageFormat.Png);
c.TextAntiAliasingQuality = TextAntiAliasingQuality.SystemDefault;
Response.ContentType = "image/png";
imageStream.WriteTo(Response.OutputStream);
g.Dispose();
image.Dispose();
return null;
}
Code is written in C# ASP.NET MVC.This is the chart at this moment
A similar question has been asked before.
Try using
a.AxisX.Interval = 1;
I believe it would help.
Good luck.

Clicking on image always shows last image in full view Xamarin IOS

In tableview cell I am dynamically showing some messages and images,If i am having more images
showing in horizontal scroll. now what my task is Clicking on particular image need to show that image in full page view, i have done the code, but my problem is clicking on any image showing last image in full view.
Can anyone please help me.
if (contents.Count > 0)
{
_scrollView = new UIScrollView (){Tag = 1002};
//_image = new UIImageView (UIImage.FromBundle("placeholder.png"));
_scrollView.Frame = new RectangleF (0, rowHeight, 320, 300);
_scrollView.PagingEnabled = true;
_scrollView.Bounces = true;
_scrollView.DelaysContentTouches = true;
_scrollView.ShowsHorizontalScrollIndicator = true;
//_scrollView.ScrollRectToVisible (new RectangleF (320, 0, 320, 480), true);
ContentView.Add(_scrollView);
int x = 35;
bool setRowHeight = true;
int scrollwidth = 0;
foreach (var contentItem in contents)
{
if (contentItem.FilePath.Length != 0)
{
index++;
//_image.SetImage (new NSUrl (contentItem.FilePath), UIImage.FromBundle ("placeholder.png"));
//_image.Tag = 1001;
_image = new UIImageView(FromUrl(contentItem.FilePath)) { Tag = 1001 };
_imagePath = contentItem.FilePath;
_image.Frame = new RectangleF(x, 0, 250, _image.Image.CGImage.Height);
x = x + (Convert.ToInt32( Bounds.Width));
scrollwidth = scrollwidth + Convert.ToInt32( Bounds.Width);
_scrollView.ContentSize = new SizeF (scrollwidth,150);
_scrollView.Add (_image);
if (setRowHeight) {
rowHeight += _image.Image.CGImage.Height + 10;
setRowHeight = false;
}
// ================
var doubletap = new UITapGestureRecognizer();
doubletap.NumberOfTapsRequired = 1; // single tap
doubletap.AddTarget(this, new MonoTouch.ObjCRuntime.Selector("DoubleTapSelector"));
_image.AddGestureRecognizer(doubletap); // detect when the scrollView is tapped
_image.UserInteractionEnabled = true;
// =================
}
}
}
[MonoTouch.Foundation.Export("DoubleTapSelector")]
public void OnDoubleTap(UIGestureRecognizer sender)
{
FullImageViewControler fullImageViewController = new FullImageViewControler(_imagePath);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(fullImageViewController, true, null);
}

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

Categories

Resources