1

I am using rails 5 and grape gem for building my application. Now I have a requirement of generating a PDF and send back to the response using grape endpoint. I am using wicked_pdf gem and wkhtmltopdf-binary for generate PDF. But I am facing the issue of undefined method 'render_to_string'. I have tried various way to resolve it. but couldn't find any solution.

Below is my code snippet

API Endpoint:

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

Gemfile:

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'

Config > initializers > mime_types.rb

Mime::Type.register "application/pdf", :pdf
hgsongra
  • 1,454
  • 15
  • 25

1 Answers1

1

Grape::API, don't have a render_to_string method that you can call on it, unlike a typical Rails controller. You should be able to replace that with something similar to this:

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)
Unixmonkey
  • 18,485
  • 7
  • 55
  • 78