How to add external CSS to HTML 'style'


Tags: java,html,css,jsoup

Problem :

How can I convert an external CSS style sheet into the 'style' section of my HTML using Java?

I want to be able to have my external CSS exist in the 'style' section so that I can parse it to inline styles rather than external and the easiest way I have seen to do this is to have the CSS directly in the HTML rather than linked.

I would like to change this in my HTML:

<link rel="stylesheet" href="smartdoc.css" /> 

To this (Ideally by passing the CSS file as an argument for a method):

<style>
    Content from external CSS.
</style>

So that I can apply JSoup to convert it to inline style using something like this:

public static String inlineCss(String html) {
final String style = "style";
Document doc = Jsoup.parse(html);
Elements els = doc.select(style);// to get all the style elements
for (Element e : els) {
  String styleRules = e.getAllElements().get(0).data().replaceAll("\n", "").trim();
  String delims = "{}";
  StringTokenizer st = new StringTokenizer(styleRules, delims);
  while (st.countTokens() > 1) {
    String selector = st.nextToken(), properties = st.nextToken();
    if (!selector.contains(":")) { // skip a:hover rules, etc.
      Elements selectedElements = doc.select(selector);
      for (Element selElem : selectedElements) {
        String oldProperties = selElem.attr(style);
        selElem.attr(style,
            oldProperties.length() > 0 ? concatenateProperties(
                oldProperties, properties) : properties);
      }
    }
  }
  e.remove();
}
return doc.toString();
}

private static String concatenateProperties(String oldProp, @NotNull String newProp) {
oldProp = oldProp.trim();
if (!oldProp.endsWith(";"))
  oldProp += ";";
return oldProp + newProp.replaceAll("\\s{2,}", " ");
}

Any suggestions for this?



Solution :

I assume that all your files are on a local hard drive encoded in UTF-8.

dummy.html

<link rel="stylesheet" href="smartdoc.css" />

smartdoc.css

a {
  background-color: red;
}

p {
  background-color: green;
}

SAMPLE CODE

To replace the link node with the CSS file content, do the following:

// Load HTML file
String charsetName = "UTF-8";
Document doc = Jsoup.parse(new File("dummy.html"), charsetName);
System.out.println("BEFORE:\n" + doc.outerHtml());

// Replace each link nodes with its respective CSS file content
for (Element link : doc.select("link[rel=stylesheet]")) {
    String cssFilename = link.attr("href");

    Element style = new Element(Tag.valueOf("style"), "");
    style.appendText("/* " + cssFilename + " */");
    style.appendText(loadCssFileContent(cssFilename, charsetName));

    link.replaceWith(style);
}

System.out.println("\nAFTER:\n" + doc.outerHtml());

private static String loadCssFileContent(String path, String charsetName) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, charsetName);
}

OUTPUT

BEFORE:
<html>
 <head>
  <link rel="stylesheet" href="smartdoc.css">
 </head>
 <body></body>
</html>

AFTER:
<html>
 <head>
  <style>/* smartdoc.css */a { background-color: red; } p { background-color: green; }</style>
 </head>
 <body></body>
</html>

    CSS Howto..

    CSS: how to add a style to everything, unless it is defined

    How to get 'div' shaped as a flag with CSS

    show loading image before the content loads through jquery or ajax

    How to center part of a navbar

    How to position a drop down list nav bar inside header in html css

    How to make a 3 column layout fill 100% width using pixel metric on 2 columns?

    How to put an image in div with CSS?

    CSS: How to crop image that has any size?

    How to simulate pixel ratio to test media queries with Google Chrome or Firefox on Windows?

    How to set table cell padding from CSS?

    Use css to not show the text box

    how can I set my gradient background in css for full width and height of the page?

    How to slide a image in background in css?

    How to handle the html and css of one side image and other side content and vice versa

    Show or hide button text responsively in jQuery Mobile

    How to make CSS background-image responsive? [duplicate]

    How to force a browser to show the latest changes to a CSS file?

    How to select an element and its first child without repetition in CSS?

    How to run PHP through Adobe Muse generated CSS

    How to conditionally adjust paddings using css only?

    How to do a best fit vertical align

    How to change active link color in navigation bar

    CSS: How to shadow a field like this? [closed]

    How to generate CSS with loop in less

    In jQuery how do I make multiple changes to css in a function?

    How to add row highlight using html, css, and javascript?

    How to cover box shadow?

    How can I use CSS to make a div float over my text whilst remaining in the right spot?

    How to create dashed radius border just with css?

    how to align div's horizontally in CSS