【问题标题】:How to generate PDF in Rails 5 Grape API endpoint and send in response?如何在 Rails 5 Grape API 端点中生成 PDF 并发送响应?
【发布时间】:2017-10-30 11:09:51
【问题描述】:

我正在使用rails 5grape gem 来构建我的应用程序。现在我需要生成 PDF 并使用 grape 端点发送回响应。我正在使用 wicked_pdf gem 和 wkhtmltopdf-binary 生成 PDF。但我面临undefined method 'render_to_string' 的问题。 我尝试了各种方法来解决它。但找不到任何解决方案。

下面是我的代码sn-p

API 端点:

module Endpoints
  class GeneratePdf < Grape::API
    get do
      users = User.all # I want this users list in my PDF
      pdf = WickedPdf.new.pdf_from_string(render_to_string('users/index.html.erb')) # placed in app/views/users/pdf.html.erb
      # some code here for send pdf back to response
    end
  end
end

宝石文件:

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'

配置 > 初始化程序 > mime_types.rb

Mime::Type.register "application/pdf", :pdf

【问题讨论】:

    标签: pdf ruby-on-rails-5 wkhtmltopdf wicked-pdf grape-api


    【解决方案1】:

    Grape::API,不像典型的 Rails 控制器,没有可以调用的render_to_string 方法。你应该可以用类似的东西替换它:

    require 'erb'
    binding_copy = binding
    binding_copy.local_variable_set(users: User.all)
    template = File.open(Rails.root.join('app/views/users/index.html.erb))
    string = ERB.new(template).result(binding_copy)
    pdf = WickedPdf.new.pdf_from_string(string)
    

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      相关资源
      最近更新 更多