Pavel Horyna
Pavel Horyna

Reputation: 431

Inject css styles from a css file into <style> tag

We are using external printing service which doesn't work with linked styles, so we are looking for a way to inject the content of a css file into tags in header, in a cshtml file. Is there a reasonable way how to do it?

EDIT: We have all our styles in scss, which compiles into css, which we want to inject into the tags.

Trying this rn, which doesn't work:

<head>
    <meta charset="utf-8" />
    <title>@Model.PrintEntityNameRk</title>
    <meta name="viewport" content="width=device-width" />
    <style>
        @@page {
            size: A4;
            margin: 4mm 4mm 10mm 4mm;
        }

        @File.ReadAllText("wwwroot/dist/css/app-print.css")

    </style>
...

Upvotes: 0

Views: 1311

Answers (2)

demoncrate
demoncrate

Reputation: 390

Check out this answer here: The Object Oriented way to do this would be to parse the html file and add the css to its head element.

The easier (hacky) way would be to get the text already present in the Head tag. Append your css to the text and write it back to the Head tag.

Edit: The methods written before deal with post processing of the html file. For pre-processing as according to your cshtml code sample would work like this.

Disclaimer: untested, uncompiled, text editor code.

<head>
    <meta charset="utf-8" />
    <title>@Model.PrintEntityNameRk</title>
    <meta name="viewport" content="width=device-width" />
    <style>
        @@page {
            size: A4;
            margin: 4mm 4mm 10mm 4mm;
        }

        @{
             var rawstyleText = File.ReadAllText("wwwroot/dist/css/app-print.css");
        }
        @rawstyleText
     </style>
...

Upvotes: 1

Zhi Lv
Zhi Lv

Reputation: 21363

You could create a custom Tag Helper, the in the custom helper's ProcessAsync method, read the CSS file content and add it in the output tag.

Please check the following sample:

  1. Create a custom Tag Helper named InlineStyleTagHelper.

    In the project(MVCAreasSample), add a TagHelpers folder. Create a InlineStyleTagHelper class with the following code:

     //required using Microsoft.AspNetCore.Hosting;
     //required using Microsoft.AspNetCore.Razor.TagHelpers;
     //required using Microsoft.Extensions.FileProviders;
     //required using System.IO;
     [HtmlTargetElement("inline-style")]
     public class InlineStyleTagHelper : TagHelper
     {
         public InlineStyleTagHelper(IWebHostEnvironment hostingEnvironment)
         {
             HostingEnvironment = hostingEnvironment;
         } 
         [HtmlAttributeName("href")]
         public string Href { get; set; } 
         private IWebHostEnvironment HostingEnvironment { get; } 
         public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
         {
             var path = Href;
             IFileProvider fileProvider = HostingEnvironment.WebRootFileProvider;
             IFileInfo file = fileProvider.GetFileInfo(path);
             if (file == null)
                 return;
             //read the css file content
             string fileContent = await ReadFileContent(file);
             if (fileContent == null)
             {
                 output.SuppressOutput();
                 return;
             } 
             // Generate the output
             output.TagName = "style"; // Change the name of the tag from inline-style to style
             output.Attributes.RemoveAll("href"); // href attribute is not needed anymore             
             output.Content.AppendHtml(fileContent); // add the css file content in the style tag.
         } 
         private static async Task<string> ReadFileContent(IFileInfo file)
         {
             using (var stream = file.CreateReadStream())
             using (var textReader = new StreamReader(stream))
             {
                 return await textReader.ReadToEndAsync();
             }
         }
     }
    
  2. Register the Custom Tag Helper in the _ViewImports.cshtml.

    Add the following code at the end of the _ViewImports.cshtml.

    @addTagHelper *, MVCAreasSample //Replace MVCAreasSample with the name of the assembly that contains the TagHelper
    
  3. Use the Custom Tag Helper in the View page:

     <inline-style href="/css/MyStyleSheet.css" ></inline-style>
    
     <div class="text-center test">
         <h1 class="display-4">Welcome</h1>
         <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
     </div>
    

    The MyStyleSheet.css content like this:

     body { 
     }
     .test{
         background-color:aqua;
     }
    

After running the website, using F12 developer tools to check the Elements, we can see the CSS styles, like this:

enter image description here

Upvotes: 4

Related Questions