Search code examples
c#htmlimagewebkithtmltextwriter

HTML img tag does not render source image in WebKit.NET browser in C#


I'm trying to set my WebKitBrowser DocumentText to an HTML string containing a local SVG file path as image source. Actually I want to show the SVG file in a web browser. Here is my code:

        string SVGPath = "file:///D:/MySVGFiles 1/SVGSample01.svg";

        StringWriter stringWriter = new StringWriter();

        using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src, SVGPath);
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "50%");
            writer.AddAttribute(HtmlTextWriterAttribute.Height, "50%");

            writer.RenderBeginTag(HtmlTextWriterTag.Img); 
            writer.RenderEndTag(); 

        }

        string content = stringWriter.ToString();

        this.webKitBrowser1.DocumentText = content;

When I run the code, the browser only shows the image canvas, and does not render the SVG file. I have tried this with a JPG image too, and got the same result.

Could anyone please tell what is wrong with this code??


Solution

  • I finally found out what is wrong. DocumentText property of WebKitBrowser is a string, and in its set method, HTML text is passed to loadHTMLString method.

    webView.mainFrame().loadHTMLString(value, null);
    

    DocumentText property is used when no URL is specified. But here I wanted to load an image from a specified address. So in case of using tags like setting DocumentText property would not be valid. I had to call loadHTMLString, and when an image is gonna be added to HTML string using its address, URL must be the directory of the image file. According to what I have found in https://groups.google.com/forum/#!topic/uni_webview/idiRRNIRnCU, I changed the code and problem is solved! Here is the code that works:

     string fileName = "SVGSample01.svg";
     string URL = "file:///D:/MySVGFiles 1/";
    
     StringWriter stringWriter = new StringWriter();
    
        using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src, fileName);
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "50%");
            writer.AddAttribute(HtmlTextWriterAttribute.Height, "50%");
    
            writer.RenderBeginTag(HtmlTextWriterTag.Img); 
            writer.RenderEndTag(); 
    
        }
    
        string content = stringWriter.ToString();
    
     (this.webKitBrowser1.GetWebView() as IWebView).mainFrame().loadHTMLString(content,URL);
    

    Just make sure the URL string contains "file:///" and the last "/".