4

i use webfont-loader dynamic load fonts via css files,code like this

WebFont.load({
    custom: {
        families: 'Lobster',
        urls:'mydomain.com/lobster.css'
    }
}

and in the css file,it like this

@font-face {
    font-family: 'Lobster';
    src: url('Lobster_1.3-webfont.woff') format('woff'),
         url('Lobster_1.3-webfont.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

i wonder as if there is a way to get the font face url,like "Lobster_1.3-webfont.ttf" and "Lobster_1.3-webfont.woff" which defined in css.

in webfont-loader,there is no such api,if there is no directly way,i have to load the css as text file first,but i relly don't want do such things

do you guys have any clue?

PS:the reason why i need the font's url,is because i use fabric.js to create svg file and render it to PDF by phantom.js in node side,but looks that phantom.js did not support svg with @import url('xxx.css'). so i have to use @font-face with src.

Kent Wood
  • 1,392
  • 2
  • 14
  • 30

2 Answers2

1

Well, let's say that you are using a subset of fonts that you chose and not updated by users, so you know paths of the font you are currently using. Fabricjs has an internal object that you can populate called:

fabric.fontPaths = { };

if you store there url information:

fabric.fontPaths = {Lobster: 'Lobster_1.3-webfont.woff'};

You will have font face embeeded in svg at export. That should allow you to have a properly loaded svg in phantomjs.

AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
  • yes,i know using fontPaths.but in my case,it is a dynamic load,and i have many fonts,a unwise decision is just add font file url into fontlist.json(which is now just record the css file url) – Kent Wood Aug 22 '16 at 05:54
  • 1
    talk about fabric fontPaths,it looks they guys didn't consider about the styles,same font family but different style,need different font file,right? – Kent Wood Aug 22 '16 at 06:06
  • It depends from the font file. If you have bold italic and bold+italic in the same file this method works. Otherwise you have to define different families Lobster_bold, Lobster_italic and so on. – AndreaBogazzi Aug 22 '16 at 06:09
1

First get font name with URL's.

var fontArray = [];
$.get("https://www.googleapis.com/webfonts/v1/webfonts?key={your key}&sort=popularity", {}, function (data) {
    var count = 0;
    $.each(data.items, function (index, value) {
        count++
        fontArray.push(value);
    });
});

and then add to fabric.fontPaths.

    $.each(fontArray, function (i, item) {
     if (fontName == item.family) {
     var ttfFile  = item.files.regular;
     var dataFile = [];
    fabric.fontPaths[fontName] = "data:font/opentype;charset=utf-8;base64," + ttfFile;
      }
})
Mudassir
  • 398
  • 5
  • 6