Convert pdf file to base64 string
Asked Answered
C

2

6

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?

Claudell answered 17/6, 2018 at 0:21 Comment(0)
G
13

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"
Gist answered 17/6, 2018 at 7:42 Comment(0)
C
0

The answer from @3елёный didn't work to me - maybe because it's the S3 file.

However I managed to find a way with Paperclip method:

file_data = Paperclip.io_adapters.for(url).read
base_64_file = Base64.encode64(file_data)
Claudell answered 20/6, 2018 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.