gdelugre / origami

Origami is a pure Ruby library to parse, modify and generate PDF documents.
GNU Lesser General Public License v3.0
326 stars 110 forks source link

Add watermark and signature to existing pdf #68

Open harabbi opened 4 years ago

harabbi commented 4 years ago

I've been trying to take an existing PDF file, add a watermark to it ("downloaded by X user at time Y"), modify the metadata, and then sign the file with my existing RSA key, but I can't for the life of me get it to work.

I'm using Prawn and CombinePDF to add watermark to the file because I couldn't get the watermark to write to the pages, and when I tried to create a new PDF with "fresh" metadata, the metadata from the parsed file always came through.

Also, I'm not trying to write the file to disk, I just want to pass it as a stream using Rails' send_data, so I've got some of the process worked out, but can't figure out the rest. Should this block work?

def generate_signed_pdf(original_pdf_path)
    info = {
      Title: 'this is my title',
      RetrievedBy: 'some user'
    }
    pdf = Origami::PDF.read(original_pdf_path)
    pdf.each_page do |page|
      page.write('This is my add on', x: 100, y: 10, rendering: Origami::Text::Rendering::FILL, size: 10)
    end
    pdf.create_metadata(info)
    pdf.sign(cert, key) # cert and key exist, just edited down the block a bit
    buffer = StringIO.new
    pdf.write(buffer)
    buffer.rewind
    buffer
end
UniqueTokens commented 3 years ago

The last row should be buffer.read