Reusing content in multiple Prawn PDFs

Let’s say you have two Prawn PDFs. Both will need similar headers, footers, titles, company logos, etc., but you want to avoid duplicating code.

As far as I know, there is no such thing as a ‘partial’ in Prawn. There used to be a feature called a ‘template’, but it is no longer in the core Prawn library. It was extracted into the prawn-templates gem and is not currently maintained.

My approach to this is to put shared content into modules, then mix the modules into each Prawn::Document class that needs them. For instance, as such:


# in config/application.rb
config.autoload_paths << "#{Rails.root}/app/prawn/helpers"

# in app/prawn/helpers/prawn_report_header_helper.rb
module PrawnReportHeaderHelper
  def shared_report_head
    image "#{Rails.root}/app/assets/images/#{@company.logo_path}.jpg", width: 187.5, height: 92.25
    move_up 15
    text "#{@report_type} earnings report"
    move_down 5
    stroke_horizontal_rule
    move_down 20
    text @company.name
  end
end

# in app/prawn/yearly_earnings_pdf.rb
class YearlyEarningsPdf < Prawn::Document
  include PrawnReportHeaderHelper

  def initialize(company)
    super()
    @company = company
    @type = 'Yearly'
    shared_report_head
    # ...
    # all the other stuff we need
    # ...
  end
end

# in app/prawn/monthly_earnings_pdf.rb
class MonthlyEarningsPdf < Prawn::Document
  include PrawnReportHeaderHelper

  def initialize(company)
    super()
    @company = company
    @type = 'Monthly'
    shared_report_head
    # ...
    # all the other stuff we need
    # ...
  end
end

This is a very simplistic example just to illustrate the general pattern. But the real benefits come when the documents are more complex.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: