使用 jsoup + cssparser:
private static final String STYLE_ATTR = "style";
private static final String CLASS_ATTR = "class";
public String inlineStyles(String html, File cssFile, boolean removeClasses) throws IOException {
Document document = Jsoup.parse(html);
CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
InputSource source = new InputSource(new FileReader(cssFile));
CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);
CSSRuleList ruleList = stylesheet.getCssRules();
Map<Element, Map<String, String>> allElementsStyles = new HashMap<>();
for (int ruleIndex = 0; ruleIndex < ruleList.getLength(); ruleIndex++) {
CSSRule item = ruleList.item(ruleIndex);
if (item instanceof CSSStyleRule) {
CSSStyleRule styleRule = (CSSStyleRule) item;
String cssSelector = styleRule.getSelectorText();
Elements elements = document.select(cssSelector);
for (Element element : elements) {
Map<String, String> elementStyles = allElementsStyles.computeIfAbsent(element, k -> new LinkedHashMap<>());
CSSStyleDeclaration style = styleRule.getStyle();
for (int propertyIndex = 0; propertyIndex < style.getLength(); propertyIndex++) {
String propertyName = style.item(propertyIndex);
String propertyValue = style.getPropertyValue(propertyName);
elementStyles.put(propertyName, propertyValue);
}
}
}
}
for (Map.Entry<Element, Map<String, String>> elementEntry : allElementsStyles.entrySet()) {
Element element = elementEntry.getKey();
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> styleEntry : elementEntry.getValue().entrySet()) {
builder.append(styleEntry.getKey()).append(":").append(styleEntry.getValue()).append(";");
}
builder.append(element.attr(STYLE_ATTR));
element.attr(STYLE_ATTR, builder.toString());
if (removeClasses) {
element.removeAttr(CLASS_ATTR);
}
}
return document.html();
}