Next-generation table drawing for Prawn.


Data, for a Prawn table, is a two-dimensional array of objects that can be converted to cells (“cellable” objects). Cellable objects can be:


Produces a text cell. This is the most common usage.


If you have already built a Cell or have a custom subclass of Cell you want to use in a table, you can pass through Cell objects.


Creates a subtable (a table within a cell). You can use Prawn::Document#make_table to create a table for use as a subtable without immediately drawing it. See examples/table/bill.rb for a somewhat complex use of subtables.


Creates a simple subtable. Create a Table object using make_table (see above) if you need more control over the subtable’s styling.


Prawn/Layout provides many options to control style and layout of your table. These options are implemented with a uniform interface: the :foo option always sets the foo= accessor. See the accessor and method documentation for full details on the options you can pass. Some highlights:


A hash of style options to style all cells. See the documentation on Prawn::Table::Cell for all cell style options.


If set to true, the first row will be repeated on every page. The header must be included as the first row of your data. Row numbering (for styling and other row-specific options) always indexes based on your data array. Whether or not you have a header, row(n) always refers to the nth element (starting from 0) of the data array.


Sets widths for individual columns. Manually setting widths can give better results than letting Prawn guess at them, as Prawn’s algorithm for defaulting widths is currently pretty boneheaded. If you experience problems like weird column widths or CannotFit errors, try manually setting widths on more columns.

Initializer Block

