使用render_to_string从Model方法导出PDF

时间:2012-08-16 21:23:17

标签: ruby-on-rails ruby pdf rendering htmldoc

我需要在我的ProjectBill模型上实现一个_to_pdf方法,该方法在这个地方生成我的账单的PDF:

/public/xls/bills/project_#{project.number}_bill_#{bill.number}.pdf

我的应用程序使用HTMLDoc生成PDF。我正在使用 Rails 2.3.11 。使用HTMLDoc gem,我需要传递部分视图 _bill.pdf.haml render_to_string ,在模型中无法访问(仅在控制器中), HTMLDOC。

我的控制器中已经有一个export_to_pdf操作,由用户在他想要导出时触发(这个有效)。模型方法将由计划任务调用,电子邮件发送者在scheduled_date等于Date.today时发送账单。

我已经尝试了很多解决方案:

  • http://www.omninerd.com/articles/render_to_string_in_Rails_Models_or_Rake_Tasks/print_friendly
  • 在我的ProjectBill控制器上执行to_pdf操作并从模型中调用它(但不起作用,说即使在Controller中调用了render_to_string也没有定义)
  • 使用我的工作export_to_pdf方法和我的模型发送的get请求(但我发现我无法真正从模型发送请求...)
  • 使用其中包含render_to_string的Helper(不工作:未定义的方法)
  • 甚至更多!

但仍然无法正常工作。

有人可以帮我解决这个问题吗?我卡住了,找不到任何解决方案......

1 个答案:

答案 0 :(得分:2)

啊,我终于做到了!

感谢您的回答肖恩,但我并不是在寻找更好的宝石,我正在寻找解决问题的方法。

由于某种原因,我无法在我的模型中使用render_to_string方法... 所以我在我的模型上创建了我的export_to_pdf方法:

  def export_to_pdf
    bill = self
    project = self.project

    path = "facture_#{self.project.id}_#{self.bill_number}_#{Date.today.strftime('%Y_%m_%d')}.pdf"

    Plus::BillingItemsController.new._to_pdf(bill.id)

    if File.exists?(path)
      return path
    else
      return nil
    end
  end

如你所见,我在我的模型中调用我的控制器。这是我的_to_pdf方法:

 def _to_pdf(bill_id)
    @bill = Plus::ProjectBill.find_by_id(bill_id)
    @project = @bill.project
    path = "#{RAILS_ROOT}/public/xls/facture_#{@project.id}_#{@bill.bill_number}_#{Date.today.strftime('%Y_%m_%d')}.pdf"

    av = ActionView::Base.new(Rails::Configuration.new.view_path)
    av.class_eval do
      include ApplicationHelper
      include ActionController::UrlWriter
      default_url_options[:host] = 'mysite.com'
    end

    av.extend ApplicationController.master_helper_module
    html = av.render(:partial => "/plus/billing_items/bill_for_pdf.haml", :locals => {:bill => @bill})
    data = to_pdf(html, false, {:header => '', :headfootsize => 0, :outfile => path})
  end

我的to_pdf函数正在执行PDF :: HTMLDoc.new以及link_option的链接,logoimage等,并返回pdf.generate

我希望有一天能在某个地方为某人提供帮助!