Ruby base64 image / pdf encoding decoding

Ganesh Prasad
Aug 4, 2021

To decode a pdf

attachment = response_xml.search(‘Attachment’).first.text
decode_base64_content = Base64.decode64(attachment)
filename = Rails.root.join(‘tmp’, ‘orders’, “#{order.id}-#{SecureRandom.hex(3)}.pdf”)

ensure_tmp_dir_exists_for filename

File.open(filename, ‘wb’) do |f|
f.write(decode_base64_content)
end
filepath = File.open(filename)
File.unlink filename

def ensure_tmp_dir_exists_for(filename)
Dir.mkdir File.dirname(filename)
rescue Errno::EEXIST
end

To encode an image

require "base64"

base64_image = File.open("doc/image.png", "rb") do |file|
Base64.strict_encode64(file.read)
end

--

--