Wicked PDF uses shell utility wkhtmltopdf to serve a PDF file to a user from HTML. In other words, you simply write an HTML view as you would normally, then wicked PDF takes care of other stuff.
wicked PDF works on Ruby versions 1.8.7 through 2.3; Rails 2 through 5.0
To use Wicked PDF, first install wkhtmltopdf. Alternatively, you could use the wkhtmltopdf-binary gem by including it in your Gemfile.
Add following gems to your Gemfile and run bundle install.
gem 'wicked_pdf' gem 'wkhtmltopdf-binary'
Register the PDF mime type in config/initializers/mime_types.rb
Mime::Type.register "application/pdf", :pdf
Wicked PDF comes with a middleware that allows user to get a PDF view of any page on your site by appending .pdf to the URL. This is achived by adding
to the /config/application.rb file.
We can create template and layout files for the PDF, and modify controller action to handle PDF-format request.
Modify the controller as shown. Here, I am specifying the name of the PDF file.
class SalaryFilesController def download respond_to do |forma| format.pdf do render pdf: "SalarySlip" #Excluding .pdf extension end end
and template file: download.pdf.haml
= wicked_pdf_stylesheet_link_tag "salary_files", media: "all" .container %table %tr %td = wicked_pdf_image_tag('kiprosh_pdf_logo.png', id:"pdf-logo")
Here I have used following Wicked helpers
There is one more helper as follows
Using the regular
If you want t just crete a pdf and not display it:
#create a pdf from a string pdf = WickedPdf.new.pdf_from_string('<h1>Hello world!</h1>')
Or from your controller using views ad templates and save to a file
pdf = render_to_string pdf: "some_file_name", temlate: "templates/pdf" save_path = Rails.roor.join('pdfs', 'filename.pdf') File.open(sve_path, 'wb') do |file| file << pdf end
Subscribe to Engineering At Kiprosh
Get the latest posts delivered right to your inbox