DocRaptor

Adding PDF Generation to Your Rails App

The gem referenced in this document is out of date. Please see our new Ruby gem documentation!

One of our new users recently added DocRaptor to his Rails app. Ryan was kind enough to document his process, and he thought a step-by-step guide for Ruby on Rails would be awesome content for our blog.

We agreed, and we fired up a fresh Rails 4 application to show you just how easy it is to DocRaptor to your own Rails app. Many of our users rely on DocRaptor to create customized reports, which sounds like a great idea for a practical example. Good news – getting started is super easy!

Step One: Add the doc_raptor gem to your gem file

Including the doc_raptor gem is the easiest way to add DocRaptor to your Rails app.

Step Two: Add your API key to an initializer

You’ll need to add your DocRaptor API key to your project, and we recommend adding it to an initializer. This will ensure your API key is initialized when Rails loads, allowing you to easily add document generation to other models. No DocRaptor account? No problem – you can get your API key by signing up here.

Step Three: Define a model for PDF generation

You’ll define a Printable class with a sales method, which generates some dummy data to create a table of sales figures. You can call this method in your controller, then render the result in your view template.

Step Four: Create a controller action to create your PDF

You do this by adding the following code to your controller. Let’s create a PDF using the index action of your PrintablesController. The doc_raptor_send method defined below handles the interaction with DocRaptor to convert the template HTML to PDF.

Step Five: Update your routes

You’ll want to update your routes.rb file so you can properly load the data pulled from your model into your view before converting it into a PDF.

Step Six: Add a template for your PDF

Here’s a sample template that pulls information from your Printable model. This template also adds a button that can be clicked to download a generated PDF of the sales report.

Here’s what our index looks like:

DocRaptor index view

Now you can just click that “Download Report” link, and you’re done! I bet you can’t believe it could be so easy. Fire up a server, head back to your view and click the link in your printables view to generate your PDF. Here’s what this sample generated sales report looks like. Please note: we’re aware it’s woefully understyled.

From here, it’s simply a matter of tweaking your input HTML until you get the PDF you want. You can check out our samples page to get ideas for customizing your PDFs, with features like running headers and footers, custom font support, and dynamically generated tables of contents.

Do you have some crazy use case and you’d like a hand? Do you have a regular use case and you’d still like a hand? Send us an email – we’d love to help!