Rails 4 wicked_pdf generate blank pdf while generating from model

3k views Asked by At

I'm trying to save pdf on server using rails model buts its generate a blank pdf. Earlier did it in controller without problem but now its creating a blank one. Any idea What's i did wrong?

def generate_bulk_pdf
  view = ActionView::Base.new(ActionController::Base.view_paths, {})
  view.extend(ApplicationHelper)
  view.extend(AbstractController::Rendering)
  view.extend(Rails.application.routes.url_helpers)
  students = Student.all.order('id ASC')
    students.each do | aStudent |
    pdf = WickedPdf.new.pdf_from_string(
       view.render_to_string(
         :template => "#{Rails.root.join('templates/challen.pdf.erb')}",
         :locals => { '@student' => aStudent }
       )
    )
    save_path = Rails.root.join('pdfs','filename.pdf')
    File.open(save_path, 'wb') do |file|
      file << pdf
    end
  end
end

Any idea What's i did wrong? I can't find any solution

1

There are 1 answers

1
Mr H On BEST ANSWER

A good test is just put a simple line of text in your template and see if you get a PDF with that line. Strip everything back so you just generating a PDF with no coming locals, just that 1 string and let me know.

Here is how I set up mine and it works fine, it might click something :)

 def generate_pdf_voucher(voucher, dir_name)
    view = ActionView::Base.new(Rails.root.join('app/views'))
    view.class.include ApplicationHelper
    view.class.include Rails.application.routes.url_helpers

    pdf = view.render :pdf => a_name,
                      :template => 'layouts/pdfs/voucher_pdf',
                      :layout => 'layouts/pdfs/pdf.html.erb',
                      :header => {:right => '[page] of [topage]'},
                      :locals => {:@voucher => voucher}
    # then save to a file
    pdf = WickedPdf.new.pdf_from_string(pdf)

    save_path = Rails.root.join('public', 'pdfs', dir_name, "#{voucher[:user].id.to_s}.pdf")
    File.open(save_path, 'wb') do |file|
      file << pdf
    end
end

pdf.html.erb is the structure of the PDF voucher_pdf is all the dynamic stuff

If this wasn't helpful, then put a comment on and I will delete it.