Search code examples
ruby-on-railsprawn

Can I save a generated by prawn pdf file to the profect folder, using initialize method?


I have an OrderPdf class that inherits from Prawn::Document Here is the content of the class:

class OrderPdf < Prawn::Document
  include ActionView::Helpers::NumberHelper
  include ActionView::Helpers::TagHelper

  def initialize(order)
    super(top_margin: 50, size: 12)
    @order = order
    logo
    # Other methods that generate pdf's content
    footer
  end

  def logo
    # Some stuff here
  end

  def footer
    #Some stuff here
  end
end

I call it like this: OrderPdf.new(@order). Pdf file is generated, but what I need - is to save it into my project with the name, something like this: "#{Rails.root}/public/uploads/orders/order-#{order.order_number}.pdf" I know, that I can do this: Prawn::Document.generate("#{Rails.root}/public/uploads/orders/order-#{order.order_number}.pdf"), but can I do something simialar with the existing code? Thanks ahead.


Solution

  • You can call the render_file method in the initializer.

    def initialize(order)
      super(top_margin: 50, size: 12)
      @order = order
      logo
      # Other methods that generate pdf's content
      footer
      render_file "#{Rails.root}/public/uploads/orders/order-#{order.order_number}.pdf"
    end