Looking for a really confusing and cryptic layout language for generating PDFs through your rails app? If you enjoy nonsensical markup languages and have the urge to read poorly written how-to documents from 1995, say hello to LaTeX! Unfortunately LaTeX can be slightly difficult to configure, but with a little help from apt-get, you can make your life easier.
Packages Needed on Ubuntu
I’ve tried the following on Ubuntu Intrepid Ibex 8.10 but I would imagine that it works on other recent versions as well.
First let’s search for available texlive related packages
$> apt-cache search ^texlive texlive - TeX Live: A decent selection of the TeX Live packages texlive-base - TeX Live: Essential programs and files texlive-base-bin - TeX Live: Essential binaries texlive-base-bin-doc - TeX Live: Documentation files for texlive-base-bin texlive-bibtex-extra - TeX Live: Extra BibTeX styles texlive-common - TeX Live: Base component ... snip... texlive-plain-extra - TeX Live: Plain TeX supplementary packages texlive-science - TeX Live: Typesetting for natural and computer sciences
You’ll notice that there are a lot of packages available. Now, you could go through and probably piece together the exact set of packages you need, or you could just do this…
$> apt-get install texlive-full
This will install everything, docs, languages, fonts, advanced math typesetting, you’ll even be able to generate PDFs in Mongolian. All of the packages together are about 1.1GB, and it takes a long time to download/build, but avoiding the apt-get hassle is worth it.
RTex Gem for Rails Support
If you’re planning on using a LaTeX template to generate a PDF in your rails app, you’ll need to make use of the RTeX gem. Once you’ve got the RTeX gem installed, create the view for your ActiveRecord model.
In this example application, we have an invoice model. We want an employee to be able to view the LaTeX generated invoice by accessing something like http://localhost:3000/invoices/1.pdf
Our controller is pretty straightforward.
1 2 3 4 5 | class InvoiceController < ActionController::Base def show @invoice = Invoice.find(params[:id]) end end |
Next we need to create a view that will store the LaTeX markup that creates our PDF.
$> touch app/views/invoices/show.pdf.rtex
Once you’ve pulled your hair out writing the LaTeX markup required to get the invoice PDF looking the way you want, save the LaTeX to the show file you’ve just created in app/views/invoices/show.pdf.rtex
Drink a Beer
You should now be able to access your pretty LaTeX formatted PDF invoice @ http://localhost:3000/invoices/1.pdf