If a block is passed to methods that initialize a table (, Prawn::Document#table, Prawn::Document#make_table), it will be called after cell setup but before layout. This is a very flexible way to specify styling and layout constraints. This code sets up a table where the second through the fourth rows (1-3, indexed from 0) are each one inch (72 pt) wide:

  pdf.table(data) do |table|
    table.rows(1..3).width = 72

As with Prawn::Document#initialize, if the block has no arguments, it will be evaluated in the context of the object itself. The above code could be rewritten as:

  pdf.table(data) do
    rows(1..3).width = 72



Number of rows in the table.


Number of columns in the table.


Manually set the width of the table.


If true, designates the first row as a header row to be repeated on every page. Does not change row numbering — row numbers always index into the data array provided, with no modification.


Accepts an Array of alternating row colors to stripe the table.

Public Class Methods

new(data, document, options={}, &block) click to toggle source

Set up a table on the given document. Arguments:


A two-dimensional array of cell-like objects. See the “Data” section above for the types of objects that can be put in a table.


The Prawn::Document instance on which to draw the table.


A hash of attributes and values for the table. See the “Options” block above for details on available options.

     # File lib/prawn/table.rb, line 120
120:     def initialize(data, document, options={}, &block)
121:       @pdf = document
122:       @cells = make_cells(data)
123:       @header = false
124:       options.each { |k, v| send("#{k}=", v) }
126:       if block
127:         block.arity < 1 ? instance_eval(&block) : block[self]
128:       end
130:       set_column_widths
131:       set_row_heights
132:       position_cells
133:     end

Public Instance Methods

cell_style=(style_hash) click to toggle source

Sets styles for all cells.

  pdf.table(data, :cell_style => { :borders => [:left, :right] })
     # File lib/prawn/table.rb, line 197
197:     def cell_style=(style_hash)
199:     end
cells() click to toggle source

Returns a Cells object that can be used to select and style cells. See the Cells documentation for things you can do with cells.

    # File lib/prawn/table/cells.rb, line 15
15:     def cells
16:       @cell_proxy ||=
17:     end
column(col_spec) click to toggle source
Alias for: columns
column_widths() click to toggle source

Calculate and return the constrained column widths, taking into account each cell’s min_width, max_width, and any user-specified constraints on the table or column size.

Because the natural widths can be silly, this does not always work so well at guessing a good size for columns that have vastly different content. If you see weird problems like CannotFit errors or shockingly bad column sizes, you should specify more column widths manually.

     # File lib/prawn/table.rb, line 304
304:     def column_widths
305:       @column_widths ||= begin
306:         if width < cells.min_width
307:           raise Errors::CannotFit,
308:             "Table's width was set too small to contain its contents " +
309:             "(min width #{cells.min_width}, requested #{width})"
310:         end
312:         if width > cells.max_width
313:           raise Errors::CannotFit,
314:             "Table's width was set larger than its contents' maximum width " +
315:             "(max width #{cells.max_width}, requested #{width})"
316:         end
318:         if width < natural_width
319:           # Shrink the table to fit the requested width.
320:           f = (width - cells.min_width).to_f / (natural_width - cells.min_width)
322:           (0...column_length).map do |c|
323:             min, nat = column(c).min_width, column(c).width
324:             (f * (nat - min)) + min
325:           end
326:         elsif width > natural_width
327:           # Expand the table to fit the requested width.
328:           f = (width - cells.width).to_f / (cells.max_width - cells.width)
330:           (0...column_length).map do |c|
331:             nat, max = column(c).width, column(c).max_width
332:             (f * (max - nat)) + nat
333:           end
334:         else
335:           natural_column_widths
336:         end
337:       end
338:     end
column_widths=(widths) click to toggle source

Sets column widths for the table. The argument can be one of the following types:


[w0, w1, w2, ...] (specify a width for each column)


{0 => w0, 1 => w1, ...} (keys are column names, values are widths)


72 (sets width for all columns)

     # File lib/prawn/table.rb, line 164
164:     def column_widths=(widths)
165:       case widths
166:       when Array
167:         widths.each_with_index { |w, i| column(i).width = w }
168:       when Hash
169:         widths.each { |i, w| column(i).width = w }
170:       when Numeric
171:         columns.width = widths
172:       else
173:         raise ArgumentError, "cannot interpret column widths"
174:       end
175:     end
columns(col_spec) click to toggle source

Selects the given columns (0-based) for styling. Returns a Cells object — see the documentation on Cells for things you can do with cells.

    # File lib/prawn/table/cells.rb, line 30
30:     def columns(col_spec)
31:       cells.columns(col_spec)
32:     end
Also aliased as: column
draw() click to toggle source

Draws the table onto the document at the document’s current y-position.

     # File lib/prawn/table.rb, line 222
222:     def draw
223:       # The cell y-positions are based on an infinitely long canvas. The offset
224:       # keeps track of how much we have to add to the original, theoretical
225:       # y-position to get to the actual position on the current page.
226:       offset = @pdf.y
228:       # Reference bounds are the non-stretchy bounds used to decide when to
229:       # flow to a new column / page.
230:       ref_bounds = @pdf.bounds.stretchy? ? @pdf.margin_box : @pdf.bounds
232:       last_y = @pdf.y
234:       # Determine whether we're at the top of the current bounds (margin box or
235:       # bounding box). If we're at the top, we couldn't gain any more room by
236:       # breaking to the next page -- this means, in particular, that if the
237:       # first row is taller than the margin box, we will only move to the next
238:       # page if we're below the top. Some floating-point tolerance is added to
239:       # the calculation.
240:       #
241:       # Note that we use the actual bounds, not the reference bounds. This is
242:       # because even if we are in a stretchy bounding box, flowing to the next
243:       # page will not buy us any space if we are at the top.
244:       if @pdf.y > @pdf.bounds.height + @pdf.bounds.absolute_bottom - 0.001
245:         # we're at the top of our bounds
246:         started_new_page_at_row = 0
247:       else
248:         started_new_page_at_row = 1
250:         # If there isn't enough room left on the page to fit the first data row
251:         # (excluding the header), start the table on the next page.
252:         needed_height = row(0).height
253:         needed_height += row(1).height if @header
254:         if needed_height > @pdf.y - ref_bounds.absolute_bottom
255:           @pdf.bounds.move_past_bottom
256:           offset = @pdf.y
257:           started_new_page_at_row = 0
258:         end
259:       end
261:       @cells.each do |cell|
262:         if cell.height > (cell.y + offset) - ref_bounds.absolute_bottom &&
263:            cell.row > started_new_page_at_row
264:           # start a new page or column
265:           @pdf.bounds.move_past_bottom
266:           draw_header unless cell.row == 0
267:           offset = @pdf.y - cell.y
268:           started_new_page_at_row = cell.row
269:         end
271:         # Don't modify cell.x / cell.y here, as we want to reuse the original
272:         # values when re-inking the table. #draw should be able to be called
273:         # multiple times.
274:         x, y = cell.x, cell.y
275:         y += offset 
277:         # Translate coordinates to the bounds we are in, since drawing is 
278:         # relative to the cursor, not ref_bounds.
279:         x += @pdf.bounds.left_side - @pdf.bounds.absolute_left
280:         y -= @pdf.bounds.absolute_bottom
282:         # Set background color, if any.
283:         if @row_colors && (!@header || cell.row > 0)
284:           index = @header ? (cell.row - 1) : cell.row
285:           cell.background_color = @row_colors[index % @row_colors.length]
286:         end
288:         cell.draw([x, y])
289:         last_y = y
290:       end
292:       @pdf.move_cursor_to(last_y - @cells.last.height)
293:     end
height() click to toggle source

Returns the height of the table in PDF points.

     # File lib/prawn/table.rb, line 179
179:     def height
180:       cells.height
181:     end
row(row_spec) click to toggle source
Alias for: rows
row_heights() click to toggle source

Returns an array with the height of each row.

     # File lib/prawn/table.rb, line 342
342:     def row_heights
343:       @natural_row_heights ||= (0...row_length).map{ |r| row(r).height }
344:     end
rows(row_spec) click to toggle source

Selects the given rows (0-based) for styling. Returns a Cells object — see the documentation on Cells for things you can do with cells.

    # File lib/prawn/table/cells.rb, line 22
22:     def rows(row_spec)
23:       cells.rows(row_spec)
24:     end
Also aliased as: row
style(stylable, style_hash={}, &block) click to toggle source

Allows generic stylable content. This is an alternate syntax that some prefer to the attribute-based syntax. This code using style:

  pdf.table(data) do
    style(row(0), :background_color => 'ff00ff')
    style(column(0)) { |c| c.border_width += 1 }

is equivalent to:

  pdf.table(data) do
    row(0).style :background_color => 'ff00ff'
    column(0).style { |c| c.border_width += 1 }
     # File lib/prawn/table.rb, line 216
216:     def style(stylable, style_hash={}, &block)
217:, &block)
218:     end
width() click to toggle source

