Method: Prawn::Document#font

Defined in:
lib/prawn/font.rb

#font(name = nil, options = DEFAULT_OPTS) { ... } ⇒ Font

Without arguments, this returns the currently selected font. Otherwise, it sets the current font. When a block is used, the font is applied transactionally and is rolled back when the block exits.

“‘ruby Prawn::Document.generate(“font.pdf”) do

text "Default font is Helvetica"

font "Times-Roman"
text "Now using Times-Roman"

font("DejaVuSans.ttf") do
  text "Using TTF font from file DejaVuSans.ttf"
  font "Courier", style: :bold
  text "You see this in bold Courier"
end

text "Times-Roman, again"

end “‘

The ‘name` parameter must be a string. It can be one of the 14 built-in fonts supported by PDF, or the location of a TTF file. The Fonts::AFM::BUILT_INS array specifies the valid built in font names.

If a TTF/OTF font is specified, the glyphs necessary to render your document will be embedded in the rendered PDF. This should be your preferred option in most cases. It will increase the size of the resulting file, but also make it more portable.

The options parameter is an optional hash providing size and style. To use the :style option you need to map those font styles to their respective font files.

Parameters:

  • name (String) (defaults to: nil)

    font name. It can be:

    • One of 14 PDF built-in fonts.

    • A font file path.

    • A font name defined in #font_families

  • options (Hash{Symbol => any}) (defaults to: DEFAULT_OPTS)

Options Hash (options):

  • :style (Symbol)

    font style

Yields:

Returns:

See Also:



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/prawn/font.rb', line 56

def font(name = nil, options = DEFAULT_OPTS)
  return((defined?(@font) && @font) || font('Helvetica')) if name.nil?

  if state.pages.empty? && !state.page.in_stamp_stream?
    raise Prawn::Errors::NotOnPage
  end

  new_font = find_font(name.to_s, options)

  if block_given?
    save_font do
      set_font(new_font, options[:size])
      yield
    end
  else
    set_font(new_font, options[:size])
  end

  @font
end