Click here to Skip to main content
15,904,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to write a generic code snippet to export the contents of UserControl/Grid to a PNG image.
eg:
<Grid>
   <dockPanel>
     <Textblock>......<Textblock>
   <dockPanel>

<scrollViewer>
  <listView>
  .....
  </listview>
</scrollViewer>

<chart>....</chart>
......
<Grid>

I need to export above UI to PNG.

What I have tried:

public void ExportToPNG(FrameWorkElement element, Stream stream)
{
BitmapEncoder encoder = new PngBitmapEncoder();
	var bitmap = new RenderTargetBitmap(
				(int)element.RenderSize.Width,
				(int)element.RenderSize.Height,
				96,
				96,
				PixelFormats.Default);

Rect bounds = VisualTreeHelper.GetDescendantBounds(element);

			DrawingVisual drawingVisual = new DrawingVisual();
			using (DrawingContext context = drawingVisual.RenderOpen())
			{
				VisualBrush brush = new VisualBrush(element);
				Rect rect = new Rect(0, 0, bounds.Width, bounds.Height);

				context.DrawRectangle(Brushes.White, null, rect);
				context.DrawRectangle(brush, null, rect);
			}
bitmap.Render(drawingVisual);
encoder.Frames.Add(bitmap);
encoder.Save(stream);
}


The above code is working. But, it's just exporting the visible area(from the ScrollViewer). I need to export the whole content from the ScrollViewer.

Note: Some Views might not have ScrollViewer

Any advise or guidance would be greatly appreciated!

Thanks!
Posted
Updated 18-Feb-19 5:30am

1 solution

Showing the routine and not the "call" is useless.

From the sounds of it, you're passing the "scroll viewer", and not the actual "content" (of the scroll viewer) to the routine. It's the "visual" (contained in the viewer) that matters.
 
Share this answer
 
Comments
Manoj_Baddi 19-Feb-19 2:24am    
Yes, I'm not passing scrollviewer's content. I'm passing the whole grid to this function(I'm passing this as dependency property of type FrameWorkElement). I need to export all the contents of the Grid(Not just scrollviewer).

I'll try this idea; Check every time if the Element is of type scrollviewer and the pass "Content" of scrollviewer to VisualBrush.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900