Prawn::Table

repository·master·Indexed 42 days ago

https://github.com/prawnpdf/prawn-table

An experimental extension for the PrawnPDF library that provides advanced table generation capabilities. It allows developers to create structured tables within PDF documents using two-dimensional arrays of cellable objects, supporting nested subtables, image cells, and complex styling for rows, columns, and individual cells.

Tokens
3.6K
Snippets
16
Records
23
Agent score
53%

What's inside Prawn Table

  1. Install and use Prawn::Table

    master
    Prawn::Table is an extension for PrawnPDF that provides table support. It is currently considered an experimental extension and is not actively maintained by the core Prawn maintainers, though they are open to assisting with pull request integration.
  2. Generate the Prawn::Table manual

    master

    You can generate a local copy of the Prawn::Table manual by following these steps:

    1. Clone the repository.
    2. Run bundle to install dependencies.
    3. Run rake manual to generate the documentation.

    Additionally, all example files located in the manual folder can be run individually to see the library in action.

    bundle
    rake manual
  3. Important: Setting colspan and rowspan

    master

    When working with tables, colspan and rowspan must be provided as part of the table's data structure. You cannot set them inside an initialization block (e.g., within a pdf.table(...) { ... } block) because the layout engine has already run by that point.

    Correct way (in data):

    pdf.table([["foo", {:content => "bar", :colspan => 2}]])

    Incorrect way (in block):

    # This will raise Prawn::Errors::InvalidTableSpan
    pdf.table([["foo", "bar"]]) { |t| t.cells[0, 1].colspan = 2 }
  4. Nest a table within a table cell using Subtable

    master

    You can nest a table inside a cell of another table by providing a Prawn::Table instance as the :content option to a cell. This is handled internally by the Subtable class. When nesting, you can specify :padding for the subtable cell via the options hash.

    # Conceptual usage of nesting a table within a cell
    inner_table = Prawn::Table.new(pdf, ...)
    
    outer_table = Prawn::Table.new(pdf, {
      rows: [
        ["Cell 1", "Cell 2"],
        ["Nested Table Cell", inner_table] # Passing the table as content
      ]
    })
  5. How the Cells collection works for bulk styling

    master

    The Cells class represents a selection of cells. It acts as a proxy that allows you to set properties on all selected cells at once. You can chain selections (e.g., selecting specific rows AND specific columns) to target a rectangular area, or use filter to select cells based on custom logic.

    Chaining Selections

    To highlight a rectangular area, chain rows and columns:

    table.rows(1..3).columns(2..4).background_color = 'ff0000'

    Filtering Cells

    You can use the filter method to select cells that match a specific condition (e.g., based on content):

    table.column(4).filter { |cell| cell.content =~ /Yes/ }.background_color = '00ff00'

    Bulk Styling with style

    Use the style method to set multiple properties at once or pass a block for more complex logic:

    # Set multiple properties
    table.cells.style(padding: 0, border_width: 2)
    
    # Use a block for complex updates
    table.cells.style { |cell| cell.border_width += 12 }
    table.rows(1..3).columns(2..4).background_color = 'ff0000'
  6. How Prawn::Table::Cell handles content types

    master

    The Prawn::Table::Cell.make method automatically determines the appropriate subclass of Cell based on the type of content provided:

    • String: Creates a Cell::Text.
    • Prawn::Table: Creates a Cell::Subtable.
    • Array: Creates a Cell::Subtable by wrapping the array in a new Prawn::Table.
    • Hash with :image key: Creates a Cell::Image.
    • Cell instance: Uses the provided Prawn::Table::Cell object directly.

    If the content type is unrecognized, it raises Errors::UnrecognizedTableContent.

  7. Create and draw a table with `pdf.table`

    master

    Use the table method on a Prawn::Document instance to set up and immediately draw a table. The data argument must be a two-dimensional array of 'cellable' objects.

    Cellable objects include:

    • String: Creates a text cell.
    • Prawn::Table::Cell: Existing cell objects or custom subclasses.
    • Prawn::Table:: (via make_table): A subtable (a table within a cell).
    • Array: A simple subtable (use make_table if you need specific styling).

    You can pass an optional block to configure the table after cell setup but before layout and drawing.

    # Basic table usage
    pdf.table([['Header 1', 'Header 2'], ['Row 1 Col 1', 'Row 1 Col 2']])
    
    # Table with a configuration block
    pdf.table(data) do |table|
      table.rows(1..3).width = 72
    end
  8. Configure table layout and style options

    master

    When calling table or make_table, you can pass an options hash to control the table's appearance and behavior. Key options include:

    • cell_style: A hash of style options applied to all cells (e.g., :borders, :background_color).
    • header: If true, the first row is repeated on every page. If an Integer, the first x rows are repeated on every page.
    • column_widths: Sets widths for columns. Can be an Array [w0, w1, ...], a Hash {0 => w0, 1 => w1, ...}, or a Numeric to set all columns to the same width.
    • position: Horizontal alignment within the bounding box. Options are :left (default), :center, :right, or a Numeric representing points from the left edge.
    • row_colors: An Array of alternating colors used to stripe the rows.
  9. Handle Prawn::Table errors

    master

    The following errors may be raised during table operations:

    • Prawn::Errors::InvalidTableData: Raised when the provided data is not a two-dimensional array.
    • Prawn::Errors::EmptyTable: Raised when an empty or nil table is provided for rendering.
    • Prawn::Errors::UnrecognizedTableContent: Raised when unrecognized content is provided for a table cell.
    • Prawn::Errors::InvalidTableSpan: Raised when cell spans (rowspan/colspan) overlap.
    • Prawn::Errors::CannotFit: Raised when the requested table width is too small to contain its contents or too large compared to its maximum width.
  10. Style specific rows or columns in a table block

    master

    Inside a table initialization block, you can use the style method or direct attribute access to apply styles to specific subsets of the table (rows, columns, or individual cells).

    pdf.table(data) do
      # Style a specific row
      style(row(0), :background_color => 'ff00ff')
    
      # Style a specific column with a block
      column(0).style { |c| c.border_width += 1 }
    end
  11. Set the text color for a nested subtable

    master

    When using a Subtable (a table nested within a cell), you can set the text color for all cells within that subtable by calling text_color= on the subtable cell. This operation is proxied to the underlying subtable's cells.

    # Assuming 'cell' is a Subtable instance
    cell.text_color = "#FF0000"
  12. Create a subtable without drawing with `pdf.make_table`

    master

    Use make_table to initialize a Prawn::Table object without drawing it immediately. This is useful for creating subtables that will be inserted into cells of another table. You must explicitly call .draw on the resulting object to render it.

    subtable = pdf.make_table(subtable_data, options)
    # ... later ...
    subtable.draw