Class: PDF::Stamper

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf/stamper/rjb.rb,
lib/pdf/stamper.rb,
lib/pdf/stamper/jruby.rb

Overview

PDF::Stamper::RJB

RJB needs the LD_LIBRARY_PATH and JAVA_HOME environment set for it to work correctly. For example on my system:

export LD_LIBRARY_PATH=/usr/java/jdk1.6.0/jre/lib/i386/:/usr/java/jdk1.6.0/jre/lib/i386/client/:./ export JAVA_HOME=/usr/java/jdk1.6.0/

Check the RJB documentation if you are having issues with this.

Constant Summary collapse

VERSION =
"0.3.0"

Instance Method Summary collapse

Constructor Details

#initialize(pdf = nil) ⇒ Stamper

Returns a new instance of Stamper.



21
22
23
24
25
26
27
28
29
# File 'lib/pdf/stamper/rjb.rb', line 21

def initialize(pdf = nil, options = {})
  @bytearray    = Rjb::import('java.io.ByteArrayOutputStream')
  @filestream   = Rjb::import('java.io.FileOutputStream')
  @acrofields   = Rjb::import('com.lowagie.text.pdf.AcroFields')
  @pdfreader    = Rjb::import('com.lowagie.text.pdf.PdfReader')
  @pdfstamper   = Rjb::import('com.lowagie.text.pdf.PdfStamper')

  template(pdf) if ! pdf.nil?
end

Instance Method Details

#image(key, image_path) ⇒ Object

Set a button field defined by key and replaces with an image.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pdf/stamper/rjb.rb', line 39

def image(key, image_path)
  # Idea from here http://itext.ugent.be/library/question.php?id=31 
  # Thanks Bruno for letting me know about it.
  image = Rjb::import('com.lowagie.text.Image')
  img = image.getInstance(image_path)
  img_field = @form.getFieldPositions(key.to_s)

  rectangle = Rjb::import('com.lowagie.text.Rectangle')
  rect = rectangle.new(img_field[1], img_field[2], img_field[3], img_field[4])
  img.scaleToFit(rect.width, rect.height)
  img.setAbsolutePosition(
    img_field[1] + (rect.width - img.getScaledWidth) / 2,
    img_field[2] + (rect.height - img.getScaledHeight) /2
  )

  cb = @stamp.getOverContent(img_field[0].to_i)
  cb.addImage(img)
end

#save_as(file) ⇒ Object

Saves the PDF into a file defined by path given.



45
46
47
48
# File 'lib/pdf/stamper.rb', line 45

def save_as(file)
  f = File.new(file, "w")
  f.syswrite to_s
end

#template(template) ⇒ Object



31
32
33
34
35
36
# File 'lib/pdf/stamper/rjb.rb', line 31

def template(template)
  reader = @pdfreader.new(template)
  @baos = @bytearray.new
  @stamp = @pdfstamper.new(reader, @baos)
  @form = @stamp.getAcroFields()
end

#text(key, value) ⇒ Object

Set a textfield defined by key and text to value.



40
41
42
# File 'lib/pdf/stamper.rb', line 40

def text(key, value)
  @form.setField(key.to_s, value.to_s) # Value must be a string or itext will error.
end

#to_sObject

Takes the PDF output and sends as a string. Basically it’s sole purpose is to be used with send_data in rails.



60
61
62
63
# File 'lib/pdf/stamper/rjb.rb', line 60

def to_s
  fill
  @baos.toByteArray
end