Make WebBrowser control use linked stylesheet in DocumentText - c#

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

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...

You can use inline style as..
<html>
<head>
<style>
// all my style here
</style>
</head>
<body>
..
..
</body>
</html>

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>

Related

Load Local CSS File Into Xamarin IOS WebView?

I'm able to load a local HTML file into my WebView like this (this works fine):
var fileName = "Views/Default.html";
var localHtmlUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
var url = new NSUrl(localHtmlUrl, false);
var request = new NSUrlRequest(url);
WebView.LoadRequest(request);
I'd like to reference a CSS file (also local) in my HTML file:
<link href="Content/style.css" rel="stylesheet">
The CSS file does exist inside of a Content folder, the build action is set to Content for said file.
How can I reference/load the CSS file in question via my html file? Possible?
UPDATE: Had css and html in separate folders. Put them both in a Content folder then updated the hrefs which solved the issue while using LoadRequest.
Check this link
https://developer.xamarin.com/recipes/ios/content_controls/web_view/load_local_content/
Section Additional information
Html generated in code can also be displayed, which is useful for customizing the content. To display an Html string, use the LoadHtmlString method instead of LoadRequest. Passing the path to the Content directory helps the web view resolve relative Urls in the Html, such as links, images, CSS, etc.
// assumes you've placed all your files in a Content folder inside your app
string contentDirectoryPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Content/");
string html = "<html><a href='Home.html'>Click me</a></html>";
webView.LoadHtmlString(html, new NSUrl(contentDirectoryPath, true));

Background Image In Aspx Content Page Won't Change On Page Load

I have searched and searched for an answer to this across the web, yet I have not found a "clearly stated" answer as to why this is happening. And I have re-worked to no avail.
I have a Asp.Net site, with a "Master Page" and few "Content" pages
There is a CSS file which successfully assigns a "background-image" in the body - for all the pages:
body { background-image: url('../Images/TestImage1.jpg'); }
I have another image, say TestImage2.jpg, which sits in same Images folder in the solution, and I want to display this image on a specific "Content Page" when that page loads. Yet, it is not loading on the page, and background just turns white without any image at all - here's my code:
My MasterPage has the correct items for runat="server":
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
... and also...
<body runat="server">
<form style="height: 906px" runat="server">
Now, here's my code-behind for the content page I wish to have new image appear on Page_Load:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TechCall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder script = new StringBuilder();
script.Append("<script type=\"text/javascript\">");
script.Append("document.body.style.background = \"url('../Images/CPUBack2nd.jpg')\";");
script.Append("document.body.style.backgroundRepeat = 'no-repeat';");
script.Append("</script>");
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "changeBackground", script.ToString());
}
}
CPUBack2nd.jpg is the actual of name of the image in place of TestImage2.jpg, but as far as I can see, I am using the correct path for the image, as like the one in the CSS file which defines the default background image. Yet, when the page loads, no image at all appears for the background - just a white space, and original image appears on other pages correctly.
Can someone examine and tell me what I am missing here? Note: please don't suggest JQuery, as if it can be solved using Javascript, then I wish to stick with this usage, as I just want to learn to make it work with JS.
I'd suggest not using javascript at all. You should have a handy ContentPlaceHolder in the header section. Add the following in there to overide the default body style
<style type="text/style">
body { background-image: url('../Images/TestImage2.jpg'); }
</style>
As this will appear in the page after the head contents of the materpage it will overide the earlier CSS.
I would also consider using Root Releative paths particularly on master pages as it makes the releative location of the calling document and the called resource irrelevant. In which case change the above to:
<style type="text/style">
body { background-image: url('/Images/TestImage2.jpg'); }
</style>
Assuming that the Images directory resides at the root level of your document.
If you really want to persist with javascript. Check the path or use Root Relative. Remember that the path is relevant to the document calling the resorce. So just because a path works in a CSS file does not mean it will work in a page which sits at a diferent level of the website. Use a CSS debug tool Like FireBug for Firefox (a free download) or Developer Tools in Chrome (in built) to check if the image was at the expected location.
After much wrangling, moving some things around and isolating them in the CSS style sheet to clean up the Master page, where I had some stray CSS classes, AND of course building on the "hunch" provided by Jon P on possible root relative with Javascript, here's what did it:
Instead of using this:
script.Append("document.body.style.background = \"url('../Images/TestImage1.jpg')\";");
The answer was to use this:
script.Append("document.body.style.background = \"url('/MyProjectName/Images/TestImage2.jpg')\";");
So, I don't know why I had go all the around the world it seems to figure that out, but I guess that's how it is with programming... the difference ALWAYS lies in the LITTLE THINGS!
Thanks to all who contributed to getting me to think about what was going on here! Hence, the lesson is also THIS CAN BE DONE WITH JAVASCRIPT. :)

