Question

I'd like to instruct Prawn to truncate the contents of table cells instead of wrapping them.

I've tried setting the style as follows, but it has no effect:

options = {
  cell_style: {
    overflow: :truncate
  },
}
pdf.table(entries, options)

If there is no direct way to specify truncation, I need a workaround recipe.

Please consider the following:

  • I cannot truncate the strings themselves, because the font is not fixed-width
  • calculating the width of each string is acceptable, but I would also need a way to retrieve the column width.
Était-ce utile?

La solution

A fixed height could be used, but only if the height of the text is fixed. Only the first line of the text will be printed.

Example:

pdf.table(entries, :cell_style => {:height => 25})

Another option is to use a custom wrapper. Details are here:

https://github.com/prawnpdf/prawn/blob/master/lib/prawn/text/formatted/box.rb#L149

Example:

module MyWrap
  def wrap(array)
    initialize_wrap(array)
    @line_wrap.wrap_line(:document => @document,
                                  :kerning => @kerning,
                                  :width => available_width,
                                  :arranger => @arranger)
    if enough_height_for_this_line?
      move_baseline_down
      print_line
    end
    @text = @printed_lines.join("\n")
    @everything_printed = @arranger.finished?
    @arranger.unconsumed
  end
end

Prawn::Text::Formatted::Box.extensions << MyWrap

entries = [ ["very long text here", "another very long text here"] ]

Prawn::Document.generate("test.pdf") do
  table entries, :cell_style => { :inline_format => true }
end

I just copy the original wrap method and remove the while loop in order to print only the first line of the text.

Note that :inline_format => true must be used in order to get Prawn::Text::Formatted::Box working.

Autres conseils

http://prawn.majesticseacreature.com/docs/0.11.1/Prawn/Text/Formatted.html

That has a way to truncate text in a box with

formatted_text_box(array, options={})

But it's not a table. I don't think there is any way to do it with a table, you'll have to use textboxes.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top