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

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

pdf-export

Installation

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

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

To know the installation path of wkhtmltopdf.

Challenges

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.

page_break

To avoid this type of page break, We can use page break avoid css option.

avoid_page_break

 

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.

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 comment