Company

Support

How to Generate PDFs With Ruby on Rails

The best approach for generating PDFs in Rails really depends on the types of PDFs you need to generate. This tutorial will provide step-by-step instructions for generating PDFs by using wkhtmltopdf, an open source CLI for rendering HTML into PDF from standard Rails view and style code. This approach is ideal if you don't need a publishing workflow or precise control over page output.

For the purpose of this tutorial I've made a simple demo application on Heroku to show you what we'll be building. The application lists a series of sample invoices that can be previewed in the browser, and then converted to PDF. The source code is available in our repo rails-generate-pdf. Here's my configuration:

Rails 5.2.1
Postgresql 10.5
wkhtmltopdf 0.12.4
macOS Mojave 10.14.1

If you're looking for more granular control over PDF output, wkhtmltopdf may not be the best. Instead, Prawn is a popular open source pure Ruby PDF generation library that is reasonably performant and uses a X,Y coordinate system for placing elements on a page. The downside is you'll need time to wrap your head around its rendering model, and learn its DSL (Domain Specific Language). Alternatively, you could use a commercial PDF generation library (like PDFTron PDF SDK).

Start by downloading and installing Wicked PDF's precompiled binary. You can test the output by converting a URL into a PDF file by opening the command line and typing this:

wkthmltopdf http://google.com google.pdf

This will generate the file google.pdf.

But, how do we use this in our Ruby on Rails projects?

Wicked PDF uses the shell utility wkhtmltopdf to serve a PDF file from HTML. Rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally do, then let Wicked PDF take care of the hard stuff.

The show action has 2 formats (html and pdf), which will be used to define how the content is rendered. For example, if you access the invoice directly without the .pdf extension, you'll see an HTML preview, while adding the .pdf extension will render it to PDF. Try it here:

Using wkhtmltopdf is a quick and easy way to generate PDFs from Ruby. However, if you need to generate PDFs from something other than HTML, want to integrate this into a workflow, or need precise control over positioning, then you're out of luck with wkhtmltopdf.

Additionally, wkhtmltopdf is based on the QtWebKit rendering engine, which is based on Apple's WebKit (which is a fork of KDE's KHTML). These engines are best suited for simple documents where you can afford to have some inconsistencies or failures.

For more robust functionality and reliable generation of PDF, PDFTron SDK supports Ruby (as well as many other languages and frameworks). Check out some of the Ruby code samples to help get you up and running quickly.

If you have any questions about PDFTron's PDF SDK, please feel free to get in touch!