Getting PDF from WickedPDF for attachment via Carrierwave
Asked Answered
W

2

17

In Rails3, I am using the WickedPDF gem to render a PDF format of one of my models. This is working fine: /invoices/123 returns HTML, /invoices/123.pdf downloads a PDF.

In my Invoice model, I am using the state_machine gem to keep track of Invoice status. When an invoice goes from "unbilled" to "billed" state, I would like to grab a copy of the invoice PDF and attach it to the invoice model using CarrierWave.

I have the three parts working separately: the controller creates a PDF view, the model tracks state and triggers a callback when making the correct transition, and CarrierWave is set up properly. However, I'm having a heck of a time getting them to play nicely together.

If I just wanted to grab the HTML version of the invoice, I could call render_to_string from the model. But render_to_string seems to choke on receiving a PDF binary file. If I can get a stream of data back, it's pretty easy to write that data to a tempfile and attach it to the uploader, but I can't figure out how to get the data stream.

Any thoughts? Code below:

Invoice controller

def show
  @invoice = @agg_class.find(params[:id])

  respond_to do |format|
    format.pdf do
      render_pdf
    end
    format.html # show.html.erb
    format.json { render json: @aggregation }
  end
end

...

def render_pdf(options = {})
  options[:pdf] = pdf_filename
  options[:layout] = 'pdf.html'
  options[:page_size] = 'Letter'
  options[:wkhtmltopdf] = '/usr/local/bin/wkhtmltopdf'
  options[:margin] = {
    :top      => '0.5in',
    :bottom   => '1in',
    :left     => '0in',
    :right    => '0in'
  }
  options[:footer] = {
    :html => {
      :template   => 'aggregations/footer.pdf.haml',
      :layout     => false,
    }
  }
  options[:header] = {
    :html => {
      :template   => 'aggregations/header.pdf.haml',
      :layout     => false,
    }
  }
  render options
end

Invoice.rb

def create_pdf_copy

   # This does not work.    
   pdf_file = ApplicationController.new.render_to_string(
    :action => 'aggregations/show',
    :format => :pdf,
    :locals => { 
      :invoice => self
    }
  )

  # This part works fine if the above works.
  unless pdf_file.blank?
    self.uploads.clear
    self.uploads.create(:fileinfo => File.new(pdf_file), :job_id => self.job.id)
  end

end

UPDATE Found a solution.

def create_pdf_copy

    wicked = WickedPdf.new

    # Make a PDF in memory
    pdf_file = wicked.pdf_from_string( 
        ActionController::Base.new().render_to_string(
            :template   => 'aggregations/show.pdf.haml', 
            :layout     => 'layouts/pdf.html.haml',
            :locals     => { 
                :aggregation => self
            } 
        ),
        :pdf => "#{self.type}-#{self}",
        :layout => 'pdf.html',
        :page_size => 'Letter',
        :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
        :margin => {
            :top      => '0.5in',
            :bottom   => '1in',
            :left     => '0in',
            :right    => '0in'
        },
        :footer => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/footer.pdf.haml', 
                :layout => false
            })
        },
        :header => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/header.pdf.haml', 
                :layout => false
            })
        }
    )

    # Write it to tempfile
    tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
    tempfile.binmode
    tempfile.write pdf_file
    tempfile.close

    # Attach that tempfile to the invoice
    unless pdf_file.blank?
        self.uploads.clear
        self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
        tempfile.unlink
    end

end
Warlord answered 7/2, 2013 at 4:16 Comment(4)
OK, I've got it working. Step 1 was working around the fact that WickedPDF ignores global config settings when not running in context of a controller. Step 2: use Tempfile to save the PDF output as a binary mode tempfile, then attach that to Carrierwave. Edited original post to reflect solution.Warlord
Can you please give me more details on step 1? I had an old version of wkhtmltopdf locally and was exporting with render_to_string just fine. On the server I have wkhtmltopdf 0.11.0, and render_to_string works but PDF is unreadable.. Upgraded to 0.11.0 locally and render_to_string chokes.. Seems to be the same problem you're having.. FYI: I use file = StringIO( render_to_string( options ) ) so I can skip the Tempfile. This is with paperclip, but you could give it a try if you like the idea.Yingyingkow
Glad you solved it. You should write up your solution as an answer, and then accept your answer. No harm in answering your own question!Batman
You should post your solution as an answer, and set it as the selected answer.Backwash
C
9

Solution:

def create_pdf_copy

    wicked = WickedPdf.new

    # Make a PDF in memory
    pdf_file = wicked.pdf_from_string( 
        ActionController::Base.new().render_to_string(
            :template   => 'aggregations/show.pdf.haml', 
            :layout     => 'layouts/pdf.html.haml',
            :locals     => { 
                :aggregation => self
            } 
        ),
        :pdf => "#{self.type}-#{self}",
        :layout => 'pdf.html',
        :page_size => 'Letter',
        :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
        :margin => {
            :top      => '0.5in',
            :bottom   => '1in',
            :left     => '0in',
            :right    => '0in'
        },
        :footer => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/footer.pdf.haml', 
                :layout => false
            })
        },
        :header => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/header.pdf.haml', 
                :layout => false
            })
        }
    )

    # Write it to tempfile
    tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
    tempfile.binmode
    tempfile.write pdf_file
    tempfile.close

    # Attach that tempfile to the invoice
    unless pdf_file.blank?
        self.uploads.clear
        self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
        tempfile.unlink
    end

end
Comptom answered 15/7, 2013 at 17:36 Comment(0)
E
2

There's a better way: PDF in Rails without controllers.

Evergreen answered 20/3, 2014 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.