Change WebView font using CSS; font file in asset folder. (problem) - android

I want to change WebView font. There are 2 files in "assets" folder. They are:
assets/fonts/DejaVuSans.ttf and
assets/css/result.css
I searched some answers on StackOverflow and find out a solution but it doesn't work. The result.css loads DejaVuSans.ttf using #font-face directive. Then it is included in < link > tag of data which is passed to WebView::loadDataWithBaseURL (The code is below). The problem is CSS styles works (the text is red) but the font doesn't. Square characters appears when I show phonetic symbols (/'pə:sn/).
String resultText = "<html><head>";
resultText += "<link href=\"css/result.css\"" + " rel=\"stylesheet\" type=\"text/css\" />";
resultText += "<style>" + "#font-face { font-family: \"DejaVuSans\"; " + "" +
"src: url('file:///android_asset/fonts/DejaVuSans.ttf'); }</style>";
resultText += "</head>";
resultText += "<body><p>" + text + "</p>" + "</body></html>";
resultView.loadDataWithBaseURL("file:///android_asset/", resultText, "text/html", "utf-8", null);
result.css:
#font-face {
font-family: "DejaVuSans";
/*src: url('fonts/DejaVuSans.ttf'); also not work*/
src: url('file:///android_asset/fonts/DejaVuSans.ttf');
}
body {
color: red;
}
The System.out.println(resultText) is:
<html><head><link href="css/result.css" rel="stylesheet" type="text/css" /><style>#font-face { font-family: "DejaVuSans"; src: url('file:///android_asset/fonts/DejaVuSans.ttf'); }</style></head><body><p>person /'pə:sn/</p></body></html>

It was solved. I didn't add "font-family" to body selector and font url must be file:///android_asset/fonts/DejaVuSans.ttf".
#font-face {
font-family: 'DejaVuSans';
/* src: url('DejaVuSans.ttf'); This doesn't work */
/* src: url('fonts/DejaVuSans.ttf'); Neither is this */
src: url('file:///android_asset/fonts/DejaVuSans.ttf'); /* but this does */
}
body {
font-family: 'DejaVuSans';
color: red;
}

Known bug on 2.0 and 2.1 :
http://code.google.com/p/android/issues/detail?id=4448
For 2.2 :
#font-face {
font-family: 'FontName';
src: url('filefont.ttf'); // with no "fonts/"
}

I used cufon replacement for devices that didn't support my local font face.
I wrote a javascript function to determine whether cufon is required
requiresCufon : function(){
var version = window.navigator.userAgent.match(/Android\s+([\d\.]+)/);
var MINIMUM_OS_FONTFACE = 2.2;
if(typeof version != 'undefined'){
//strip non digits
version = version[0].replace(/[^0-9\.]/g, '');
//if version is less than required for #font-face then cufon
if(parseFloat(version) < MINIMUM_OS_FONTFACE)
return true;
else
return false;
}
else{
return true;
}
},

Related

Use custom font from res/font with WebView in Android

