'Error during PDF form population, how do I fix and display pdf?
I am trying to populate a pdf form using the example posted here:
I am trying to answer 2 questions..
- What is causing the error?
- And simply how do I execute this in my user show.html.erb?
#app/pdfs/fillablepdfform.rb
class FillablePdfForm
attr_writer :template_path
attr_reader :attributes
def initialize
fill_out
end
def export(output_file_path=nil)
output_path = output_file_path || "#{Rails.root}/tmp/pdfs/#{SecureRandom.uuid}.pdf" # make sure tmp/pdfs exists
pdftk.fill_form template_path, output_path, attributes
output_path
end
def get_field_names
pdftk.get_field_names template_path
end
def template_path
@template_path ||= "#{Rails.root}/lib/pdf_templates/EmployeeFormFillable.pdf" # makes assumption about template file path unless otherwise specified
end
protected
def attributes
@attributes ||= {}
end
def fill(key, value)
attributes[key.to_s] = value
end
def pdftk
@pdftk ||= PdfForms.new(ENV['PDFTK_PATH'] || '/usr/local/bin/pdftk') # On my Mac, the location of pdftk was different than on my linux server.
Rails.logger.info @pdftk
end
def fill_out
raise 'Must be overridden by child class'
end
end
#app/controllers/testpdfform_controller.rb
class TestpdfformController < FillablePdfForm
def initialize(user)
@user = user
super()
end
protected
def fill_out
[:firstname, :lastname].each do |field|
fill field, @user.send(field)
end
end
end
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
def new
end
def show
@user = User.find(params[:id])
respond_to do |format|
format.pdf { send_file TestPdfForm.new(@user).export, type: 'application/pdf' }
end
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
#flash[:notice] = "Book saved"
redirect_to @user , notice: 'User Saved'
# flash[:notice] = "Book Saved."
#redirect_to action: 'index', notice: 'Book Saved'
else
render :new, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:firstname, :lastname)
end
end
#config/initializers/mime_types.rb
Mime::Type.register "application/pdf", :pdf
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

