gpt4 book ai didi

ruby-on-rails - 使用 render_to_string 从模型方法导出 PDF

转载 作者:太空宇宙 更新时间:2023-11-03 16:07:00 25 4
gpt4 key购买 nike

我需要在我的 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.hamlrender_to_string,它在模型中不可访问(仅在 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 操作并从模型中调用它(但不工作,说即使在 Controller 中调用 render_to_string 也未定义)
  • 将我的工作 export_to_pdf 方法与从我的模型发送的获取请求一起使用(但我发现我无法真正从模型发送请求...)
  • 使用内部带有 render_to_string 的 Helper(不工作:未定义的方法)
  • 甚至更多!

但还是不行。

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

最佳答案

啊,我终于做到了!

感谢您的回答,肖恩,但我不是在寻找更好的 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 和链接的 set_option、logoimage 等,然后返回 pdf.generate

我希望有一天这可以帮助某个人!

关于ruby-on-rails - 使用 render_to_string 从模型方法导出 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11995644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com