Convert html to PDF using wicked PDF gem(Ruby on Rails)

January 27, 2017
admin

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

<td><%= link_to ‘Download CV’, basic_info_path(basic_info, :format => :pdf) , :format => :pdf %></td>
<td><%= link_to ‘Preview CV’, basic_info_path(basic_info) %></td>

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

<%= wicked_pdf_stylesheet_link_tag “template1″ -%>

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.

       <% if @basic_info.avatar.present? %>
       <% if request.format == ‘application/pdf’ %>
       <%= wicked_pdf_image_tag @basic_info.avatar.to_s %>
       <% else %>
       <%= image_tag @basic_info.avatar.to_s %>
       <% end %>
       <% end %>

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.

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.