Convert HTML to PDF in Ruby on Rails Applications – Part-I

Siva KB

1 min read

Recently I worked for a project, in which we got a requirement of generating many pages of PDF which has text, table, Images,Graph and so on.We chose to go with Wkhtmmltopdf library which really makes our life easier, I heard about Prawn gem, which many people suggested where i will have more control, but I found it is possible with Wkhtmmltopdf itself.

In this blog i am going to share my experience and challenges I faced while converting html to pdf using wicked_pdf and how i resolved them.Wicked Pdf is a ruby wrapper for Wkhtmmltopdf binary


You can download/install latest version of wkhtmltopdf form the official site wkhtmltopdf, or else you can also install that from the command line.

sudo add-apt-repository ppa:ecometrica/servers
sudo apt-get update
sudo apt-get install wkhtmltopdf

After installing wkhtmltopdf into our system you need to specify the executable path to Wicked pdf gem. Add the below code into the initializer file(config/initializers/wicked_pdf.rb).

WickedPdf.config = {
  exe_path: '/usr/local/bin/wkhtmltopdf'

To know the installation path of wkhtmltopdf.

which wkhtmltopdf


Challenges we faced while converting html to pdf

  • Page break
  • Bootstrap css load
  • Displaying chart
  • Mixed page orientations

Page break

Some of the time page break can occur in the middle of a table row or paragraph content, this will really make the pdf look worse, the table won’t be properly closed and there will be some break in the text too.
There are two scenearios where we need a page break
1) Break a table
2) Break any content(Image/ Text) and make it appear in the next page

1) Break a table

See how the table is broken in the middle of a table row.
To avoid this type of page break, We can use page break avoid css option.

tr { page-break-inside: avoid; }


2) Break any content(Image/ Text) and make it appear in the next page

Always you want some chart/content need to print in new page rather than the existing page, you can use the below one to achieve that.

.sample-image { page-break-before: always; }

I will share the remaining challenges and resolutions in following blogs. Share if you found this useful. Follow @spritlesoftware for more updates.

Related posts:

Leave a Reply

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