Generate PDF Using Rails and Flying Saucer

Author :- Amar Daxini

Rails Pdf Plugin act_as_flying_saucer

There are various ways to generate pdf documents in any language.In Rails we can use prawn library ,HtmlDoc,PrinceXml and many other library,using their api we can generate pdf document.Basically the primary goal is converting HTML web pages to PDF Document,without much changing existing CSS and HTML.


Using the Flying Saucer Project we can achieve this.we can convert HTML + CSS to PDF documents without much changing HTML and CSS. It also support CSS 2 and many properties of CSS 3 for printing Header,Footer,Page Number,Paginated Tables and many more.This Project is built on Java so Java is required on system.


Lets Start How to generate PDF Using Flying Saucer.


 script/plugin install git://github.com/amardaxini/acts_as_flying_saucer.git

This Plugin forked From

http://github.com/dagi3d/acts_as_flying_saucer

Which has older version of flying saucer project.


Next Step after installing plugin add flying_saucer.rb file at config/initializers.


ActsAsFlyingSaucer::Config.options = {
:java_bin => "/usr/bin/java",          # java binary
:classpath_separator => ':',           # classpath separator. unixes system use ':' and windows ';'
:tmp_path => "/tmp"                   # path where temporary files will be stored
}

After Setting Java path , classpath separator and tmp path now do following step.


class PdfController < ActionController::Base
  acts_as_flying_saucer

  def generate_pdf
    render_pdf :template => 'pdf/pdf_template'
  end
end
  render_pdf :file=>'pdf/generate_pdf.html.erb'
  render_pdf :template=>'pdf/generate_pdf.pdf.erb',
             :send_file => { :filename => 'pdfdoc.pdf' }

Add act_as_flying_saucer to controller then render_pdf.

There are various ways to render pdf using ”template” or ”file”,:send_file option use to send pdf file to client side.if we are using any external css file then this css shoulda have media option as 'print'.


<%= stylesheet_link_tag 'pdf' ,:media=>'print' %>

If pdf containing images which generate on the fly.so instead of using


<%= image_tag %>

use

 <img src=" " >

Before rendering PDF validate HTML,like whether all tags are close properly or not.otherwise it gives an parse error.


Now You are ready to Generate PDF. Hurray!!!!!!!!!


How to generate Header, Footer,Page Number and Automation Of HTML Validation will be discussed in next post.