Using custom fonts in WKWebView Using custom fonts in WKWebView ios ios

Using custom fonts in WKWebView


I faced same issue, in my case i could fix it WITHOUT using base64 encoding and GCDWebServer.

Scenario:

  • WkWebView loading is through string html
  • WkWebView is using local .css
  • Fonts are local and are added at top level project
  • Entries for fonts are provided in appName-info.plist under key Fonts provided by application

Solution:

Add font face in .css at top level as follows

@font-face{    font-family: 'FontFamily';    src: local('FontFamily'),url('FontFileName.otf') format('opentype');}

DEMO PROJECT:

GitHub Project Link

NOTE: Fresh demo app run may take 2-3 sec, I have tested it for long html string it works same as UIWebView, no lags. Same font may look bit smaller in WKWebView than UIWebView.


Assuming you embed the font in your application as a resource that's copied to the target bundle, you can give the WKWebView access to the font by passing a NSURL to it's folder as the baseURL

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];NSURL *bundleUrl = [NSURL fileURLWithPath:bundlePath];[self.webView loadHTMLString:HTML baseURL:bundleUrl];

and define the font-face url without any preceeding path elements, which in turn makes WKWebKit prepend the baseURL

<style>  @font-face { font-family: 'Custom Font'; src: url('CustomFont.ttf'); }  ...</style>


Since I don't want to use another third party just for that and since I'm building the html string itself, I took the first part of using the font-face and instead of using a url to a remote or local file, i converted the fonts to base64.

The css looks like this:

@font-face {    font-family: 'FONTFAMILY';    src: url(data:font/ttf;base64,FONTBASE64) format('truetype');}

You can replace the FONTFAMILY with the family that you need and the FONTBASE64 with the base 64 string that was generated from the font.

If you need to create the base64 string in your application, you can use this, just provide the filename and type (i used it to get other files as well so it's more generic, you can remove the ofType parameter and use @"ttf" instead):

- (NSString*)getBase64FromFile:(NSString*)fileName ofType:(NSString*)type{    NSString * filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:type];    // Create NSData object    NSData *nsdata = [NSData dataWithContentsOfFile:filePath];    // Get NSString from NSData object in Base64    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];    return base64Encoded;}

if you want to do it only one time and then save it in some file, you can use any of the online websites that converts files to base64, like this: http://www.opinionatedgeek.com/dotnet/tools/base64encode/