Class: Prawn::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/prawn/table.rb,
lib/prawn/table/cell.rb,
lib/prawn/table/cells.rb,
lib/prawn/table/version.rb,
lib/prawn/table/cell/text.rb,
lib/prawn/table/cell/image.rb,
lib/prawn/table/cell/in_table.rb,
lib/prawn/table/cell/subtable.rb,
lib/prawn/table/cell/span_dummy.rb,
lib/prawn/table/column_width_calculator.rb

Overview

Next-generation table drawing for Prawn.

Data

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

String

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

Prawn::Table::Cell

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.

Prawn::Table

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.

Array

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

Options

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:

cell_style

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

header

If set to true, the first row will be repeated on every page. If set to an Integer, the first x rows will be repeated on every page. 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.

column_widths

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.

position

Either :left (the default), :center, :right, or a number. Specifies the horizontal position of the table within its bounding box. If a number is provided, it specifies the distance in points from the left edge.

Initializer Block

If a block is passed to methods that initialize a table (Prawn::Table.new, 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
end

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
end

Defined Under Namespace

Modules: Interface Classes: Cell, Cells, ColumnWidthCalculator

Constant Summary collapse

VERSION =
'0.2.2'.freeze

Experimental API collapse

Experimental API collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, document, options = {}, &block) ⇒ Table

Set up a table on the given document. Arguments:

data

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.

document

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

options

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



137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/prawn/table.rb', line 137

def initialize(data, document, options={}, &block)
  @pdf = document
  @cells = make_cells(data)
  @header = false
  options.each { |k, v| send("#{k}=", v) }

  if block
    block.arity < 1 ? instance_eval(&block) : block[self]
  end

  set_column_widths
  set_row_heights
  position_cells
end

Instance Attribute Details

#cellsObject (readonly)

Returns a Prawn::Table::Cells object representing all of the cells in this table.



172
173
174
# File 'lib/prawn/table.rb', line 172

def cells
  @cells
end

#column_lengthObject (readonly)

Number of columns in the table.



158
159
160
# File 'lib/prawn/table.rb', line 158

def column_length
  @column_length
end

#header=(value) ⇒ Object (writeonly)

If true, designates the first row as a header row to be repeated on every page. If an integer, designates the number of rows to be treated as a header Does not change row numbering – row numbers always index into the data array provided, with no modification.



224
225
226
# File 'lib/prawn/table.rb', line 224

def header=(value)
  @header = value
end

#position=(value) ⇒ Object (writeonly)

Position (:left, :right, :center, or a number indicating distance in points from the left edge) of the table within its parent bounds.



167
168
169
# File 'lib/prawn/table.rb', line 167

def position=(value)
  @position = value
end

#row_colors=(value) ⇒ Object (writeonly)

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



228
229
230
# File 'lib/prawn/table.rb', line 228

def row_colors=(value)
  @row_colors = value
end

#row_lengthObject (readonly)

Number of rows in the table.



154
155
156
# File 'lib/prawn/table.rb', line 154

def row_length
  @row_length
end

#widthObject

Returns the width of the table in PDF points.



185
186
187
# File 'lib/prawn/table.rb', line 185

def width
  @width ||= [natural_width, @pdf.bounds.width].min
end

Instance Method Details

#before_rendering_page(&block) ⇒ Object

Specify a callback to be called before each page of cells is rendered. The block is passed a Cells object containing all cells to be rendered on that page. You can change styling of the cells in this block, but keep in mind that the cells have already been positioned and sized.



179
180
181
# File 'lib/prawn/table.rb', line 179

def before_rendering_page(&block)
  @before_rendering_page = block
end

#cell_style=(style_hash) ⇒ Object

Sets styles for all cells.

pdf.table(data, :cell_style => { :borders => [:left, :right] })


234
235
236
# File 'lib/prawn/table.rb', line 234

def cell_style=(style_hash)
  cells.style(style_hash)
end

#column_widthsObject

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.



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/prawn/table.rb', line 327

def column_widths
  @column_widths ||= begin
    if width - cells.min_width < -Prawn::FLOAT_PRECISION
      raise Errors::CannotFit,
        "Table's width was set too small to contain its contents " +
        "(min width #{cells.min_width}, requested #{width})"
    end

    if width - cells.max_width > Prawn::FLOAT_PRECISION
      raise Errors::CannotFit,
        "Table's width was set larger than its contents' maximum width " +
        "(max width #{cells.max_width}, requested #{width})"
    end

    if width - natural_width < -Prawn::FLOAT_PRECISION
      # Shrink the table to fit the requested width.
      f = (width - cells.min_width).to_f / (natural_width - cells.min_width)

      (0...column_length).map do |c|
        min, nat = column(c).min_width, natural_column_widths[c]
        (f * (nat - min)) + min
      end
    elsif width - natural_width > Prawn::FLOAT_PRECISION
      # Expand the table to fit the requested width.
      f = (width - cells.width).to_f / (cells.max_width - cells.width)

      (0...column_length).map do |c|
        nat, max = natural_column_widths[c], column(c).max_width
        (f * (max - nat)) + nat
      end
    else
      natural_column_widths
    end
  end
