-
Notifications
You must be signed in to change notification settings - Fork 117
PDF Export
Brendon Muir edited this page Dec 23, 2017
·
4 revisions
Datagrid provides you a table like structure with data:
report = MyGrid.new
report.header # => ["Group", "Name", "Activated"]
report.rows # => [
# ["Steve", "Spammers", true],
# [ "John", "Spoilers", true],
# ["Berry", "Good people", false]
# ]
report.data # => [ header, *rows]
You can use this data for export.
There are some gems available that can give you export.
Easy way (using ruport):
require 'ruport' # gem install ruport
f = File.new("report.pdf", "w")
f.write Ruport::Data::Table.new(:column_names =>report.header, :data => report.rows).to_pdf
f.close
Ruport doesn't really work with Ruby 1.9+ because of some of its PDF dependencies. It turns out PrawnPDF can easily be used to generate a report instead:
gem 'prawn'
It's best to have a base report class. I put the PDF classes under /app/prawn
. You'll need to restart your app for the directory to be autoloaded.
class PdfReport < Prawn::Document
TABLE_ROW_COLORS = ["FFFFFF","DDDDDD"]
TABLE_FONT_SIZE = 9
def initialize(default_prawn_options={})
super(default_prawn_options)
font_size 10
end
def header(title=nil)
text title, size: 18, style: :bold, align: :center if title
end
end
Then create your custom report class:
class IdentitiesPdfReport < PdfReport
def initialize(title, header=[], rows=[])
super()
@header = header
@rows = rows
header title
display_table
end
private
def display_table
if @rows.empty?
text "No Identities Found"
else
table @rows.unshift(@header),
header: true,
width: bounds.width,
row_colors: TABLE_ROW_COLORS,
cell_style: { size: TABLE_FONT_SIZE }
end
end
end
Then in your controller:
respond_to do |format|
format.html
format.csv do
...
end
format.pdf do
send_data IdentitiesPdfReport.new(@title, @grid.header, @grid.rows).render,
type: "application/pdf",
disposition: 'attachment',
filename: "identities-#{Time.current.to_s}.pdf"
end
end
Works a treat!
Hard way with custom formatting: https://github.com/mileszs/wicked_pdf