Wednesday, August 5, 2015

Convert html to pdf using wiked pdf gem(Ruby on Rails)


Today I will write how to convert html to pdf. For this we will use wiked_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 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 wiked functon. like this –
<%= wicked_pdf_stylesheet_link_tag “template1″ -%>
You can define your css file instade 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” funtion.
<% 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.

4 comments:

  1. Another option is to use a API such as GrabzIt's HTML to PDF API. This allows you to freely convert HTML directly to PDF and best of all it uses a browser process for accurate conversion: https://grabz.it/html-to-pdf-image-api.aspx

    ReplyDelete
  2. Let me introduce professionals on the IT market with more than 10 years of experience
    http://serfcompany.com/
    http://itkron.com/en/

    ReplyDelete
  3. Division - This HTML tag is used for defining a section of your document. With the div, you can group large sections of HTML elements together and format them with CSS.
    StartPoint

    ReplyDelete
  4. Templates are available in various types ranging from formula based electronic calculator to a web design. free html5 website templates

    ReplyDelete