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.html
       format.pdf do
       render :pdf => “file.pdf”, :template => ‘basic_infos/show.html.erb’
       end
       end

———— OR ————

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

       respond_to do |format|
       format.html
       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”)
       end
       end

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
       else
       image_tag “file://#{Rails.root.join(‘public’, img)}”, options
       end
       end

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

Contributor: Akhlasur Rahman, Nascenia

Published On: October 9th, 2018 / Categories: Career tips / Tags: , /