I'm trying to render a html code to export it to an image and then use that image to put it in a pdf document. I'm doing all in an asp.net/C# web application. The problem I'm having is that when I do that more than one time it give me this error:
You are attempting to re-initialize the WebCore. The WebCore must only be initialized once per process and must be shut down only when the process exits.
This is my code:
WebCore.Initialize(new WebConfig(), false);
using (WebView webView = WebCore.CreateWebView((pdfWidth - 80).ToString().ToInt() + 20, (pdfHeight / 2).ToString().ToInt() + 20))
{
webView.LoadHTML(html);
while (webView.IsLoading || !webView.IsDocumentReady)
WebCore.Update();
Thread.Sleep(1100);
WebCore.Update();
string fileName = Server.MapPath("result." + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Millisecond.ToString() + ".png");
BitmapSurface surface = (BitmapSurface)webView.Surface;
surface.SaveToPNG(fileName, true);
WebCore.Shutdown();
}
I figure that I can't initialize the WebCore every time the web page render, so I put it in the Global.asax. After doing this, when I'm debugging, another error came up:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The current thread is not currently running code or the call stack could not be obtained.
Any ideas how can I do this?
Thanks
Short answer: yes, you can.
BUT according to the
WebCore
documentation:Also look at the
Exceptions
section ofWebCore.Update()
method description:Thus considering that every request in web application is generally processed in different thread,
AccessViolationException
is a documented feature.Therefore your task here is to guarantee that all Awesomium calls will be processed in a special dedicated thread. The thread should live on application level and its access has to be shared between requests. Technically, you need to write a kind of Message Loop or Synchronization Context where you will be able to push your
delegate
,Action
orFunc
with Awesomium code to provide its execution only in this thread.probably you need to call the webview.invoke or webview.begininvoke and you are going to need to create a delegate to access the webview that was created before the webcore.initialize in another thread, I would use a singleton pattern to use the same webview instance.