PDF Generation in Merb using HTMLDOC

A good part of this is thanks to this tutorial.

Installation

# Download HTMLDoc from <a href="http://www.htmldoc.org/software.php?VERSION=1.9.x-r1586&FILE=htmldoc/snapshots/htmldoc-1.9.x-r1586.tar.gz">here</a>
      tar zxvf htmldoc-1.9.x-r1586.tar.gz
      cd htmldoc-1.9.x-r1586
      ./configure --prefix=/usr/local
      make
      sudo make install
      

Install gem

sudo gem install htmldoc

sudo gem install htmldoc

Configure merb app

# dependencies.rb
      dependency "htmldoc", "0.2.1"
      
# init.rb
      Merb::BootLoader.after_app_loads do
              # This will get executed after your app's classes have been loaded.
              Merb.add_mime_type(:pdf, :to_pdf, %w[application/pdf], "Content-Encoding" => "gzip")
      end
      

Create an action for the pdf generation

(there must be a way to just put this in the show action instead of a separate action but i had trouble)

# router.rb
      resources :proposals, :collection => { :generate => :get }
      

# router.rb
resources :proposals, :collection => { :generate => :get }

# proposals.rb controller
      def generate(id)
              only_provides :pdf
              pdf = PDF::HTMLDoc.new
              pdf.set_option :bodycolor, :white
              pdf.set_option :toc, false
              pdf.set_option :portrait, true
              pdf.set_option :links, true
              pdf.set_option :webpage, true
              pdf.set_option :left, '2cm'
              pdf.set_option :right, '2cm'
              pdf.set_option :header, "Header here!"
              pdf << "<h1>Title</h1> <p>This is some <strong>bold</strong> text.</p>"
              pdf.footer ".t."
              send_data pdf.generate
      end
      

Then just put a link_to in your view

<%= link_to "Generate PDF", "/proposals/generate/#{@proposal.id}.pdf" %>

<%= link_to "Generate PDF", "/proposals/generate/#{@proposal.id}.pdf" %>

Warning: I was never able to get background images to work. I don’t know if this was a limitation with the htmldoc ruby gem, whether it was something with my htmldoc install, or whether it was a stupid coding mistake on my end.

Picture of Scott Motte

delicious facebook rss twitter

Spitfire Sky | github | archives | resume