Published On: January 27th, 20171.5 min read

Contributor: Akhlasur Rahman, Nascenia

Convert html to pdf using wiked pdf gem | Nascenia

Today I will write how to convert HTML to pdf. For this, we will use the wicked_pdf gem. It’s a nice gem to convert.

1. put this on your gem file

       gem ‘wicked_pdf’, github: ‘mileszs/wicked_pdf’
       gem ‘wkhtmltopdf-binary’

2. Then on the controller, you can write this(if u want to generate pdf file on the browser).
here you must define which template do u want to make pdf. here I write basic_infos/show.html.erb

       respond_to do |format|
       format.pdf do
       render :pdf => “file.pdf”, :template => ‘basic_infos/show.html.erb’

———— OR ————

If u want to make force download link, you can write like this –

       respond_to do |format|
       format.pdf do
       @pdf = render_to_string :pdf => “mashpy”, :template => ‘basic_infos/show.html.erb’, :encoding => “UTF-8″
       send_data(@pdf, :filename => “mashpy”, :type=>”application/pdf”)

3. You can put a download button like this –

 :pdf) , :format => :pdf %>



4. on the template you have to embed CSS file using the wicked function. like this –

You can define your CSS file instead of template1

5. Also to show images on the pdf you have to use wicked_pdf_image_tag. here you can see I also used “to_s” function.


6. Then on the helper, you have to write like this –

       def wicked_pdf_image_tag(img, options={})
       if img[0].chr == “/” # images from paperclip
       new_image = img.slice 1..-1
       image_tag “file://#{Rails.root.join(‘public’, new_image)}”, options
       image_tag “file://#{Rails.root.join(‘public’, img)}”, options

By this process, you can easily convert HTML to pdf.

Share it, Choose Your Platform!

More to Explore

The Quest for Knowledge Continues. Fuel Your Curiosity.