How to convert TypeKit fonts to PNG for comping

I recently ran into a problem when trying to use a TypeKit font: I didn’t have the font. I knew which font I wanted to use for the project and I had some preliminary designs, but I really wanted to drop it in to see how it would look. So I did a little googling to see if I could use the TypeKit fonts for photoshop somehow or generate a png from a comp tool, but found nothing. I admittedly didn’t look very hard, but the solution most people had was buy the font or illegally download it.

Well, I’m not going to do either of those choices

Here’s a link to what I prototyped: http://jrf0110.github.com/text-to-png/

The bottom one is the image

Now, this tool works with any font you can load in via CSS. Since I was specifically wanted to use TypeKit fonts, I’ll talk about how I went about doing that.

It’s pretty easy actually

What I do is use a hidden canvas element to write the text from the editable div. You can convert canvas to a png via the context.canvas.toDataURL() function. It returns the data that represents a PNG by default but you can pass in different types.

// language: markup;
<div class="tool">
  <div class="left">
    <input class="family" id="fontFamily" value="Helvetica" />
    <input class="font-size" id="fontSize" value="16px" />
    <input class="color" id="fontColor" value="#333" />
    <div class="text" id="text">Hello World!</div>
  </div>
  <div class="right">
    <img class="result" id="result" src="src" alt="image" />
  </div>
</div>

Here’s the function that handles drawing on the canvas and setting the iamge

// language: javascript;
var updateImage = function(){
  var
    // Get the dimensions from the text element
    width = text.offsetWidth
  , height = text.offsetHeight
  ;
  // Clear the canvas for drawing
  foContext.clearRect(0, 0, foCanvas.width, foCanvas.height);

  // Setup the correct size for the PNG and some basic styling
  foCanvas.width          = width + 20;
  foCanvas.height         = height + 20;
  foContext.font          = font.size + " " + font.family;
  foContext.fillStyle     = font.color;
  foContext.textBaseline  = "top";

  // Make it so
  foContext.fillText(text.innerHTML, 0, 0);
  result.src = foContext.canvas.toDataURL();
}

Getting typekit in there was the easy part. Just get your kit id from typekit and then load in a script with the url of //use.typekit.net/{YOUR_KIT_ID}.js

You can view the full source on github.

Limitations

This was just a quick hack that isn’t quite there yet. I started to implement word wrapping, but my algorithm isn’t quite right yet. There’s also changing the font weight. I’m sure That could easily be added actually.