【问题标题】:How to convert existing html file to pdfs in rails 4?如何在rails 4中将现有的html文件转换为pdf?
【发布时间】:2016-08-23 11:29:54
【问题描述】:

我有一个 html 文件 generate_invoice.html.erb。我必须在同一个文件上提供一个按钮才能将 generate_invoice.html.erb 转换为可下载的 pdf。我尝试使用 wicked pdf gem 和 gem 'wkhtmltopdf-binary'

然后我还创建了 config/initializers/wicked_pdf.rb 并将 mime 类型设置为 pdf

我的路线如下:

match 'orders/:id/invoice'      => 'orders#order_invoice', as:   
'order_invoice', via: [:put,:post,:get]

我的order_controller如下

 def order_invoice
  @base_url = ENV['base_url']
  @order = Order.includes(:status, :user, payment: 
  [:status]).where(id: params[:id]).first
  if (['Notary', 'Attestation','Franking'].include? 
  @order.service.name)
    @no_of_copies = ((@order.answers.where(question_id: 
    [37,15]).length
    > 0) ? @order.answers.where(question_id: [37,15]).first.body : 
    0).to_i 
  else
    @no_of_copies = ((@order.answers.where(question_id: 
    [37,15]).length 
    > 0) ? @order.answers.where(question_id: [37,15]).first.body : 
    0).to_i + 1
  end

  render 'order_mailer/generate_invoice',layout: false
  respond_to do |format|
   format.pdf do
     render pdf: "order_invoice"
  end 
end

结束

但它会抛出此错误

ActionController::UnknownFormat at /admin/orders/131/invoice
ActionController::UnknownFormat

基本上它指向 respond_to do |format|

我做错了什么。请帮我纠正这个问题。也请告诉我下一步如何实现pdf格式

【问题讨论】:

  • 尝试在...之后添加format.html以及... |format|

标签: ruby-on-rails ruby pdf wicked-pdf


【解决方案1】:

我假设您的order_invoice 文件的格式为order_invoice.html.erb 而不是order_invoice.pdf.erb,这应该是正确的格式。

【讨论】:

    【解决方案2】:
    respond_to do |format|
      format.html
      format.pdf do
        render pdf: "order_invoice"   
      end
    end
    

    我希望你已经有了视图文件“order_invoice.html.erb”

    【讨论】:

    • 其实我这里要用到文件generate_invoice.html.erb。同样,现在我尝试了代码,它会为控制器抛出此错误:在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。另请注意,无论是重定向还是渲染都不会终止该操作的执行,因此如果您想在重定向后退出某个操作,则需要执行“redirect_to(...) and return”之类的操作。
    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2013-09-29
    • 2011-01-25
    • 2023-03-27
    • 1970-01-01
    • 2018-07-14
    • 2018-06-03
    • 2013-07-10
    相关资源
    最近更新 更多