简体   繁体   中英

Automatically generating PDF's in ruby on rails

I'm currently working on a ruby on rails project. I need the system to automatically generate a PDF every 12 hours based off information from a data base.

Currently I'm looking at the prawn gem to generate the PDF's but I was wondering if there was a way to make this gem (or any other) produce the PDF every so many hours.

If you know how to generate PDFs via Ruby (using prawn or wicked_pdf ), there are only 2 steps left to take:

  1. Create a rake task, call it, like this:

     # lib/tasks/my_pdf_task.rake desc "Generate pdf" task :generate_pdf => :environment do MyPdfGenerator.new.generate end 
  2. Run it via cron, using whenever gem. After installing & initializing the gem, edit the config/schedule.rb :

     # config/schedule.rb every 3.hours do rake "generate_pdf" end 

Something like this can be achieved by using Wicked PDF . From my past understanding and your question it seems that you want to generate some sort of email that contains the attachment pdf. If I stand correctly you would have something like this in your mailer.

 def overtime_pdf(user, booking)
    @bookings = booking
    @user = user
    mail(:subject => 'Overtime', :to => user.email) do |format|
      format.text # renders overtime_pdf.text.erb for body of email
      format.pdf do
        attachments['bookings.pdf'] = WickedPdf.new.pdf_from_string(
            render_to_string(:pdf => 'overtime', :template =>
                'bookings/index.pdf.erb', :layouts => 'pdf.html')
        )
      end
    end
  end

Upon doing this if you are using heroku you can use heroku-scheduler . What you want to do is create a class method that take a user argument, then you can pass the user in the controller action and use this in the rake task. So you could have something like this.

Class

 def self.send_overtime_mail(user, bookings)
    BookingMailer.booking_pdf(user, bookings).deliver
  end

Rake task

task :overtime_report => :environment do
  every 3.hours do
    user = User.where(:role => :administrator).first
    bookings = Bookings.where(:day => Date.today.beginning_of_month..Date.today.end_of_month)
    Booking.send_overtime_mail(user, bookings)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM