6
votes

I'm making a little script with ruby which produces a week schedule PDF file, using Prawn as a PDF library and I'm struggling with styling the table. I'd like to set a static width for all the columns in the table so that the widths wouldn't depend on the contents of the cells.

I've read the documentation (lot of room for improvement there) from the Prawn project site and googled for a few hours, but I'm lost at how to set width for columns or cells in a table, or how to style the columns/cells in any way whatsoever. I do get a PDF file which has a grid layout though, the cells just vary in size a lot, which doesn't look that neat.

This didn't work:

Prawn::Document.generate(@filename, :page_size => 'A4', :page_layout => :landscape) do
  table(course_matrix, :headers => HEADERS, :border_style => :grid, :row_colors => ['dddddd', 'eeeeee'], :column_widths => 50)
end

Here's the current version of my method to generate PDF, but it doesn't stylize the cells either:

def produce_pdf
  course_matrix = DataParser.new.parse_for_pdf

  Prawn::Document.generate(@filename, :page_size => 'A4', :page_layout => :landscape) do
    table(course_matrix, :headers => HEADERS, :border_style => :grid, :row_colors => ['dddddd', 'eeeeee']) do |table|
      table.cells.style { |cell| cell.width = 50 }
    end
  end
end
2
If you're not happy with Prawn's documentation, contribute. - Tass

2 Answers

13
votes

I do something like this:

pdf = Prawn::Document.new(
  :page_size => 'A4',
  :page_layout => :landscape,
  :margin => [5.mm])
  ....
  .... 
  pdf.table(tbl_data) do
    row(0).style(:background_color => 'dddddd', :size => 9, :align => :center, :font_style => :bold)
    column(0).style(:background_color => 'dddddd', :size => 9, :padding_top => 20.mm, :font_style => :bold)
    row(1).column(1..7).style(:size => 8, :padding => 3)
    cells[0,0].background_color = 'ffffff'
    row(0).height = 8.mm
    row(1..3).height = 45.mm
    column(0).width = 28.mm
    column(1..7).width = 35.mm
    row(1..3).column(6..7).borders = [:left, :right]
    row(3).column(6..7).borders = [:left, :right, :bottom]
  ....
 pdf.render()

More info here.

0
votes

To set a static width for all the columns I do something like this:

REPORT_FIELDS = %w[DESCRIPTION PRICE DATE NOTE].freeze
A4_SIZE = 200.freeze

data = []
data << REPORT_FIELDS
... things happen ...
table(data, column_widths: (A4_SIZE/REPORT_FIELDS.size).mm))

In this case I wanted to set the table to fit the full page and with the cells with the same width.