Returns the width of the table in PDF points.

     # File lib/prawn/table.rb, line 149
149:     def width
150:       @width ||= [natural_width, @pdf.bounds.width].min
151:     end

Protected Instance Methods

assert_proper_table_data(data) click to toggle source

Raises an error if the data provided cannot be converted into a valid table.

     # File lib/prawn/table.rb, line 375
375:     def assert_proper_table_data(data)
376:       if data.nil? || data.empty?
377:         raise Prawn::Errors::EmptyTable,
378:           "data must be a non-empty, non-nil, two dimensional array " +
379:           "of cell-convertible objects"
380:       end
382:       unless data.all? { |e| Array === e }
383:         raise Prawn::Errors::InvalidTableData,
384:           "data must be a two dimensional array of cellable objects"
385:       end
386:     end
draw_header() click to toggle source

If the table has a header, draw it at the current position.

     # File lib/prawn/table.rb, line 390
390:     def draw_header
391:       if @header
392:         y = @pdf.cursor
393:         row(0).each do |cell|
394:           cell.y = y
395:           cell.draw
396:         end
397:         @pdf.move_cursor_to(y - row(0).height)
398:       end
399:     end
make_cells(data) click to toggle source

Converts the array of cellable objects given into instances of Prawn::Table::Cell, and sets up their in-table properties so that they know their own position in the table.

     # File lib/prawn/table.rb, line 352
352:     def make_cells(data)
353:       assert_proper_table_data(data)
355:       cells = []
357:       @row_length = data.length
358:       @column_length ={ |r| r.length }.max
360:       data.each_with_index do |row_cells, row_number|
361:         row_cells.each_with_index do |cell_data, column_number|
362:           cell = Cell.make(@pdf, cell_data)
363:           cell.extend(Cell::InTable)
364:           cell.row = row_number
365:           cell.column = column_number
366:           cells << cell
367:         end
368:       end
369:       cells
370:     end
natural_column_widths() click to toggle source

Returns an array of each column’s natural (unconstrained) width.

     # File lib/prawn/table.rb, line 403
403:     def natural_column_widths
404:       @natural_column_widths ||= (0...column_length).map { |c| column(c).width }
405:     end
natural_width() click to toggle source

Returns the “natural” (unconstrained) width of the table. This may be extremely silly; for example, the unconstrained width of a paragraph of text is the width it would assume if it were not wrapped at all. Could be a mile long.

     # File lib/prawn/table.rb, line 412
412:     def natural_width
413:       @natural_width ||= natural_column_widths.inject(0) { |sum, w| sum + w }
414:     end
position_cells() click to toggle source

Set each cell’s position based on the widths and heights of cells preceding it.

     # File lib/prawn/table.rb, line 437
437:     def position_cells
438:       # Calculate x- and y-positions as running sums of widths / heights.
439:       x_positions = column_widths.inject([0]) { |ary, x| 
440:         ary << (ary.last + x); ary }[0..2]
441:       x_positions.each_with_index { |x, i| column(i).x = x }
443:       # y-positions assume an infinitely long canvas starting at zero -- this
444:       # is corrected for in Table#draw, and page breaks are properly inserted.
445:       y_positions = row_heights.inject([0]) { |ary, y|
446:         ary << (ary.last - y); ary}[0..2]
447:       y_positions.each_with_index { |y, i| row(i).y = y }
448:     end
set_column_widths() click to toggle source

Assigns the calculated column widths to each cell. This ensures that each cell in a column is the same width. After this method is called, subsequent calls to column_widths and width should return the finalized values that will be used to ink the table.

     # File lib/prawn/table.rb, line 421
421:     def set_column_widths
422:       column_widths.each_with_index do |w, col_num| 
423:         column(col_num).width = w
424:       end
425:     end
set_row_heights() click to toggle source

Assigns the row heights to each cell. This ensures that every cell in a row is the same height.

     # File lib/prawn/table.rb, line 430
430:     def set_row_heights
431:       row_heights.each_with_index { |h, row_num| row(row_num).height = h }
432:     end

Disabled; run with --debug to generate this.


Generated with the Darkfish Rdoc Generator 1.1.6.