I need to change font-family to a custom one after loading html into WebView. Basically I need to get this:
<style>
@font-face {
font-family: 'MyFont';
src: url('file:///android_asset/Custom-Font.otf')
}
body { font-family: 'MyFont', serif; font-size: 17px; color: #000; }
a { color: #000; }
</style>
from
<style>
body { font-family: 'Helvetica', serif; font-size: 17px; color: #000; }
a { color: #000; }
</style>
Html is dynamically loaded, not from assets. I use Jsoup, but cannot get this font-family parameter so far...
JSoup does not parse the CSS for you. It ends up in a DataNode
hanging off the style
element. From there, you are on your own in terms of parsing. If you have a simple search and replace, you can use a regular expression to do the work. For complicated situations, you can look at a [CSS Parser][1]. Your situation looks relatively simple, but given just one exemplar it is hard to tell which elements you want preserved. Here is a sketch of the basic idea, you may need to modify to fully fit your situation. The basic idea is to get the DataNode
from the Style
tag and using a regex to search and replace the field.
final String newFontInfo = "@font-face { \n"
+ "font-family: 'MyFont';\n"
+ "src: url('file:///android_asset/Custom-Font.otf')\n" + "}\n";
Elements styles = doc.select("style");
for (Element style : styles) {
for (DataNode data : style.dataNodes()) {
String dataTxt = data.getWholeData();
if (dataTxt.contains("font-family")) {
final String newData = dataTxt.replaceAll("font-family:\\s*'[^']*'","font-family: 'MyFont'");
data.setWholeData(newFontInfo + newData);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.