I want to change font face of html string loaded into WebView similarly as mentioned in this question:
How to change font face of Webview in Android?
The difference is that I am not using old approach where you store you font files in assets folder, but I store them in res/font as described in "Fonts in XML" android font support documentation:
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
Now, I obviously can't use:
file:///android_asset/fonts/my_font.otf
I tried:
file:///android_res/font/my_font.otf
and many other ways of describing path to my font inside of res/font folder, but none of them work.
How to use custom font family for a WebView that loads html string if my font is stored in res/font folder ?
//Edit:
My current implementation that is not working is:
#BindingAdapter("loadData")
public static void loadData(WebView webView, String htmlData) {
webView.loadDataWithBaseURL(null, htmlData, "text/html", "utf-8", null);
}
#BindingAdapter({"loadData", "fontFamily"})
public static void loadData(WebView webView, String htmlData, #FontRes int fontFamilyId) {
TypedValue value = new TypedValue();
ApplicationActivity.getSharedApplication().getResources().getValue(fontFamilyId, value, true);
String fontPath = value.string.toString();
File fontFile = new File(fontPath);
String prefix = "<html>\n"
+"\t<head>\n"
+"\t\t<style type=\"text/css\">\n"
+"\t\t\t#font-face {\n"
+"\t\t\t\tfont-family: 'CustomFont';\n"
+"\t\t\t\tsrc: url(\"file:///android_res/font/"+fontFile.getName()+"\")\n"
+"\t\t\t}\n"
+"\t\t\tbody {\n"
+"\t\t\t\tfont-family: 'CustomFont';\n"
+"\t\t\t}\n"
+"\t\t</style>\n"
+"\t</head>\n"
+"\t<body>\n";
String postfix = "\t</body>\n</html>";
loadData(webView, prefix + htmlData + postfix);
}
Just tried and this works similarly to loading fonts from assets, you just need to change the base url to point to resources instead.
Example HTML
<html>
<head>
<style>
#font-face {
font-family: 'CustomFont';
src: url('font/CustomFont.ttf');
}
#font {
font-family: 'CustomFont';
}
</style>
</head>
<body>
<p>No Font</p>
<br />
<p id="font">Font</p>
</body>
load this HTML into the webview using Webview#loadDataWithBaseURL(String, String, String, String, String), using file://android_res/ as the base url (first param)
Example:
webview.loadDataWithBaseURL("file:///android_res/", html, "text/html", "utf-8", null)
Edit:
If you're using proguard on your release builds you'll need to add extra rules to prevent the R class being renamed during the ProGuard process otherwise the WebView won't be able to find the font resource. Details can be found at this post
I managed to load my local font from res/font directory. In my example i want to load italic opensans.
My setup are as follow:
css file inside assets directory
use this for setting the font-face
#font-face {
font-family: 'opensans';
src: url("file:///android_res/font/opensans_italic.ttf")
}
body {
font-family: 'opensans';
font-weight: 400;
}
Load the WebView using loadDataWithBaseUrl, for example:
webView.loadDataWithBaseURL(null, yourHtmlContent, "text/html", "utf-8", null)
But i have this at the the top of my html content:
"<link rel='stylesheet' type='text/css' href='file:///android_asset/mycss.css' />”
I hope it works too for your case.
Edit:
Add this in your proguard config to make it work in release mode.
-keep class com.your.package.name.R$font { *; }
You can use the custom res font like this -
<head>
<style type="text/css">
#font-face {
font-family: MyFont;
src: url("file:///res/font/myfont.ttf")
}
body {
font-family: MyFont;
}
</style>

How to show Myanmar font from database in webview

I store Myanmar font in database. When I show Myanmar font by webview, They show the followings. How do I change my codes? Please help me.
ပရမá€á± (ပရမ + အá€á³) = အá‚ွစ္á€á€ºá€³á€•á€¹áŠ အျမင့္ဆုံး သိစရာá‹
These are my codes.
dstory = (WebView) findViewById(R.id.dstory);
String data=result.getString(3);
dstory.loadData(data , "text/html", "utf-8");
Try adding Fonts to your Asset folder and add it to your WebView by CSS
You Code Should be loaded from asset directory
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
and your CSS should be
#font-face {
font-family: 'my_font';
src: url('my_font.ttf');
}
#Muthu Thank u for your advice.Now I got it.
In css file,
#font-face {
font-family: 'ZawgyiOne2008';
src: url('file:///android_asset/ZawgyiOne2008.ttf');
}
body{
font-family: ZawgyiOne2008; width: 100%;
background-color: transparent;
padding: 0px;
}
In my DetailActivity.java, to link css is used full html.
WebView view = (WebView)findViewById(R.id.webView1);
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html =
"<html><head><LINK href=\"file:///android_asset/bootstrap.css\" type=\"text/css\" rel=\"stylesheet\"/></head><body><H1 class='label'>A simple HTML page</H1>" +
"<input type='text' class='input-large' required='true' id='cname' name='cname'/>" +
"<input type='text'/>" +
"<p>The quick brown fox jumps over the lazy dog</p></body></html>";
view.loadDataWithBaseURL("", html, mimeType, encoding, "");
To show Myanmar Font from database, use string replace.
String old="%#";
String newstr=html.replace(old, data);

android- font face is not changing on webview

I need to change webview font face , I've searched and I used this but it didn't change the font , I've the font file in asset folder :
wb.loadData(
"<html><head><style>#font-face { font-family: myface;src: url('file:///android_asset/yekan.ttf');" +
"BODY, HTML {background: transparent; } body,div { font-family: myface;} </style></head><body><div style='text-align: justify; line-height: 23px;float:right' dir='rtl'>"
+ text + "</div></body></html>",
"text/html; charset=utf-8", "UTF-8");
is it wrong or webview couldn't change the font face ?
thanks
change
url('file:///android_asset/yekan.ttf')
to
url(\"file:///android_asset/yekan.ttf\")

Android Jsoup change font-family in style tag

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);
}
}
}

font styles not working when set custom font for webview

Main.java:
Main instanceMain = this;
String Dataz = FN.getHtmlData(instanceMain,"BMitra",20,(getResources().getString(R.string.matn2)));
btne.loadDataWithBaseURL("file:///android_asset/", Dataz, "text/html", "utf-8", null);
FN.java:
public static String getHtmlData(Context context,String fontname,Integer fontsize, String data){
String head = "<head><style type=\"text/css\">#font-face {font-family: 'MYFNT';src: url('"+fontname+".ttf');} body {text-align:justify;font-family: 'MYFNT';color: Black;}</style></head>";
String htmlData= "<html>"+head+"<body dir=\"rtl\">"+data+"</body></html>" ;
return htmlData;
}
strings.xml:
<string name="matn2">
<![CDATA[
<html><body><b>سلام</b> non bold text . <b>english bold</b></body></html>
]]>
</string>
but bold tag not working and output is : سلام english bold . non bold text
by the way i found some report issue
in another way :
Main.java :
Main instanceMain = this;
String Dataz = FN.getHtmlData(instanceMain,getResources().getString(R.string.matn2)));
btne.loadDataWithBaseURL("file:///android_asset/", Dataz, "text/html", "utf-8", null);
FN.java:
public static String getHtmlData(Context paramContext, String paramString)
{
return "<!DOCTYPE HTML><html lang=\"fa-ir\" dir=\"rtl\"><head>" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"justified_textview.css\" />" + "</head>" + " <body>" + paramString + "</body></html>";
}
justified_textview.css (in assest folder) :
/*#font-face {
font-family:"MyFont";
src:url('file:///android_asset/BMITRA.TTF');
}
#font-face {
font-family:"MyFont";
src:url('file:///android_asset/BMITRABD.TTF');
font-weight: bold;
}*/
#font-face {
font-family: 'Conv_BMITRA';
src: url('file:///android_asset/BMITRA.ttf');
font-weight: normal;
font-style: normal;
}
#font-face {
font-family: 'Conv_BMITRA';
src: url('file:///android_asset/BMITRABD.ttf');
font-weight: bold;
font-style: normal;
}
body {
font-family:'Conv_BMITRA';
text-align:justify;
line-height: 20pt;
color: Black;
}
and matn2(strings.xml) :
<string name="matn">
<![CDATA[
م ولادت توی وب با سی اس اس
normal text
<b>ولایت بولد م bold text</b>
]]>
</string>
and now its work on android 2.3.3 or 2.3.5 but not working on android 4.0.x
It's not possible, because of Webview rather than Android OS progress, is broken. If you set a custom font for Webview, in some device and Android OS it works and in some others not, unfortunately.
I ran into the same issue on a really large page I was displaying. Try setting the activity with the webview to android:hardwareAccelerated="false" in the manifest.

Categories

Resources