I am trying to download an HTML view in Rails5 as a PDF, however, whenever I download the PDF I get an error: Failed to load PDF document. I am using the following gems:
gem 'pdf kit' gem 'wkhtmltopdf-binary'
here is my controller:
class InputController < ApplicationController
def index
@inputs = Input.all
end
def show
@input = Input.find_by(id: params[:id])
send_data @pdf, :filename => @input.company + ".pdf",
:type => "application/pdf",
:disposition => "attachment"
end
end
when i type in a download URL ie: localhost:3000/input/1.pdf i get a downloaded pdf file with an error:
My show view is very simple:
<ul>
<li><%= @input.company %></li>
<li><%= @input.position %></li>
<li><%= @input.date %></li>
</ul>
Any help would be appreciated.
Best, Ayaz
UPDATE
I also just tried taking out @pdf and putting in @input:
def show
@input = Input.find_by(id: params[:id])
send_data @input, :filename => @input.company + ".pdf",
:type => "application/pdf",
:disposition => "attachment"
end
No change in results
Your code doesn't assign anything to the instance variable
@pdf
:and instance variables have a default value of
nil
. You need to do something like:Or, if you want to read the view file then run it through the ERB engine, something like this:
From the Rails Guide:
And from the docs for send_data():
Therefore, when you call
send_data()
in the controller, you are explicitly rendering something, so the default rendering of the action_name.html.erb file doesn't occur.