2

I have the same question as this guy: "Compile" CSS into HTML as inline styles

Except that I use asp.net mvc razor or to be more correct RazorEngine: https://github.com/Antaris/RazorEngine

I compile .cshtml files into html files. While I do this or after this process is done I want that all .css files and their id`s, tags, classes and their properties/values are rendered as inline styles directly into the html tag as style attribute.

I need to use style attributes because the result html is a template to be shown in email clients like gmail/outlook/mobile etc...

How would you start with the process of converting the css stylesheet definitions into the appropriate style attributes?

Community
  • 1
  • 1
Pascal
  • 12,265
  • 25
  • 103
  • 195

1 Answers1

0

If you absolutely MUST replace the class attribute on your HTML attributes with in-line style attributes, you are looking at a non-trivial task. A good solution won't be a simple String.Replace or Regex.Replace. Here is how I would probably approach it:

  • Create a custom ActionFilter to read the HTML after your controller action executes (Capturing HTML output with a controller action filter)
  • Load the HTML using something like HTMLAgilityPack
  • Load your CSS class using a CSS parser
  • Find the class attribute on your HTML elements, remove it, replace it with a style attribute, and set the style attribute value to the value of the corresponding CSS class (read using the CSS parser mentioned above).
Community
  • 1
  • 1
DVK
  • 2,726
  • 1
  • 17
  • 20
  • Filter stuff I wont do, as I use RazorEngine that means I do not use a asp.net web project + iis server. Well as gmail does not support class attributes as they require an internal/external stylesheet, I have to do it that way when I want re-usable css definitions! Thanks for the htmlagilitypack and css parser links. I think thats the way to go. – Pascal May 06 '16 at 13:57
  • I found a solution which is already doing the HTMLAgilityPack + CSS parser and combine them together!!! see https://github.com/milkshakesoftware/PreMailer.Net – Pascal May 06 '16 at 19:54