tags:

views:

236

answers:

1

Is there an easy way to display powers in PDF generated using the Ruby PDF::Writer library? I realize that I can just print the exponent a bit higher than the base number, however I thought maybe there is some easier way to do this... such as a markup tag of some sort.

Basically, I want to cleanly display x**-2.

Thanks in advance!

+3  A: 

I wrote up a quick algorithm to do what I need to do. Hopefully it will work for you as well. The only requirement is that you use PDF::Writer. The method below is using PDF::Writer and Ruport. However, if you aren't using Ruport, the only thing you need to change is the "draw_text" method. Substitute it with the PDF::Writer "text" method.

def draw_text_with_exponent(text, left, font_size)
 exponent_offset = 1
 font_size_reduction = 5

 words = text.split(" ")

 buffer = ""
 words.each() do |word|
  if (word.gsub("**", '') == word)
   buffer += word + " "
  else
   number = word.split("**")
   base = number[0]
   exponent = number[1]

   buffer += base
   draw_text(buffer, :left => left, :font_size => font_size)
   left += pdf_writer.text_line_width(buffer, font_size)

   pdf_writer.y+=exponent_offset
   draw_text(exponent, :left => left, :font_size => font_size - font_size_reduction)
   left += pdf_writer.text_line_width(exponent, font_size)
   buffer = ""
   pdf_writer.y-=exponent_offset
  end
 end

 if (buffer.length > 0)
  draw_text(buffer, :left => left, :font_size => font_size)
 end
end

Here is an example call:

draw_text_with_exponent("The numbers are x**2 and y**3 ok?", 50, 11)

Let me know if you have any trouble with this method or you find an answer to my original question.

-JP

JP