We have recently done a few projects that required providing a PDF version of a page of reporting data.

Fortunately we were able to use the WickedPdf plugin (https://github.com/mileszs/wicked_pdf) to create the PDFs quickly and easily.

Here are some lessons that we learned while working with it.

1. Installing wkhtmltopdf

WickedPDF depends on wkhtmltopdf. There are a few different ways of installing it on Linux. One or more of these should work for you.

  1. 		
            # wkhtmltopdf-binary gem
    	$ sudo gem install wkhtmltopdf-binary # rvmsudo if using rvm
    	or
    	gem 'wkhtmltopdf-binary' # in Gemfile
    
    	Test the install of wkhtmltopdf
    	$ wkhtmltopdf --help
    
    
  2. 		sudo apt-get install wkhtmltopdf  # ubuntu/debian
  3. Download the static version

    		# http://code.google.com/p/wkhtmltopdf/downloads/list
    	# from http://www.linkme.com.au/ui/unregistered/blogs/BlogPost.aspx?postId=72fc2553cfe3454bb11c00c16c583638
    	sudo aptitude install openssl build-essential xorg libssl-dev
    
    	#for 64bits OS
    	$ wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
    	$ tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
    	$ chown root:root wkhtmltopdf-amd64
    	$ mv wkhtmltopdf-amd64 /usr/bin/wkhtmltopdf
    
    	#for 32bits OS
    	$ wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
    	$ tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
    	$ chown root:root wkhtmltopdf-i386
    	$ mv wkhtmltopdf-i386 /usr/bin/wkhtmltopdf
    

2. Install WickedPDF

rails plugin install git://github.com/mileszs/wicked_pdf.git

Find out where wkhtmltopdf was installed

$ which `wkhtmltopdf`

Set the path to wkhtmltopdf

# config/initializers/wicked_pdf.rb
WickedPdf.config = {
  :exe_path => '/path/to/wkhtmltopdf'
}

3. Render PDF


		# controllers/welcome_controller.rb
		def index
		  respond_to do |format|
		    format.html
		    format.pdf do
		      render :pdf => "my_pdf", # pdf will download as my_pdf.pdf
		        :layout => 'pdf', # uses views/layouts/pdf.haml
		    :show_as_html => params[:debug].present? # renders html version if you set debug=true in URL
		      end
		    end
		  end
		end

Take a look at a sample app for this on github

Bugs/Limitations

I wasn't able to get Javascript working with PDF. So if the page depends on Javascript, it won't render. I also had a problem getting the stylesheet helpers working. I had to inline all the css and then it worked.

 

If you found this blog piece to be helpful, feel free to add this snippet to your own site so that others may benefit from it: 

<a href="http://www.lucidity.ie/blog/33-generating-pdfs-using-wicked-pdf-in-ruby-on-rails">Web Development company</a>

 
 
Web Design