Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pdf file to base64 string

I have working Paperclip gem in my app for documents (pdf, doc). I need to pass the document to some other third party application via post request.

I tried to convert the paperclip attachment via Base64 but it throws error: no implicit conversion of Tempfile into String

Here is how I did it:

# get url from the paperclip file
url = document.doc.url # https://s3-ap-southeast-1.amazonaws.com/xx-eng/documents/xx/000/000/xx/original/doc.pdf

file_data = open(url)

# Encode the bytes to base64 - this line throw error
base_64_file = Base64.encode64(file_data)

Do you have any suggestion how to avoid the Tempfile error?

like image 665
Petr Avatar asked Jan 02 '23 06:01

Petr


1 Answers

You need to read file first.

base_64_file = Base64.encode64(file_data.read)

Here is working example:

$ bundle exec rails c
=> file = open("tmp/file.pdf")
#> #<File:tmp/receipts.pdf>
=> base_64 = Base64.encode64(file)
#> TypeError: no implicit conversion of File into String
=> base_64 = Base64.encode64(file.read)
#> "JVBERi0xLjQKMSAwIG9iago8PAovVGl0b/BBQEPgQ ......J0ZgozMDM0OQolJUVPRgo=\n"
like image 145
Philidor Avatar answered Jan 05 '23 15:01

Philidor