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 / table.rb
100644 239 lines (207 sloc) 8.413 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# encoding: utf-8
 
module Prawn
  class Document
 
    # Builds and renders a Document::Table object from raw data.
    # For details on the options that can be passed, see
    # Document::Table.new
    #
    # data = [["Gregory","Brown"],["James","Healy"],["Jia","Wu"]]
    #
    # Prawn::Document.generate("table.pdf") do
    #
    # # Default table, without headers
    # table(data)
    #
    # # Default table with headers
    # table data, :headers => ["First Name", "Last Name"]
    #
    # # Very close to PDF::Writer's default SimpleTable output
    # table data, :headers => ["First Name", "Last Name"],
    # :font_size => 10,
    # :vertical_padding => 2,
    # :horizontal_padding => 5,
    # :position => :center,
    # :row_colors => :pdf_writer,
    #
    # # Grid border style with explicit column widths.
    # table data, :border_style => :grid,
    # :widths => { 0 => 100, 1 => 150 }
    #
    # end
    #
    def table(data,options={})
      Prawn::Document::Table.new(data,self,options).draw
    end
 
    # This class implements simple PDF table generation.
    #
    # Prawn tables have the following features:
    #
    # * Can be generated with or without headers
    # * Can tweak horizontal and vertical padding of text
    # * Minimal styling support (borders / row background colors)
    # * Can be positioned by bounding boxes (left/center aligned) or an
    # absolute x position
    # * Automated page-breaking as needed
    # * Column widths can be calculated automatically or defined explictly on a
    # column by column basis
    #
    # The current implementation is a bit barebones, but covers most of the
    # basic needs for PDF table generation. If you have feature requests,
    # please share them at: http://groups.google.com/group/prawn-ruby
    #
    # Tables will be revisited before the end of the Ruby Mendicant project and
    # the most commonly needed functionality will likely be added.
    #
    class Table
 
      attr_reader :col_widths # :nodoc:
 
      # Creates a new Document::Table object. This is generally called
      # indirectly through Document#table but can also be used explictly.
      #
      # The <tt>data</tt> argument is a two dimensional array of strings,
      # organized by row, e.g. [["r1-col1","r1-col2"],["r2-col2","r2-col2"]].
      # As with all Prawn text drawing operations, strings must be UTF-8 encoded.
      #
      # The following options are available for customizing your tables, with
      # defaults shown in [] at the end of each description.
      #
      # <tt>:font_size</tt>:: The font size for the text cells . [12]
      # <tt>:horizontal_padding</tt>:: The horizontal cell padding in PDF points [5]
      # <tt>:vertical_padding</tt>:: The vertical cell padding in PDF points [5]
      # <tt>:padding</tt>:: Horizontal and vertical cell padding (overrides both)
      # <tt>:border</tt>:: With of border lines in PDF points [1]
      # <tt>:border_style</tt>:: If set to :grid, fills in all borders. Otherwise, borders are drawn on columns only, not rows
      # <tt>:position</tt>:: One of <tt>:left</tt>, <tt>:center</tt> or <tt>n</tt>, where <tt>n</tt> is an x-offset from the left edge of the current bounding box
      # <tt>:widths:</tt> A hash of indices and widths in PDF points. E.g. <tt>{ 0 => 50, 1 => 100 }</tt>
      # <tt>:row_colors</tt>:: An array of row background colors which are used cyclicly.
      #
      # Row colors are specified as html encoded values, e.g.
      # ["ffffff","aaaaaa","ccaaff"]. You can also specify
      # <tt>:row_colors => :pdf_writer</tt> if you wish to use the default color
      # scheme from the PDF::Writer library.
      #
      # See Document#table for typical usage, as directly using this class is
      # not recommended unless you know why you want to do it.
      #
      def initialize(data, document,options={})
        @data = data
        @document = document
        @font_size = options[:font_size] || 12
        @border_style = options[:border_style]
        @border = options[:border] || 1
        @position = options[:position] || :left
        @headers = options[:headers]
        @row_colors = options[:row_colors]
 
        @horizontal_padding = options[:horizontal_padding] || 5
        @vertical_padding = options[:vertical_padding] || 5
 
        if options[:padding]
          @horizontal_padding = @vertical_padding = options[:padding]
        end
 
        
        @row_colors = ["ffffff","cccccc"] if @row_colors == :pdf_writer
 
        @original_row_colors = @row_colors.dup if @row_colors
        
        calculate_column_widths(options[:widths])
      end
      
      # Width of the table in PDF points
      #
      def width
         @col_widths.inject(0) { |s,r| s + r }
      end
      
      # Draws the table onto the PDF document
      #
      def draw
        case(@position)
        when :center
          x = (@document.bounds.width - width) / 2.0
          y = @document.y - @document.bounds.absolute_bottom
          @document.bounding_box [x, y], :width => width do
            generate_table
          end
        when Numeric
          x = @position
          y = @document.y - @document.bounds.absolute_bottom
          @document.bounding_box [x,y], :width => width do
            generate_table
          end
        else
          generate_table
        end
      end
 
      private
 
      def calculate_column_widths(manual_widths=nil)
        @col_widths = [0] * @data[0].length
        renderable_data.each do |row|
          row.each_with_index do |cell,i|
            length = cell.lines.map { |e|
              @document.font_metrics.string_width(e,@font_size) }.max.to_f +
                2*@horizontal_padding
            @col_widths[i] = length if length > @col_widths[i]
          end
        end
        
        # TODO: Could optimize here
        manual_widths.each { |k,v| @col_widths[k] = v } if manual_widths
      end
 
      def renderable_data
        if @headers
          [@headers] + @data
        else
          @data
        end
      end
 
      def generate_table
        page_contents = []
        y_pos = @document.y
 
        @document.font_size(@font_size) do
          renderable_data.each_with_index do |row,index|
            c = Prawn::Graphics::CellBlock.new(@document)
            row.each_with_index do |e,i|
              c << Prawn::Graphics::Cell.new(
                :document => @document,
                :text => e,
                :width => @col_widths[i],
                :horizontal_padding => @horizontal_padding,
                :vertical_padding => @vertical_padding,
                :border => @border,
                :border_style => :sides )
            end
 
            if c.height > y_pos - @document.margin_box.absolute_bottom
              draw_page(page_contents)
              @document.start_new_page
              if @headers
                page_contents = [page_contents[0]]
                y_pos = @document.y - page_contents[0].height
              else
                page_contents = []
                y_pos = @document.y
              end
            end
 
            page_contents << c
 
            y_pos -= c.height
 
            if index == renderable_data.length - 1
              draw_page(page_contents)
            end
 
          end
          @document.y -= @vertical_padding
        end
      end
 
      def draw_page(contents)
        return if contents.empty?
 
        if @border_style == :grid || contents.length == 1
          contents.each { |e| e.border_style = :all }
        else
          contents.first.border_style = @headers ? :all : :no_bottom
          contents.last.border_style = :no_top
        end
 
        contents.each do |x|
          x.background_color = next_row_color if @row_colors
          x.draw
        end
 
        reset_row_colors
      end
 
      def next_row_color
        @row_colors.unshift(@row_colors.pop).last
      end
 
      def reset_row_colors
        @row_colors = @original_row_colors.dup if @row_colors
      end
 
    end
  end
end