gettalong / hexapdf

Versatile PDF creation and manipulation for Ruby
https://hexapdf.gettalong.org
Other
1.21k stars 69 forks source link

Previously added text disappears when new text is added #263

Closed work-wajeeh closed 11 months ago

work-wajeeh commented 11 months ago

I've a model LibraryDocument and I'm using following method to add text to the pdf document. It just keeps the most recent text added to the document and previous changes are removed. Not sure what I'm missing here


def add_text(text, pos=[100,100])
  downloadPDF = Tempfile.new('download_pdf')
  File.open(downloadPDF.path, "w") do |f|
    document_path = Addressable::URI.parse(doc_url).normalize.to_s
    IO.copy_stream(URI.open(document_path), f)
  end
  doc = HexaPDF::Document.open(downloadPDF)
  (doc.pages[0]).canvas(type: :overlay).font('Helvetica', size: 12).fill_color(0,0,0).text(text, at: pos)
  io = StringIO.new(''.b)
  doc.write(io)

  t = Tempfile.new("test_temp")
  t.write(io.string)
  t.rewind

  # upload to S3
  filesize = File.size(t.path)
  wsS3 = Aws::S3::Resource.new(:region => "us-east-1")
  key = document.url #document is an instance of LibraryDocument
  s3obj = wsS3.bucket($UPLOADBUCKET).object(key)
  s3obj.upload_file(t.path, :acl => "public-read", :content_type => "application/pdf")
  t.close
  t.unlink
end
gettalong commented 11 months ago

I'm not sure what you are doing in that method, to be honest. You are writing the PDF document to the StringIO instance named io but after that you don't use that variable anymore, effectively throwing away the written PDF document.

Could you please clarify?

work-wajeeh commented 11 months ago

@gettalong my bad. I'm using io to write into the TempFile object t t.write(io.string) I've update the code. Apologies

gettalong commented 11 months ago

Okay, a few points that should make the code easier to follow:

There is nothing wrong with HexaPDF here. Maybe you are downloading the original file instead of the modified one?