Wednesday, June 16, 2010

Rethinking PDF Creation in Ruby

What's the big deal?

  1. HTML+CSS - Assuming you're a web developer, there's a good chance that you already know HTML and can work with it efficiently.
  2. CSS3 - We get WebKit's CSS3 support for free. This means effects like drop shadows, rounded borders, transformations and others are super-easy. (Note: effects requiring blur radius do not work.)
  3. Testing - We have tools built into our normal workflow for testing HTML. You can even use Cucumber to drive the development of a PDF with PDFKit.
To give you an idea of how well this fits into our normal workflow here at Relevance, this is how we built out our PDF reports:
  1. Our designer mocked up a sample PDF and converted it to HTML+CSS.
  2. Using Cucumber to drive development, we created a controller action to generate this HTML view of the PDF. (It was just another URL in our app.)
  3. We added a screen-only stylesheet to the HTML that mimics the look of a PDF reader. This allowed us to get a feel of how it would look as a PDF.
  4. Using a bit of Rack Middleware that ships with PDFKit, we can get the PDF version of that web page by simply appending '.pdf' to the url.
  5. We're done. No crazy extra class to handle PDF rendering. No need to spend all day reading through docs to learn the obscure code and magic incantations required to generate your PDF.

Samples

  • PDF of google.com - PDF rendered from http://google.com
  • CSS3 Examples - Sample rendering of common CSS3 effects including border-radius, text-shadow, box-shadow, and border-image. Notice the lack of a blur radius on text-shadow and box-shadow.
  • Sample HTML page with PDF viewer CSS - Example of using a single HTML source to render both a screen version and a PDF version. Uses a media="screen" and media="all" to mark relevant CSS.
  • PDF generated from PDF viewer HTML - PDF generated from sample HTML above. You must tell PDFKit to only use print stylesheets in order to achieve this effect (PDFKit.new(html, :print_media_type => true)).
http://thinkrelevance.com/blog/2010/06/15/rethinking-pdf-creation-in-ruby.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+relevance-llc+%28Relevance,+Inc.%29&utm_content=Google+Reader

No comments: