xwrs
xwrs

Reputation: 1297

Rendering ASP.NET MVC ViewResult HTML as image without third party components

is there a way to render ViewResult or PartialViewResult as an image?

I have tried to get ViewResult as string and I got a string containing html as it should be, but I need to render that html to image. If it is possible - with styles and images.

I have an idea to get some browser output for this html on server and capture result to an image, but how it can be done in practice I don't know at this time. If you have any ideas, please, help.

Please do not suggest any third party components. Just tell if it is impossible to do by standart .NET classes.

Thank you

Upvotes: 3

Views: 5255

Answers (2)

Todd Smith
Todd Smith

Reputation: 17272

See How to render an image using the WebBrowser control

public class HtmlToBitmapConverter 
{ 
    private const int SleepTimeMiliseconds = 5000; 

    public Bitmap Render(string html, Size size) 
    { 
        var browser = CreateBrowser(size); 

        browser.Navigate("about:blank"); 
        browser.Document.Write(html); 

        return GetBitmapFromControl(browser, size); 
    } 

    public Bitmap Render(Uri uri, Size size) 
    { 
        var browser = CreateBrowser(size); 

        NavigateAndWaitForLoad(browser, uri, 0); 

        return GetBitmapFromControl(browser, size); 
    } 

    public void NavigateAndWaitForLoad(WebBrowser browser, Uri uri, int waitTime) 
    { 
        browser.Navigate(uri); 
        var count = 0; 

        while (browser.ReadyState != WebBrowserReadyState.Complete) 
        { 
            Thread.Sleep(SleepTimeMiliseconds); 

            Application.DoEvents(); 
            count++; 

            if (count > waitTime / SleepTimeMiliseconds) 
            { 
                break; 
            } 
        } 
    } 

    private WebBrowser CreateBrowser(Size size) 
    { 
        return 
            new WebBrowser 
            { 
                ScrollBarsEnabled = false, 
                ScriptErrorsSuppressed = true, 
                Size = size 
            }; 
    } 

    private Bitmap GetBitmapFromControl(WebBrowser browser, Size size) 
    { 
        var bitmap = new Bitmap(size.Width, size.Height); 

        NativeMethods.GetImage(browser.Document.DomDocument, bitmap, Color.White); 
        return bitmap; 
    } 
}

Then it's as easy as

var image = new HtmlToBitmapConverter()
                .Render(new Uri(urlTextBox.Text), pictureBox.Size);

Upvotes: 8

Kath
Kath

Reputation: 1854

Sorry for my previous suggestion. It was not correct, really. Now I understand what you want. But if you don't like the idea to use the third-party solutions the only way is to write your own parser and it's not easy task. Or you could try to use WebBrowser class and its method DrawToBitmap how it's described here http://englestone.blogspot.com/2009/06/generate-screenshot-previews-with-c.html

Upvotes: 0

Related Questions