Tuesday, July 15, 2008

iText with Ruby on Rails using Ruby Java Bridge


(see discussion)
Step 1 :
install JDK 1.5+ and above
Step 2: check JAVA_HOME is set
Step 3: install the rjb gem
gem install rjb -v 1.1.2

see discussion
Step 4: Place iText files in a known directory
Step 5 (optional): check to see from your application if you can access iText (discussion)
ruby script/console # in the working directory of your application
jar = "c:/ruby/iText-2.1.2u.jar"
require 'rjb'
doc = Rjb::import("com.lowagie.text.Document")
Step 6: From your controller call the various iText classes





1 class LettersController < ApplicationController

2 require 'rjb'
3
4 Rjb::load("c:/ruby/iText-2.1.2u.jar;c:/ruby/pdf.jar")
5

6 def download
7 pdfwriterclass = Rjb::import("com.lowagie.text.pdf.PdfWriter")
8 documentclass = Rjb::import("com.lowagie.text.Docuemnt")

9 bytearrayclass = Rjb::import("java.io.ByteArrayOutputStream")
10 paragraphclass = Rjb::import("com.lowagie.text.Paragraph")
11 byteArrayInstance = byteArrayClass.new()

12 document = documentClass.new()
13 writer = pdfWriterClass.getInstance(document,byteArrayInstance)
14 document.open()
15 document.add(paragraphClass.new("Hello!!!"))
16 document.close()

17 fileinbytes = byteArrayInstance.toByteArray()
18 send_data(fileInBytes, {:filename => "Letters For Printing.pdf", :type => "application/pdf"})

19 end
20
21 end
22


(recommended) Please place the
require 'rjb'
in your application.rb

WARNING: Do not call Rjb::load() more than once throughout your application. Put Rjb::load in your application.rb file and then load all your jars there like so Rjb::load(abc.jar;def.jar;ghi.jar).

No comments:

Total Pageviews

Popular Posts