How do I use the Arial font with Prawn on OS X?

croceldon picture croceldon · Aug 14, 2012 · Viewed 9.6k times · Source

I'm trying to use ruby to generate a PDF using Prawn on OS X. I have the following:

font 'Arial'

Arial is installed on my Mac. But when I try to generate the PDF, I get the following error:

Prawn::Errors::UnknownFont in ProjectsController#show
Arial is not a known font.

How can I get this common font to work in Prawn? In fact, almost anything other than Helvetica or Times New Roman throws this same error. This is part of a Rails 3.2 app.

If I try to load the font ttf file directly, per Ashish's suggestion below, I get a Bad font family message:

RuntimeError (Bad font family):
  app/pdfs/quote_sheet_pdf.rb:29:in `page_top'
  app/pdfs/quote_sheet_pdf.rb:12:in `initialize'
  app/controllers/projects_controller.rb:9:in `new'
  app/controllers/projects_controller.rb:9:in `block (2 levels) in show'
  app/controllers/projects_controller.rb:7:in `show'
  config/initializers/quiet_assets.rb:7:in `call_with_quiet_assets'

Answer

matt picture matt · Aug 18, 2012

If you’re using the :style option to calls to text, e.g.

text "Hello World", :style => :italic

Then the font you’re using at the time needs to have an associated font family, otherwise you’ll get the “Bad font family” error you’re seeing, e.g. this:

Prawn::Document.generate("output.pdf") do
  font "/Library/Fonts/Arial.ttf"
  text "Hello World", :style => :italic
end

produces: Bad font family (RuntimeError).

One way round this would be to always specify the exact font file you want every time you want to change style, e.g.

font "/Library/Fonts/Arial Italic.ttf"
text "Hello World"

A better option would be to create a font family with the styles you want:

Prawn::Document.generate("output.pdf") do

  font_families.update("Arial" => {
    :normal => "/Library/Fonts/Arial.ttf",
    :italic => "/Library/Fonts/Arial Italic.ttf",
    :bold => "/Library/Fonts/Arial Bold.ttf",
    :bold_italic => "/Library/Fonts/Arial Bold Italic.ttf"
  })

  font "Arial"
  text "Hello World"
  text "Hello World", :style => :italic
  text "Hello World", :style => :bold
  text "Hello World", :style => :bold_italic
end

After you’ve set up the font family you can just use Arial as the font name, and you can use the different styles easily.