Prawn::Table
repository·master·Indexed 42 days ago
https://github.com/prawnpdf/prawn-tableAn 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.
What's inside Prawn Table
- 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.
Generate the Prawn::Table manual
masterYou can generate a local copy of the Prawn::Table manual by following these steps:
- Clone the repository.
- Run
bundleto install dependencies. - Run
rake manualto generate the documentation.
Additionally, all example files located in the
manualfolder can be run individually to see the library in action.bundle rake manualImportant: Setting colspan and rowspan
masterWhen working with tables,
colspanandrowspanmust be provided as part of the table's data structure. You cannot set them inside an initialization block (e.g., within apdf.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 }Nest a table within a table cell using Subtable
masterYou can nest a table inside a cell of another table by providing a
Prawn::Tableinstance as the:contentoption to a cell. This is handled internally by theSubtableclass. When nesting, you can specify:paddingfor 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 ] })How the Cells collection works for bulk styling
masterThe
Cellsclass 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 usefilterto select cells based on custom logic.Chaining Selections
To highlight a rectangular area, chain
rowsandcolumns:table.rows(1..3).columns(2..4).background_color = 'ff0000'Filtering Cells
You can use the
filtermethod 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
styleUse the
stylemethod 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'How Prawn::Table::Cell handles content types
masterThe
Prawn::Table::Cell.makemethod automatically determines the appropriate subclass ofCellbased on the type of content provided:- String: Creates a
Cell::Text. - Prawn::Table: Creates a
Cell::Subtable. - Array: Creates a
Cell::Subtableby wrapping the array in a newPrawn::Table. - Hash with
:imagekey: Creates aCell::Image. - Cell instance: Uses the provided
Prawn::Table::Cellobject directly.
If the content type is unrecognized, it raises
Errors::UnrecognizedTableContent.- String: Creates a
Create and draw a table with `pdf.table`
masterUse the
tablemethod on aPrawn::Documentinstance to set up and immediately draw a table. Thedataargument 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::(viamake_table): A subtable (a table within a cell).Array: A simple subtable (usemake_tableif 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 endConfigure table layout and style options
masterWhen calling
tableormake_table, you can pass anoptionshash 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: Iftrue, the first row is repeated on every page. If anInteger, the firstxrows are repeated on every page.column_widths: Sets widths for columns. Can be anArray[w0, w1, ...], aHash{0 => w0, 1 => w1, ...}, or aNumericto set all columns to the same width.position: Horizontal alignment within the bounding box. Options are:left(default),:center,:right, or aNumericrepresenting points from the left edge.row_colors: AnArrayof alternating colors used to stripe the rows.
Handle Prawn::Table errors
masterThe 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 orniltable 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.
Style specific rows or columns in a table block
masterInside a table initialization block, you can use the
stylemethod 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 } endSet the text color for a nested subtable
masterWhen using a
Subtable(a table nested within a cell), you can set the text color for all cells within that subtable by callingtext_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"Create a subtable without drawing with `pdf.make_table`
masterUse
make_tableto initialize aPrawn::Tableobject without drawing it immediately. This is useful for creating subtables that will be inserted into cells of another table. You must explicitly call.drawon the resulting object to render it.subtable = pdf.make_table(subtable_data, options) # ... later ... subtable.draw