我有一个html + svg文件,当我使用下面的代码将其转换为图像时它的工作正常我,e)我得到了实际的图像。
private void NavigateLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
pictureBox.Image =
new HtmlToBitmapConverter()
.Render(new Uri(urlTextBox.Text), size);
}
Image - Using URI method converting - working fine
但是,当我将相同的html + Svg字符串内容转换为图像时,以下代码无效。
private void RenderHtmlToBitmapLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
pictureBox.Image =
new HtmlToBitmapConverter()
.Render(htmlTextBox.Text, size);
}
Image - Using Rendering method converting - Not working
类实现如下。
公共类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;
}
}
while (browser.Document.Body == null)
{
Application.DoEvents();
}
HideScrollBars(browser);
}
private void HideScrollBars(WebBrowser browser)
{
const string Hidden = "hidden";
var document = (IHTMLDocument2)browser.Document.DomDocument;
var style = (IHTMLStyle2)document.body.style;
style.overflowX = Hidden;
style.overflowY = Hidden;
}
private WebBrowser CreateBrowser(Size size)
{
var
newBrowser =
new WebBrowser
{
ScrollBarsEnabled = false,
ScriptErrorsSuppressed = true,
Size = size
};
newBrowser.BringToFront();
return newBrowser;
}
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;
}
}
如果第二个选项工作,那么我可以直接将html字符串转换为图像,而无需写入文件,然后使用第一种方法转换它。
帮助表示赞赏。