public
Description: Fast, Nimble PDF Writer for Ruby
Homepage: http://prawn.majesticseacreature.com
Clone URL: git://github.com/sandal/prawn.git
prawn / lib / prawn / document / text / box.rb
100644 53 lines (42 sloc) 1.392 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
module Prawn
  class Document
    
    def text_box(text,options)
      Text::Box.new(text, options.merge(:for => self)).render
    end
    
    module Text
      class Box
        def initialize(text,options={})
          @document = options[:for]
          @text = text
          @at = options[:at] || [0, @document.y - @document.bounds.absolute_bottom]
          @width = options[:width] || @document.bounds.width
          @height = options[:height]
          @overflow = options[:overflow] || :truncate
        end
        
        def render
          x,y = @at
          
          unless @overflow == :expand
            fit_text_to_box
          end
          
          @document.y = @document.bounds.absolute_bottom + y
          @document.span(@width, :position => x) do
            @document.text @text
          end
            
        end
        
        private
        
        def fit_text_to_box
          text = @document.font.metrics.naive_wrap(@text,
            @width, @document.font.size)
            
          max_lines = (@height / @document.font.height).floor
          
          unless text.lines.size < max_lines
            @text = text.lines[0...max_lines].join
            case(@overflow)
            when :ellipses
              @text[-3..-1] = "..."
            end
          end
        end
        
      end
    end
  end
end