Search code examples
c#wpfwebbrowser-controlscreenshot

how to take snapshot from rendered HTML in WPF


Is there any way to take a snapshot of rendered html, i.e from webBrowser control and make an image object of the output?

is it possible by code besides using webbrowser, bcoz i think it needs to be visible on screen before the source is render as output.

i have html string which contains some picture text and table. of height of almost 700px, could be less or more on other scenario.

please guide me on this.


Solution

  • Use a RenderTargetBitmap instance. This allows you to render a control without displaying it on screen. Be careful to give it a width and height ;)

    http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap%28v=vs.110%29.aspx

    Sample from MSDN

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Globalization;
    
    namespace SDKSample
    {
        public partial class RenderTargetBitmapExample : Page
        {
            public RenderTargetBitmapExample()
            {
    
            Image myImage = new Image();
            FormattedText text = new FormattedText("ABC",
                    new CultureInfo("en-us"),
                    FlowDirection.LeftToRight,
                    new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
                    this.FontSize,
                    this.Foreground);
    
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            drawingContext.DrawText(text, new Point(2, 2));
            drawingContext.Close();
    
            RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);
            myImage.Source = bmp;
    
            // Add Image to the UI
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Children.Add(myImage);
            this.Content = myStackPanel;
            }
        }
    }