Pages

Monday 15 July 2013

Generate a PDF in ruby on rails (ROR) using 'gem pdfKit'

PDFKit is basically a gem which is used to genrate the pdf reports.PDFkit basically accepts the HTML as Input and Pdf Report of that HTML as output.
Steps To Install PDFkit
  • Firstlly add this line to your gemlist
    `gem 'pdfkit'`
  • Then install wkhtmltopdf library
  • Wkhtmltopdf is an open source project that uses the WEBkit rendering engine to convert HTML to native PDF code.
    `gem install wkhtmltopdf-binary`
  • And install wkhtmltopdf to your system by hand
    `https://github.com/pdfkit/pdfkit/wiki/Installing-WKHTMLTOPDF`
  • Now bundle install
  • Check the wkhtmltopdf installed write 'which wkhtmltopdf' to console
  • Write PDFKit.new in your code and then pass HTML and wkhtmltopdf options as parameters.
  • To check the wkhtmltopdf options run `wkhtmltopdf –extended-help`
    kit = PDFKit.new(html,  :page_size => 'Letter')
    :page_size is wkhtmltopdf option,  html is simple basic html
  • You can also give stylesheets to your pdf like 
      kit.stylesheets << '/path/to/css/file'
  • For save the pdf as file
      file =  kit.to_file('/path/to/save/pdf')
  • We can also pass url's for generating the pdf likekit = PDFKit.new('http://google.com')
    Note: if we give url then we can not add stylesheets
  • You installed wkhtmltopdf by hand to a location other than /usr/local/bin you will need to tell PDFKit where the binary is
    write this code in enviornment.rb
    PDFKit.configure do |config|
      config.wkhtmltopdf = '/path/to/wkhtmltopdf'
      config.default_options = {
      :page_size => 'Legal',
      :print_media_type => true
      }