Last active
July 13, 2021 21:28
-
-
Save jfeust/973267 to your computer and use it in GitHub Desktop.
Mock Table with Images in Prawn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# NOTE: Prawn 1.0 now supports images in tables, and it works much better than my mock table below! | |
# As you may have noticed Prawn does not currently support images in table cells. | |
# There is an unofficial fork with initial table image support but it appears that | |
# it will be some time before this gets merged into the official branch. | |
# | |
# Instead of using an unofficial branch, I found a nice way to do a mock table with | |
# image support. You just need to keep track of your page breaks. | |
# size values | |
cell_width = 90 | |
row_height = 80 | |
# Build an array with your table data | |
pieces = @pieces_to_report.map do |piece| | |
[ | |
piece.image.url(:thumb), | |
piece.name, | |
piece.inventory_number, | |
piece.medium, | |
piece.size_str, | |
number_to_currency(piece.price, :unit => "$") | |
] | |
end | |
# Column Header Values | |
header = ['', 'Name', 'Inv #', 'Medium','Size', 'Price'] | |
pdf.bounding_box [0, pdf.cursor], :width => 500, :height => 20 do | |
header.each_with_index do |head,i| | |
pdf.bounding_box [cell_width*i,0], :width => cell_width do | |
pdf.text head, :size => 10 | |
end | |
end | |
end | |
pdf.move_down 15 | |
# Build the Mock Table | |
pieces.each_with_index do |p,i| | |
pdf.bounding_box [0, pdf.cursor], :height => row_height, :width => 500 do | |
pdf.stroke do | |
pdf.line pdf.bounds.top_left, pdf.bounds.top_right | |
pdf.line pdf.bounds.bottom_left, pdf.bounds.bottom_right | |
end | |
pdf.move_down 5 # a bit of padding | |
cursor = pdf.cursor # keep current cursor value for all cells in this row | |
p.each_with_index do |v, j| | |
pdf.bounding_box [cell_width*j, cursor], :height => row_height, :width => cell_width do | |
if j == 0 # handle image column | |
# might want logic here to handle empty/nil images | |
pdf.image open(v), :scale => 0.6 | |
else | |
pdf.text v, :size => 10 unless v.blank? | |
end | |
end | |
end | |
end | |
# create a new page every 5 rows | |
pdf.start_new_page if i > 0 && i % 5 = 0 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You right! just pdf.image v worked fine! Thank you again!