我需要在我的 ProjectBill 模型上实现 _to_pdf 方法,该方法在此处生成我的账单的 PDF:
/public/xls/bills/project_#{project.number}_bill_#{bill.number}.pdf
我的应用程序正在使用 HTMLDoc 生成 PDF。我正在使用Rails 2.3.11。使用 HTMLDoc gem,我需要将部分 View _bill.pdf.haml 的 render_to_string 传递给模型,该 View 在模型中无法访问(仅在 Controller 中) HTML 文档。
我的 Controller 中已经有一个export_to_pdf操作,由用户在想要导出时触发(这个有效)。该模型方法将由计划任务调用,当 Scheduled_date 等于 Date.today 时,电子邮件发送器会发送账单。
我已经尝试过很多解决方案:
- http://www.omninerd.com/articles/render_to_string_in_Rails_Models_or_Rake_Tasks/print_friendly
- 在我的 ProjectBill Controller 上有一个 to_pdf 操作,并从模型中调用它(但不起作用,说 render_to_string 未定义,即使它在 Controller 中调用)
- 将我的工作export_to_pdf方法与从我的模型发送的get请求一起使用(但我发现我无法真正从模型发送请求......)
- 使用内部包含 render_to_string 的 Helper(不起作用:未定义的方法)
- 甚至更多!
但仍然无法正常工作。
有人可以帮我解决这个问题吗?我陷入困境,找不到任何解决方案......
最佳答案
啊啊我终于做到了!
感谢您的回答 Sean,但我并不是在寻找更好的 Gem,我只是在寻找问题的解决方案。
出于某种原因,我无法在模型中使用 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
如您所见,我在模型中调用了 Controller 。这是我的 _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 和链接、 logoimage 等的 set_option 并返回 pdf.generate
我希望有一天这可以帮助某人!
关于ruby-on-rails - 使用 render_to_string 从模型方法导出 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11995644/