mike
mike

Reputation: 31

Make WebBrowser control use linked stylesheet in DocumentText

I'm using a WebBrowser control and the text displays but it isn't using the linked css, it just appears as plain text. I'm populating it like so

webBrowser1.DocumentText = some_text;

In some_text is <link rel="stylesheet"href="PF.css"> along with the rest of the html

When I save some_text to a file and have the WebBrowser navigate to it it works fine webBrowser1.Navigate(@"C:\test.html"); and PF.css is in C:\

I've put PF.css in my project folder, where all the class files are.

How can I make the WebBrowser control use/display my linked css file? I don't want to save off my string to a file and then navigate to it.

thanks

Upvotes: 2

Views: 8991

Answers (3)

mike
mike

Reputation: 31

mshtml.HTMLDocument CurrentDocument = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
 mshtml.IHTMLStyleSheet styleSheet = CurrentDocument.createStyleSheet("", 0);
 StreamReader streamReader = new StreamReader(@"C:\PF.css");
 string text = streamReader.ReadToEnd();
 streamReader.Close();
 styleSheet.cssText = text;

kind of a krapy way to do it, but everything I read seems to point to the webbrowser control can't do css unless you Navigate to a file/url and it's included in there. BTW you have to add a ref to Microsoft.mshtml.

Maybe future versions of this control could handle linked stylesheets...

Upvotes: 1

user153498
user153498

Reputation:

If by put it in your project folder, do you mean your bin folder, or the folder with the .sln file in it? If it's the latter, you have to put it in the same folder as your executable (e.g. bin/Debug/PF.css, bin/Release/PF.css, etc).

Alternatively, you can embed it in the HTML using a <style type="text/css"><!-- CSS Here --></style>, and replace the comment with your CSS. If you don't want to hardcode it in where ever you get some_text from, you can dynamically replace it by loading PF.css:

using (StreamReader sr = new StreamReader("PF.css"))
{
    some_text = String.Format(some_text, sr.ReadToEnd());
}

That example assumes some_text contains the following:

<style type="text/css">
    {0}
</style>

Upvotes: 0

Akash Kava
Akash Kava

Reputation: 39916

You can use inline style as..

<html>
   <head>
       <style>
           // all my style here
       </style>
   </head>
<body>
..
..
</body>
</html>

Upvotes: 0

Related Questions