问题描述
有没有办法来呈现的ViewResult或PartialViewResult作为图像?
is there a way to render ViewResult or PartialViewResult as an image?
我试图让的ViewResult为字符串,我得到了包含HTML,因为它应该是一个字符串,但我需要渲染HTML图像。如果可能的话 - 与风格和图像
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.
请不要提出任何第三方组件。只是判断它是不可能通过非标准.NET类的事情。
Please do not suggest any third party components. Just tell if it is impossible to do by standart .NET classes.
感谢您
推荐答案
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);
这篇关于渲染ASP.NET MVC的ViewResult的HTML因为没有第三方组件形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!