Search code examples
c#cssanglesharp

Retrieving Css Rules via AngleSharp


I'm trying to get css @page rules from an AngleSharp parsed html file. It's interesting because I can get the Rules property when I am debugging the stylesheet but not when I try accessing it when writing code. Am I missing a nuget package?

string input = "<style type=\"text/css\">body,p,div {font-family:Times; font-size:10pt; text-align:justify;}" + "@page :first { size: letter portrait; margin-top:1in; margin-right: .5in; margin-bottom: .5in; margin-left:1in;}" + "@page :last { size: letter portrait; margin-top:200in; margin-right: 50in; margin-bottom: 50in; margin-left:1in;" + "</style>";

var config = Configuration.Default.WithDefaultLoader().WithCss();
var ctx = BrowsingContext.New(config);

IDocument document = await ctx.OpenAsync(req => req.Content(input));

IStyleSheet sheet = document.GetStyleSheets().First();

I'm unable to access Rules property when writing the code


Solution

  • You should convert to an ICssStyleSheet. An IStyleSheet has no CSS rules. Only an ICssStyleSheet has.

    var sheet = document.GetStyleSheets().OfType<ICssStyleSheet>().First();
    

    Note that by specification there are multiple possible kinds of stylesheets. Practically, its only CSS.