Published On: May 1st, 20241.5 min read

Step-by-step guide to convert HTML to PDF using Wicked PDF

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.

Step 1. Put this on your gem file

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

Step 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 a 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”)

Step 3. You can put a download button like this –

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

Step 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

Step 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.

Step 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.

Contributor: Akhlasur Rahman, Nascenia

Share it, Choose Your Platform!

More to Explore

The Quest for Knowledge Continues. Fuel Your Curiosity.