load ttf font file as binary string in javascript

You can use XMLHttpRequest to get font file and then convert it to base64. Here is code example:

index.tsx
function loadFontAsBase64(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';
  xhr.onload = function(e) {
    if (this.status == 200) {
      var uInt8Array = new Uint8Array(this.response);
      var i = uInt8Array.length;
      var binaryString = new Array(i);
      while (i--)
      {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
      }
      var data = binaryString.join('');
      var base64 = window.btoa(data);
      callback(base64);
    }
  };
  xhr.send();
}

loadFontAsBase64('font.ttf', function(base64){
  console.log(base64); // font file as base64 string
});
658 chars
25 lines

You can use this base64 string in CSS like this:

@font-face {
  font-family: 'YourFont';
  src: url(data:application/x-font-ttf;base64,base64-encoded-font-data) format('truetype');
}
134 chars
5 lines

related categories

gistlibby LogSnag