How to set width of the text in System.Windows.Forms.WebBrowser?

I am currently using the control System.Windows.Forms.WebBrowser to create an Wysiwyg editor in a windows application.
Basically what I need is that the text does not exceed the width of the control, ie I do not want to use a horizonal scrollbar.
Is it possible?
[UPDATE]
this is the code for the moment I am running:
Reconocimiento.Navigate("about:blank"); //this is my object System.Windows.Forms.WebBrowser
Reconocimiento.Document.OpenNew(false);
string html = "<html><head><style type=\"text/css\">body {width: 400px;}</style></head><body></body></html>";
Reconocimiento.Document.Write(html);
recon = (Reconocimiento.Document.DomDocument) as IHTMLDocument2;
recon.designMode = "On"; //What we just did was make our web browser editable!
You can make use of the css word-break property.
Create a file with the following contents and save it to say C:\default.html (or some application path)
<html>
<body style='word-break: break-all'>
<body>
</html>
In you code, instead of navigating to about:blank, call
Reconocimiento.Navigate(new Uri("file:///C:/default.html"));

How do I include the css file in a XMLtransformation?

I'm creating an html file based on xml and xsl with XslCompiledTransform in c#.net. This works perfectly.
But the xsl also has a css file included, and I'm wondering if there is any way to get this css styles included in the output html file, so it can be showed as a standalone file (so I don't have to copy the css file to wherever i want to see the file).
To define the style of each tag explicitly is not an option either unfortunately, and the file is of course really ugly without the css.
Any help would be very much appreciated! :)
In your output html add a style sheet link within the <head> tag.
<link rel="stylesheet" type="text/css" href="mystyle.aspx" />
Then add a page to your project called mystyle.aspx. In Page_Load of this file you do your xslt transformation to output only the css part. (And remove the css part of the transformation for the html pages).
protected void Page_Load(object sender, EventArgs e) {
Response.Clear();
Response.ContentType = "text/css";
string css = // Do your xslt transformation here
Response.Write( css );
Response.End();
}
If the CSS is the same for all pages, you might want to add some caching to the code above to save doing the transformation every time.
You might have to use some parameters to point to your xml/xslt, but you haven't provided any information in your question in this regard.

mixing html and C#

I have some html that is going to be in every page so i stuck it in a .cs file. This piece of html has a lot of quotes so i would prefer not to escape each of the (\"). It isnt hard to since i can use find/replace but i wanted to know. Is there a nice way to mix html and CS so i can easily generate the page?
Rather than having your HTML in C# code move it to resource file. Here's how (for Visual Studio 2008):
Right-click on the project, select "Add New Item..."
Select Resource File. Leave Resource.resx as file name. A prompt will appear - select yes to place file in App_GlobalResources folder.
Double-click Resource.resx. Add new string item MyHtml.
In your code, use Resources.Resource.MyHtml:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Resources.Resource.MyHtml);
}
See also: How to: Create Resource Files for ASP.NET Web Sites
For the specific case of double quote, there's not a much better way. Generally, you can use verbatim strings. They will handle line breaks and all escape characters except " which should be replaced with "":
Response.Write(#"<html>
<body>
<h1 style=""style1"">Hello world</h1>
</body>
</html>");
Why wouldn't you just stick that HTML into a user control and then just add that user control to all the pages that use that HTML?
You say same html on EVERY page. Have you considered using a master page with a content placeholder for your common content? You could combine this with the user control idea mentioned by King Avitus.
You can use the legacy include directives in asp.net
You can then have your block of HTML in a separate .html file.
<!-- #include PathType = FileName -->
You could do this with single quotes:
string MyHTML = #"<html>
<body>
<div class='foo'>...</div>
</body>
</html>";
or do double double quotes:
string MyHTML = #"<html>
<body>
<div class=""foo"">...</div>
</body>
</html>";
If you use #string literals you can escape double quotes with 2 double quotes. Slightly more readable (but not much)...
You can use the # to treat it literally, or you can take a look at the HtmlTextWriter class for a more programmatic approach.

Categories