Ra3IDeN Ra3IDeN - 2 months ago 13
C# Question

How to Apply css to webbrowser.documentText and print the html with the applied css?

I have a asp.net mvc web app that has a controller which has an action that returns html to a windows forms client.

The html that is returned gets printed.
This works perfectly and the html looks like the following:

enter image description here

NOTE that the html is always diffirent.

I designed the html with the help of bootstrap and some other custom css (including inline styles).

As shown above there are stylsheets being linked in to the html.
I haven't been able to figure out how to apply this css to the webBrowser.DocumentText.

With the help of google I found that I have to find the file and link it from there and here is my attempt:

private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
var document = ((WebBrowser) sender);
string content = document.DocumentText;

char separator = Path.DirectorySeparatorChar;
string startupPath = AppDomain.CurrentDomain.BaseDirectory;
string[] pathItems = startupPath.Split(separator);
string projectPath = string.Join(separator.ToString(),
pathItems.Take(pathItems.Length - 4));

string file = Path.Combine(projectPath, "\\IautmationWeb\\Content\\bootstrapSmall.css");

content = content.Replace("<link href='/Content/bootstrapSmall.css' rel=stylesheet'/>", "<link href='" + projectPath + file + "'rel='stylesheet'/>");

document.DocumentText = content;

// add css ... how?
// print...implemented

for (int i = 0; i < copies; i++)


This doesn't work. What am I doing wrong?


after some info from @Peter B I tried:

content = content.Replace("href='/Content/bootstrapSmall.css'", "href='" + file + "'");

document.DocumentText = content;

But the replace method is still not doing what I want it to do:

enter image description here


Thanks to @Peter B

I managed to navigate to the files.

string file = Path.Combine(projectPath, "\\IautmationWeb\\Content\\bootstrapSmall.css");
string fileTwo = Path.Combine(projectPath, "\\IautmationWeb\\Content\\Automation.css");
string fileThree = Path.Combine(projectPath, "\\IautmationWeb\\Content\\octicons.css");

content = content.Replace("href=\"/Content/bootstrapSmall.css\"", "href='" + projectPath + file + "'");

content = content.Replace("href=\"/Content/Automation.css\"", "href='" + projectPath + fileTwo + "'");

content = content.Replace("href=\"/Content/octicons.css\"", "href='" + projectPath + fileThree + "'");

document.DocumentText = content;

how the html looks now:
enter image description here


You seem to get the quotes wrong, a ' is not the same as a ".

Try this:

content = content.Replace("href=\"/Content/bootstrapSmall.css\"", "href='" + file + "'");

For the 2nd parameter it doesn't really matter which quotes you use, but for the 1st parameter it does.