Add custom css to html code with jsoup
Several ways. You can use Element#append()
to append some piece of HTML to the element.
Document document = Jsoup.connect(url).get();
Element head = document.head();
head.append("<link rel=\"stylesheet\" href=\"http://example.com/your.css\">");
Or, use Element#attr(name, value)
to add attributes to existing elements. Here's an example which adds style="color:pink;"
to all links.
Document document = Jsoup.connect(url).get();
Elements links = document.select("a");
links.attr("style", "color:pink;");
Either way, after modification get the final HTML string by Document#html()
.
String html = document.html();
Write it to file by PrintWriter#write()
(with the right charset).
String charset = Jsoup.connect(url).response().charset();
// ...
Writer writer = new PrintWriter("/file.html", charset);
writer.write(html);
writer.close();
Finally open it in the webview. Since I can't tell it from top of head, here's just a link with an example which I think is helpful: WebViewDemo.java. I found the link on this blog by the way (which I in turn found by Google).
How to add external CSS to HTML 'style'
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>
Extract CSS Styles from HTML using JSOUP in JAVA
If the style is embedded in your Element you just have to use .attr("style")
.
JSoup is not a Html renderer, it is just a HTML parser, so you will have to parse the content from the retrieved <style>
tag html content. You can use a simple regex for this; but it won't work in all cases. You may want to use a CSS parser for this task.
public class Test {
public static void main(String[] args) throws Exception {
String html = "<HTML>\n" +
"<HEAD>\n"+
"<TITLE>Page 1</TITLE>\n"+
"<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"+
"<DIV style=\"position:relative;width:931;height:1243;\">\n"+
"<STYLE type=\"text/css\">\n"+
"<!--\n"+
" .ft00{font-size:11px;font-family:Times;color:#ffffff;}\n"+
" .ft01{font-size:11px;font-family:Times;color:#ffffff;}\n"+
"-->\n"+
"</STYLE>\n"+
"</HEAD>\n"+
"</HTML>";
Document doc = Jsoup.parse(html);
Element style = doc.select("style").first();
Matcher cssMatcher = Pattern.compile("[.](\\w+)\\s*[{]([^}]+)[}]").matcher(style.html());
while (cssMatcher.find()) {
System.out.println("Style `" + cssMatcher.group(1) + "`: " + cssMatcher.group(2));
}
}
}
Will output:
Style `ft00`: font-size:11px;font-family:Times;color:#ffffff;
Style `ft01`: font-size:11px;font-family:Times;color:#ffffff;
Possible to style jsoup output with CSS?
When you have selected element or elements you can style it by adding new class:
elements.addClass("your-class");
or by adding your own style attribute:
elements.attr("style", "text-align: center; color: red;");
These changes are saved in document
object so to use updated HTML code you will probably want to use the output of: document.html()
.
How to add padding to html content using Jsoup?
You could set the style using javascript. Add the following code before webView1.loadDataWithBaseURL(...)
webView1.setWebViewClient(
new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
String javascriptCode = "javascript:";
javascriptCode+="var elements=document.querySelectorAll(\"code\");";
javascriptCode+="var parent;";
javascriptCode+="var container;";
javascriptCode+="for(i in elements){";
javascriptCode+="container = document.createElement('div');";
javascriptCode+="parent = elements[i].parentElement;";
javascriptCode+="parent.replaceChild(container, elements[i]);";
javascriptCode+="container.appendChild(elements[i]);";
javascriptCode+="container.setAttribute(\"style\",\"overflow:scroll; border: 1px solid black; background-color: #EEEEEE; padding-top: 50px; padding-right: 30px; padding-bottom: 50px; padding-left: 80px;\");}";
webView1.loadUrl(javascriptCode);
}
}
);
CSS from URL not working in JSoup
Instead of loadData()
try to use loadDataFromBaseUrl()
.
Well or do it With
it ;-).
Related Topics
How to Solve the "Double-Checked Locking Is Broken" Declaration in Java
How to Use an Arraylist as a Prepared Statement Parameter
How to Scroll More Than One Object at the Same Time
Why Do I Need Transaction in Hibernate for Read-Only Operations
Prevent Android Activity Dialog from Closing on Outside Touch
How to Create Android Virtual Device
Change Listview Background - Strange Behaviour
How to Sort Alphabetically While Ignoring Case Sensitive
Android HTML.Fromhtml() with Images
Android Onconfigurationchanged Not Being Called
Java - Declaring from Interface Type Instead of Class
Meaning of the Import Statement in a Java File
Intellij Fat One Jar Artifact Does Not Generate a Working Output
How to Change Webservice Url Endpoint
How to Set Background Color of an Activity to White Programmatically
How to Remove All Callbacks from a Handler
Android: Email Client Receiver Email Id Empty in Android-Parse