Ruby on Rails PDF Stamper / iText

1.8k Views Asked by At

I have done a lot of searching and cannot find a solution for getting PDF-stamper to work in my rails application. From the tutorials it appears that I write a method in the model? I wrote a simple app with two fields: nameLast and nameFirst. All I want to do is write these to a PDF I have that contains fields for user info. Two field happen to be FirstName and LastName so perfect time to use PDF-stamper right? I just want to take user data from the rails application and have then be able to push a button and generate a PDF. Here is the method I have in my model.

  def savePDF
    pdf = PDF::Stamper.new("sample.pdf") 
          pdf.text :nameFirst, "Jason"
               pdf.text :nameLast, "Yates" 
               pdf.save_as "my_output.pdf"
  end

That was clearly taken from a tutorial that I must not properly understand. I can actually get this working in java pretty easy, but I don't want to use jRuby. I am using rjb which is working fine. I just don't think I properly understand what needs to happen to get this working. Any help is greatly appreciated!

2

There are 2 best solutions below

1
On

i was doing the same with use of xfdf as a source data for fields, the following code worked for me, maybe it will be helpful to you aswell:

  pdfreader = Rjb::import('com.itextpdf.text.pdf.PdfReader')
  pdfstamper = Rjb::import('com.itextpdf.text.pdf.PdfStamper')
  pdffields = Rjb::import('com.itextpdf.text.pdf.AcroFields')
  xfdfreader = Rjb::import('com.itextpdf.text.pdf.XfdfReader')


  pdf = pdfreader.new("#{Rails.root}/public/out/temp/form1.pdf", nil)
  xfdf = xfdfreader.new(f)

  stamp = pdfstamper.new(pdf, filestream.new("/tmp/text#{i}.pdf"))
  pdffields = stamp.getAcroFields()
  pdffields.setFields(xfdf)
  stamp.close
0
On

I'm the author of the pdf-stamper gem.

The save_as method saves the created PDF to the filesystem. If you are building a Rails application, I don't think that is what you want.

I'm guessing from your question you want to send a "stamped" PDF back to the browser. If that is the case, you should call to_s on the created PDF and then pass the output of that to Rails send_data method.

In your controller(not the model) you'll want to add some code like this.

def send 
    pdf = PDF::Stamper.new("sample.pdf") 
    pdf.text :nameFirst, "Jason"
    pdf.text :nameLast, "Yates" 
    send_data(pdf.to_s, :filename => "output.pdf", :type => "application/pdf",:disposition => "inline")
end    

The problem here really is the documentation for the pdf-stamper gem. The feature you wanted was there just undocumented, hence your confusion. I'll have to fix that.