Search code examples
ruby-on-railsrubyprawn

Prawn::Errors::CannotFit: Table's width was set too small to contain its contents


I am trying to create a table in Prawn using the following code however the columns widths do not suite well for me with columns width I have now. Given that I still have some free space, I want to expand a little bit the second and last columns so I increased both of them to 55.mm and 20.mm accordingly but I am getting an error

Prawn::Errors::CannotFit: Table's width was set too small to contain its contents (min width 450.70866141732284, requested 442).

Why does expanding a column width throws Tabe too small error?

I have calculated the total width of the columns:

9.mm + 45.mm + 20.mm + 20.mm + 20.mm + 30.mm + 15.mm + 20.mm #=> 507.40157480314963

I don't understand it. What am I doing wrong?

bounding_box [0, 792], width: 612, height: 792 do
  bounding_box [30, 792], width: 442, height: 792 do
    line_items_table
  end
end

def line_items_table
  table line_item_rows, table_options do
    row(0).background_color = TABLE_BACKGROUND_COLOR
    columns(2..-1).align = :right
  end
end

def table_options
  {
    cell_style: { border_width: 0 },
    column_widths: TABLE_COLUMN_WIDTHS,
    header: true,
    # width: 160.mm
  }
end

def line_item_rows
  [TABLE_HEADERS]
end

TABLE_COLUMN_WIDTHS = { 0 => 9.mm, 1 => 45.mm, 2 => 20.mm, 3 => 20.mm, 4 => 30.mm, 5 => 15.mm, 6 => 15.mm }.freeze

TABLE_HEADERS  = [I18n.t('pdf.headers.row_num'), I18n.t('pdf.headers.name'),
                       I18n.t('pdf.headers.quantity'), I18n.t('pdf.headers.price_net_amount'), I18n.t('pdf.headers.net_amount'),
                       I18n.t('pdf.headers.vat'), I18n.t('pdf.headers.gross_amount')].freeze
#Table headers above are: 'No', 'Name', 'Qauntity', 'Net Sale', 'Net amount', 'Gross amount', 'VAT'

Solution

  • Table's width was set too small to contain its contents (min width 450.7, requested 442) meaning your total column width must below 442, and your total currently is 450.7, you should change it to below 442

    you have line code that set 442

    bounding_box [30, 792], width: 442, height: 792 do
    

    if you want to set bigger then my suggestion you should change it first