Hi, I'm Tiago

Easy way to use Custom Fonts in Android WebViews

Published on

Sometimes a backend provides you with a partial or unstyled html code, usually provenient from a Rich Text editor in a Web App. Therefore, you need to complete this html code and display it in a WebView. If you’re using a custom font, you might have noticed there’s no straightforward way to modify the default WebView font family, as there is for other views. Here’s an easy way to do it via CSS.

Let’s just assume you have a .ttf or an .otf file under your res/font directory. You can use the following code snippet to have a complete HTML you can load in a WebView. This method will NOT work for xml font family resources, as they’re native to Android, and not web.

val myFont = "file:///android_res/font/my_custom_font.ttf"

fun completeHtmlFrom(bodyContents: String) = """

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

  <html>
    <head>
      <style type="text/css">

        @font-face {
          font-family: "my_font";
          src: url("$myFont");
        }

        body { font-family: "my_font"; }

      </style>
    </head>

    <body> $bodyContents </body>

  </html>

"""

Then all you need to do is load the resulting html into your WebView:

val bodyContents = "<p>This text is going to be rendered with myFont.</p>"
myWebView.loadData(completeHtmlFrom(bodyContents), "text/html", "UTF-8");