Skip to content

Prawn Table Example

Ben Koshy edited this page Mar 19, 2019 · 12 revisions

Example of How to Set up a Prawn Table in Rails

Add to gemfile:

    gem 'prawn'
    gem 'prawn-table'

In config/initializers/mime_types.rb

     Mime::Type.register "application/pdf", :pdf

run bundle install

Create the pdfs directory and the invoice_pdf.rb document (rename it to suit your needs):

	app/pdfs/invoice_pdf.rb

Go to the relevant controller and add in the relevant code. Here is mine:

def show
  @invoice = Invoice.find(params[:id])
  @jobs = Job.where(invoice: @invoice)

  respond_to do |format|
    format.html
    format.xlsx 
    format.pdf do
      pdf = InvoicePdf.new(@jobs)
      send_data pdf.render, filename: "Invoice #{@invoice.invoice_no}", type: "application/pdf", disposition: "inline"
    end
  end
end

Here is my invoice_pdf.rb ruby file

require 'prawn'
class InvoicePdf < Prawn::Document
  def initialize(jobs, invoice)
    super(top_margin: 70)
    @jobs = jobs
    @invoice = invoice
    table client_information
  end

  def client_information
    [[supplier_name = @jobs.first.level.building.project.client.supplier.name],
     [supplier_address = @jobs.first.level.building.project.client.supplier.address],
     [supplier_abn_acn = @jobs.first.level.building.project.client.supplier.abn_acn]]
  end
end

And as for the specifics of creating tables:

The documentation for prawn table manual is very, very good.

I hope this helps someone.

Clone this wiki locally