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!