Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Print dynamically generated controls in WPF

Posted by Viral Sarvaiya on May 19, 2011

Hi

From my previous post https://viralsarvaiya.wordpress.com/2011/05/17/printing-in-wpf-with-fit-to-printing-page we see how to print page with wpf and with fit to printing page,

But what if we want to print dynamically generated control?

Because printdialog’s PrintVisual method print only visual controls.

Here I demonstrate that how to print controls that dynamically generated.


void PrintOnClick(object sender, RoutedEventArgs args)
{
PrintDialog dlg = new PrintDialog();
if ((bool)dlg.ShowDialog().GetValueOrDefault())
{
// Create Grid panel.
Grid grid = new Grid();
// Define 5 auto-sized rows and columns.
for (int i = 0; i < 5; i++)
{
ColumnDefinition coldef = new ColumnDefinition();
coldef.Width = GridLength.Auto;
grid.ColumnDefinitions.Add(coldef);

RowDefinition rowdef = new RowDefinition();
rowdef.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowdef);
}

// Give the Grid a gradient brush.
grid.Background = new LinearGradientBrush(Colors.Black, Colors.White, new Point(0, 0), new Point(1, 1));
// Every program needs some randomness.
Random rand = new Random();

// Fill the Grid with 25 buttons.
for (int i = 0; i < 25; i++)
{
Button btn = new Button();
btn.FontSize = 12 + rand.Next(8);
btn.Content = "Button No. " + (i + 1);
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = VerticalAlignment.Center;
btn.Margin = new Thickness(6);
grid.Children.Add(btn);
Grid.SetRow(btn, i % 5);
Grid.SetColumn(btn, i / 5);
}

// Size the Grid.
grid.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

Size sizeGrid = grid.DesiredSize;

// Determine point for centering Grid on page.
Point ptGrid =  new Point((dlg.PrintableAreaWidth - sizeGrid.Width) / 2, (dlg.PrintableAreaHeight - sizeGrid.Height) / 2);

// Layout pass.
grid.Arrange(new Rect(ptGrid, sizeGrid));
// Now print it.
dlg.PrintVisual(grid, Title);
}
}

thanks and enjoy coding…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: