Tuesday, July 16, 2013

Add Custom Fonts to Web View Android


Add Custom Fonts to Web View Android

 

Some android phones wont support indic language display in web view in app. You can easily solve this  problem by adding indic font to assets folder. Assume added the font file has been added under the assets/fonts folder (kannada.ttf)


Create one WebTask class to download the web data, add CSS style ( which includes the font path ) to web view html content.


public static class WebTask extends AsyncTask<Void, Void, String> {
        private WeakReference<WebView> mWebView;
        private String mUrl;

        public WebTask(WebView webView, String url) {
            mWebView = new WeakReference<WebView>(webView);
            mUrl = url;
        }

        @Override
        protected String doInBackground(Void... params) {
            BufferedReader in = null;
            String data = null;

            try {
                HttpClient client = new DefaultHttpClient();
                URI website = new URI(mUrl);
                HttpGet request = new HttpGet();
                request.setURI(website);
                HttpResponse response = client.execute(request);
                response.getStatusLine().getStatusCode();
            //    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), HTTP.UTF_8));
                data = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
                return data;
            } catch (Exception e) {
                return null;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                        return data;
                    } catch (Exception e) {
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    int hedpos = result.indexOf("</html>");
                    String style = Utility.getFontStyle();
                    StringBuilder builder = new StringBuilder(result);
                    builder = builder.insert(hedpos, style);
                    mWebView.get().loadDataWithBaseURL(null, builder.toString(), "text/html", "utf-8", "about:blank");
                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {
                // error occured
            }
        }
    }

public static String getFontStyle() {
        return "<style>@font-face {font-family: Kannda';src: url('file:///android_asset/fonts/Kannda.ttf');}body, h2, li, p, span, div{font-family: 'Kannda' !important;}</style>";
    }
Call the web task as follows:

    WebTask task = new WebTask(yourwebviewobject, Url);
            task.execute();
If anything wrong i am doing please let me know.