end

#column_widths=(widths) ⇒ Object

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

Array

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

Hash

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

Numeric

72 (sets width for all columns)



200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/prawn/table.rb', line 200

def column_widths=(widths)
  case widths
  when Array
    widths.each_with_index { |w, i| column(i).width = w }
  when Hash
    widths.each { |i, w| column(i).width = w }
  when Numeric
    cells.width = widths
  else
    raise ArgumentError, "cannot interpret column widths"
  end
end

#columns(col_spec) ⇒ Object Also known as: column

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



22
23
24
# File 'lib/prawn/table/cells.rb', line 22

def columns(col_spec)
  cells.columns(col_spec)
end

#drawObject

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



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/prawn/table.rb', line 259

def draw
  with_position do
    # Reference bounds are the non-stretchy bounds used to decide when to
    # flow to a new column / page.
    ref_bounds = @pdf.reference_bounds

    # Determine whether we're at the top of the current bounds (margin box or
    # bounding box). If we're at the top, we couldn't gain any more room by
    # breaking to the next page -- this means, in particular, that if the
    # first row is taller than the margin box, we will only move to the next
    # page if we're below the top. Some floating-point tolerance is added to
    # the calculation.
    #
    # Note that we use the actual bounds, not the reference bounds. This is
    # because even if we are in a stretchy bounding box, flowing to the next
    # page will not buy us any space if we are at the top.
    #
    # initial_row_on_initial_page may return 0 (already at the top OR created
    # a new page) or -1 (enough space)
    started_new_page_at_row = initial_row_on_initial_page

    # The cell y-positions are based on an infinitely long canvas. The offset
    # keeps track of how much we have to add to the original, theoretical
    # y-position to get to the actual position on the current page.
    offset = @pdf.y

    # Duplicate each cell of the header row into @header_row so it can be
    # modified in before_rendering_page callbacks.
    @header_row = header_rows if @header

    # Track cells to be drawn on this page. They will all be drawn when this
    # page is finished.
    cells_this_page = []

    @cells.each do |cell|
      if start_new_page?(cell, offset, ref_bounds) 
        # draw cells on the current page and then start a new one
        # this will also add a header to the new page if a header is set
        # reset array of cells for the new page
        cells_this_page, offset = ink_and_draw_cells_and_start_new_page(cells_this_page, cell)

        # remember the current row for background coloring
        started_new_page_at_row = cell.row
      end

      # Set background color, if any.
      cell = set_background_color(cell, started_new_page_at_row)

      # add the current cell to the cells array for the current page
      cells_this_page << [cell, [cell.relative_x, cell.relative_y(offset)]]
    end

    # Draw the last page of cells
    ink_and_draw_cells(cells_this_page)

    @pdf.move_cursor_to(@cells.last.relative_y(offset) - @cells.last.height)
  end
end

#heightObject

Returns the height of the table in PDF points.



215
216
217
# File 'lib/prawn/table.rb', line 215

def height
  cells.height
end

#row_heightsObject

Returns an array with the height of each row.



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/prawn/table.rb', line 365

def row_heights
  @natural_row_heights ||=
    begin
      heights_by_row = Hash.new(0)
      cells.each do |cell|
        next if cell.is_a?(Cell::SpanDummy)

        # Split the height of row-spanned cells evenly by rows
        height_per_row = cell.height.to_f / cell.rowspan
        cell.rowspan.times do |i|
          heights_by_row[cell.row + i] =
            [heights_by_row[cell.row + i], height_per_row].max
        end
      end
      heights_by_row.sort_by { |row, _| row }.map { |_, h| h }
    end
end

#rows(row_spec) ⇒ Object Also known as: row

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



14
15
16
# File 'lib/prawn/table/cells.rb', line 14

def rows(row_spec)
  cells.rows(row_spec)
end

#style(stylable, style_hash = {}, &block) ⇒ Object

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 }
end

is equivalent to:

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


253
254
255
# File 'lib/prawn/table.rb', line 253

def style(stylable, style_hash={}, &block)
  stylable.style(style_hash, &block)
end